Completed
Push — master ( d7b90c...c585c5 )
by Yannick
31:05
created

update_db::update_ModeS()   C

Complexity

Conditions 7
Paths 30

Size

Total Lines 32
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 30
nop 0
dl 0
loc 32
rs 6.7272
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
		global $globalProxy, $globalForceIPv4;
15
		$fp = fopen($file, 'w');
16
		$ch = curl_init();
17
		curl_setopt($ch, CURLOPT_URL, $url);
18
		if (isset($globalForceIPv4) && $globalForceIPv4) {
19
			if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
20
				curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
21
			}
22
		}
23
		if (isset($globalProxy) && $globalProxy != '') {
24
			curl_setopt($ch, CURLOPT_PROXY, $globalProxy);
25
		}
26
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
27
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
28
		curl_setopt($ch, CURLOPT_TIMEOUT, 20);
29
		if ($referer != '') curl_setopt($ch, CURLOPT_REFERER, $referer);
30
		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');
31
		curl_setopt($ch, CURLOPT_FILE, $fp);
32
		curl_exec($ch);
33
		curl_close($ch);
34
		fclose($fp);
35
	}
36
37
	public static function gunzip($in_file,$out_file_name = '') {
38
		//echo $in_file.' -> '.$out_file_name."\n";
39
		$buffer_size = 4096; // read 4kb at a time
40
		if ($out_file_name == '') $out_file_name = str_replace('.gz', '', $in_file); 
41
		if ($in_file != '' && file_exists($in_file)) {
42
			// PHP version of Ubuntu use gzopen64 instead of gzopen
43
			if (function_exists('gzopen')) $file = gzopen($in_file,'rb');
44
			elseif (function_exists('gzopen64')) $file = gzopen64($in_file,'rb');
45
			else {
46
				echo 'gzopen not available';
47
				die;
48
			}
49
			$out_file = fopen($out_file_name, 'wb'); 
50
			while(!gzeof($file)) {
51
				fwrite($out_file, gzread($file, $buffer_size));
52
			}  
53
			fclose($out_file);
54
			gzclose($file);
55
		}
56
	}
57
58
	public static function unzip($in_file) {
59
		if ($in_file != '' && file_exists($in_file)) {
60
			$path = pathinfo(realpath($in_file), PATHINFO_DIRNAME);
61
			$zip = new ZipArchive;
62
			$res = $zip->open($in_file);
63
			if ($res === TRUE) {
64
				$zip->extractTo($path);
65
				$zip->close();
66
			} else return false;
67
		} else return false;
68
	}
69
	
70
	public static function connect_sqlite($database) {
71
		try {
72
			self::$db_sqlite = new PDO('sqlite:'.$database);
73
			self::$db_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
74
		} catch(PDOException $e) {
75
			return "error : ".$e->getMessage();
76
		}
77
	}
78
	
79
	public static function retrieve_route_sqlite_to_dest($database_file) {
80
		global $globalDebug, $globalTransaction;
81
		//$query = 'TRUNCATE TABLE routes';
82
		if ($globalDebug) echo " - Delete previous routes from DB -";
83
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
84
		$Connection = new Connection();
85
		try {
86
			//$Connection = new Connection();
87
			$sth = $Connection->db->prepare($query);
88
                        $sth->execute(array(':source' => $database_file));
89
                } catch(PDOException $e) {
90
                        return "error : ".$e->getMessage();
91
                }
92
93
    		if ($globalDebug) echo " - Add routes to DB -";
94
    		update_db::connect_sqlite($database_file);
95
		//$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';
96
		$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";
97
		try {
98
                        $sth = update_db::$db_sqlite->prepare($query);
99
                        $sth->execute();
100
                } catch(PDOException $e) {
101
                        return "error : ".$e->getMessage();
102
                }
103
		//$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)';
104
		$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,ToAirport_ICAO,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
105
		$Connection = new Connection();
106
		$sth_dest = $Connection->db->prepare($query_dest);
107
		try {
108
			if ($globalTransaction) $Connection->db->beginTransaction();
109
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
110
				//$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);
111
				$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);
112
				$sth_dest->execute($query_dest_values);
113
            		}
114
			if ($globalTransaction) $Connection->db->commit();
115
		} catch(PDOException $e) {
116
			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...
117
			return "error : ".$e->getMessage();
118
		}
119
                return '';
120
	}
121
	public static function retrieve_route_oneworld($database_file) {
122
		global $globalDebug, $globalTransaction;
123
		//$query = 'TRUNCATE TABLE routes';
124
		if ($globalDebug) echo " - Delete previous routes from DB -";
125
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
126
		$Connection = new Connection();
127
		try {
128
			//$Connection = new Connection();
129
			$sth = $Connection->db->prepare($query);
130
                        $sth->execute(array(':source' => 'oneworld'));
131
                } catch(PDOException $e) {
132
                        return "error : ".$e->getMessage();
133
                }
134
135
    		if ($globalDebug) echo " - Add routes to DB -";
136
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
137
		$Spotter = new Spotter();
138
		if ($fh = fopen($database_file,"r")) {
139
			$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)';
140
			$Connection = new Connection();
141
			$sth_dest = $Connection->db->prepare($query_dest);
142
			if ($globalTransaction) $Connection->db->beginTransaction();
143
			while (!feof($fh)) {
144
				$line = fgetcsv($fh,9999,',');
145
				if ($line[0] != '') {
146
					if (($line[2] == '-' || ($line[2] != '-' && (strtotime($line[2]) > time()))) && ($line[3] == '-' || ($line[3] != '-' && (strtotime($line[3]) < time())))) {
147
						try {
148
							$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');
149
							$sth_dest->execute($query_dest_values);
150
						} catch(PDOException $e) {
151
							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...
152
							return "error : ".$e->getMessage();
153
						}
154
					}
155
				}
156
			}
157
			if ($globalTransaction) $Connection->db->commit();
158
		}
159
                return '';
160
	}
161
	
162
	public static function retrieve_route_skyteam($database_file) {
163
		global $globalDebug, $globalTransaction;
164
		//$query = 'TRUNCATE TABLE routes';
165
		if ($globalDebug) echo " - Delete previous routes from DB -";
166
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
167
		$Connection = new Connection();
168
		try {
169
			//$Connection = new Connection();
170
			$sth = $Connection->db->prepare($query);
171
                        $sth->execute(array(':source' => 'skyteam'));
172
                } catch(PDOException $e) {
173
                        return "error : ".$e->getMessage();
174
                }
175
176
    		if ($globalDebug) echo " - Add routes to DB -";
177
178
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
179
		$Spotter = new Spotter();
180
		if ($fh = fopen($database_file,"r")) {
181
			$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)';
182
			$Connection = new Connection();
183
			$sth_dest = $Connection->db->prepare($query_dest);
184
			try {
185
				if ($globalTransaction) $Connection->db->beginTransaction();
186
				while (!feof($fh)) {
187
					$line = fgetcsv($fh,9999,',');
188
					if ($line[0] != '') {
189
						$datebe = explode('  -  ',$line[2]);
190
						if (strtotime($datebe[0]) > time() && strtotime($datebe[1]) < time()) {
191
							$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');
192
							$sth_dest->execute($query_dest_values);
193
						}
194
					}
195
				}
196
				if ($globalTransaction) $Connection->db->commit();
197
			} catch(PDOException $e) {
198
				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...
199
				return "error : ".$e->getMessage();
200
			}
201
		}
202
                return '';
203
	}
204
	public static function retrieve_modes_sqlite_to_dest($database_file) {
205
		global $globalTransaction;
206
		//$query = 'TRUNCATE TABLE aircraft_modes';
207
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
208
		try {
209
			$Connection = new Connection();
210
			$sth = $Connection->db->prepare($query);
211
                        $sth->execute(array(':source' => $database_file));
212
                } catch(PDOException $e) {
213
                        return "error : ".$e->getMessage();
214
                }
215
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
216
		try {
217
			$Connection = new Connection();
218
			$sth = $Connection->db->prepare($query);
219
                        $sth->execute(array(':source' => $database_file));
220
                } catch(PDOException $e) {
221
                        return "error : ".$e->getMessage();
222
                }
223
224
    		update_db::connect_sqlite($database_file);
225
		$query = 'select * from Aircraft';
226
		try {
227
                        $sth = update_db::$db_sqlite->prepare($query);
228
                        $sth->execute();
229
                } catch(PDOException $e) {
230
                        return "error : ".$e->getMessage();
231
                }
232
		//$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)';
233
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
234
		
235
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
236
		
237
		$Connection = new Connection();
238
		$sth_dest = $Connection->db->prepare($query_dest);
239
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
240
		try {
241
			if ($globalTransaction) $Connection->db->beginTransaction();
242
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
243
			//$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']);
244
				if ($values['UserString4'] == 'M') $type = 'military';
245
				else $type = null;
246
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
247
				$sth_dest->execute($query_dest_values);
248
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
249
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
250
				    $sth_dest_owner->execute($query_dest_owner_values);
251
				}
252
            		}
253
			if ($globalTransaction) $Connection->db->commit();
254
		} catch(PDOException $e) {
255
			return "error : ".$e->getMessage();
256
		}
257
258
		// Remove data already in DB from ACARS
259
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
260
		try {
261
			$Connection = new Connection();
262
			$sth = $Connection->db->prepare($query);
263
                        $sth->execute(array(':source' => $database_file));
264
                } catch(PDOException $e) {
265
                        return "error : ".$e->getMessage();
266
                }
267
		return '';
268
	}
269
270
	public static function retrieve_modes_flarmnet($database_file) {
271
		global $globalTransaction;
272
		$Common = new Common();
273
		//$query = 'TRUNCATE TABLE aircraft_modes';
274
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
275
		try {
276
			$Connection = new Connection();
277
			$sth = $Connection->db->prepare($query);
278
                        $sth->execute(array(':source' => $database_file));
279
                } catch(PDOException $e) {
280
                        return "error : ".$e->getMessage();
281
                }
282
		
283
		if ($fh = fopen($database_file,"r")) {
284
			//$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)';
285
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
286
		
287
			$Connection = new Connection();
288
			$sth_dest = $Connection->db->prepare($query_dest);
289
			try {
290
				if ($globalTransaction) $Connection->db->beginTransaction();
291
            			while (!feof($fh)) {
292
            				$values = array();
293
            				$line = $Common->hex2str(fgets($fh,9999));
294
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
295
            				$values['ModeS'] = substr($line,0,6);
296
            				$values['Registration'] = trim(substr($line,69,6));
297
            				$aircraft_name = trim(substr($line,48,6));
298
            				// Check if we can find ICAO, else set it to GLID
299
            				$aircraft_name_split = explode(' ',$aircraft_name);
300
            				$search_more = '';
301
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
302
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
303
            				$sth_search = $Connection->db->prepare($query_search);
304
					try {
305
                                    		$sth_search->execute();
306
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
307
	            				//if (count($result) > 0) {
308
	            				if (isset($result['icao']) && $result['icao'] != '') {
309
	            				    $values['ICAOTypeCode'] = $result['icao'];
310
	            				} 
311
					} catch(PDOException $e) {
312
						return "error : ".$e->getMessage();
313
					}
314
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
315
					// Add data to db
316
					if ($values['Registration'] != '' && $values['Registration'] != '0000') {
317
						//$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']);
318
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':source_type' => 'flarm');
319
						//print_r($query_dest_values);
320
						$sth_dest->execute($query_dest_values);
321
					}
322
				}
323
				if ($globalTransaction) $Connection->db->commit();
324
			} catch(PDOException $e) {
325
				return "error : ".$e->getMessage();
326
			}
327
		}
328
329
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
330
		try {
331
			$Connection = new Connection();
332
			$sth = $Connection->db->prepare($query);
333
                        $sth->execute(array(':source' => $database_file));
334
                } catch(PDOException $e) {
335
                        return "error : ".$e->getMessage();
336
                }
337
		return '';
338
	}
339
340
	public static function retrieve_modes_ogn($database_file) {
341
		global $globalTransaction;
342
		//$query = 'TRUNCATE TABLE aircraft_modes';
343
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
344
		try {
345
			$Connection = new Connection();
346
			$sth = $Connection->db->prepare($query);
347
                        $sth->execute(array(':source' => $database_file));
348
                } catch(PDOException $e) {
349
                        return "error : ".$e->getMessage();
350
                }
351
		
352
		if ($fh = fopen($database_file,"r")) {
353
			//$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)';
354
			$query_dest = 'INSERT INTO aircraft_modes (LastModified,ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:lastmodified,:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
355
		
356
			$Connection = new Connection();
357
			$sth_dest = $Connection->db->prepare($query_dest);
358
			try {
359
				if ($globalTransaction) $Connection->db->beginTransaction();
360
				$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...
361
            			while (!feof($fh)) {
362
            				$line = fgetcsv($fh,9999,',',"'");
363
            				
364
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
365
					//print_r($line);
366
            				$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...
367
            				$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...
368
            				$values['ICAOTypeCode'] = '';
369
            				$aircraft_name = $line[2];
370
            				// Check if we can find ICAO, else set it to GLID
371
            				$aircraft_name_split = explode(' ',$aircraft_name);
372
            				$search_more = '';
373
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
374
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
375
            				$sth_search = $Connection->db->prepare($query_search);
376
					try {
377
                                    		$sth_search->execute();
378
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
379
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
380
					} catch(PDOException $e) {
381
						return "error : ".$e->getMessage();
382
					}
383
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
384
					// Add data to db
385
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
386
						//$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']);
387
						$query_dest_values = array(':lastmodified' => date('Y-m-d H:m:s'),':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':source_type' => 'flarm');
388
						//print_r($query_dest_values);
389
						$sth_dest->execute($query_dest_values);
390
					}
391
				}
392
				if ($globalTransaction) $Connection->db->commit();
393
			} catch(PDOException $e) {
394
				return "error : ".$e->getMessage();
395
			}
396
		}
397
398
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
399
		try {
400
			$Connection = new Connection();
401
			$sth = $Connection->db->prepare($query);
402
                        $sth->execute(array(':source' => $database_file));
403
                } catch(PDOException $e) {
404
                        return "error : ".$e->getMessage();
405
                }
406
		return '';
407
	}
408
409
	public static function retrieve_owner($database_file,$country = 'F') {
410
		global $globalTransaction, $globalMasterSource;
411
		//$query = 'TRUNCATE TABLE aircraft_modes';
412
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source; DELETE FROM aircraft_modes WHERE Source = :source;";
413
		try {
414
			$Connection = new Connection();
415
			$sth = $Connection->db->prepare($query);
416
                        $sth->execute(array(':source' => $database_file));
417
                } catch(PDOException $e) {
418
                        return "error : ".$e->getMessage();
419
                }
420
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
421
		$Spotter = new Spotter();
422
		if ($fh = fopen($database_file,"r")) {
423
			//$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)';
424
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
425
		        $query_modes = 'INSERT INTO aircraft_modes (ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:modes,:modescountry,:registration,:icaotypecode,:source)';
426
		        
427
			$Connection = new Connection();
428
			$sth_dest = $Connection->db->prepare($query_dest);
429
			$sth_modes = $Connection->db->prepare($query_modes);
430
			try {
431
				if ($globalTransaction) $Connection->db->beginTransaction();
432
				$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...
433
            			while (!feof($fh)) {
434
            				$line = fgetcsv($fh,9999,',','"');
435
            				$values = array();
436
            				//print_r($line);
437
            				if ($country == 'F') {
438
            				    $values['registration'] = $line[0];
439
            				    $values['base'] = $line[4];
440
            				    $values['owner'] = $line[5];
441
            				    if ($line[6] == '') $values['date_first_reg'] = null;
442
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
443
					    $values['cancel'] = $line[7];
444
					} elseif ($country == 'EI') {
445
					    // TODO : add modeS & reg to aircraft_modes
446
            				    $values['registration'] = $line[0];
447
            				    $values['base'] = $line[3];
448
            				    $values['owner'] = $line[2];
449
            				    if ($line[1] == '') $values['date_first_reg'] = null;
450
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
451
					    $values['cancel'] = '';
452
					    $values['modes'] = $line[7];
453
					    $values['icao'] = $line[8];
454
					    
455
					} elseif ($country == 'HB') {
456
					    // TODO : add modeS & reg to aircraft_modes
457
            				    $values['registration'] = $line[0];
458
            				    $values['base'] = null;
459
            				    $values['owner'] = $line[5];
460
            				    $values['date_first_reg'] = null;
461
					    $values['cancel'] = '';
462
					    $values['modes'] = $line[4];
463
					    $values['icao'] = $line[7];
464
					} elseif ($country == 'OK') {
465
					    // TODO : add modeS & reg to aircraft_modes
466
            				    $values['registration'] = $line[3];
467
            				    $values['base'] = null;
468
            				    $values['owner'] = $line[5];
469
            				    if ($line[18] == '') $values['date_first_reg'] = null;
470
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
471
					    $values['cancel'] = '';
472
					} elseif ($country == 'VH') {
473
					    // TODO : add modeS & reg to aircraft_modes
474
            				    $values['registration'] = $line[0];
475
            				    $values['base'] = null;
476
            				    $values['owner'] = $line[12];
477
            				    if ($line[28] == '') $values['date_first_reg'] = null;
478
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
479
480
					    $values['cancel'] = $line[39];
481
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
482
            				    $values['registration'] = $line[0];
483
            				    $values['base'] = null;
484
            				    $values['owner'] = $line[4];
485
            				    $values['date_first_reg'] = null;
486
					    $values['cancel'] = '';
487
					} elseif ($country == 'CC') {
488
            				    $values['registration'] = $line[0];
489
            				    $values['base'] = null;
490
            				    $values['owner'] = $line[6];
491
            				    $values['date_first_reg'] = null;
492
					    $values['cancel'] = '';
493
					} elseif ($country == 'HJ') {
494
            				    $values['registration'] = $line[0];
495
            				    $values['base'] = null;
496
            				    $values['owner'] = $line[8];
497
            				    if ($line[7] == '') $values['date_first_reg'] = null;
498
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
499
					    $values['cancel'] = '';
500
					} elseif ($country == 'PP') {
501
            				    $values['registration'] = $line[0];
502
            				    $values['base'] = null;
503
            				    $values['owner'] = $line[4];
504
            				    if ($line[6] == '') $values['date_first_reg'] = null;
505
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
506
					    $values['cancel'] = $line[7];
507
					} elseif ($country == 'E7') {
508
            				    $values['registration'] = $line[0];
509
            				    $values['base'] = null;
510
            				    $values['owner'] = $line[4];
511
            				    if ($line[5] == '') $values['date_first_reg'] = null;
512
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
513
					    $values['cancel'] = '';
514
					} elseif ($country == '8Q') {
515
            				    $values['registration'] = $line[0];
516
            				    $values['base'] = null;
517
            				    $values['owner'] = $line[3];
518
            				    if ($line[7] == '') $values['date_first_reg'] = null;
519
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
520
					    $values['cancel'] = '';
521
					} elseif ($country == 'ZK') {
522
            				    $values['registration'] = $line[0];
523
            				    $values['base'] = null;
524
            				    $values['owner'] = $line[3];
525
            				    $values['date_first_reg'] = null;
526
					    $values['cancel'] = '';
527
					    $values['modes'] = $line[5];
528
					    $values['icao'] = $line[9];
529
					} elseif ($country == 'M') {
530
            				    $values['registration'] = $line[0];
531
            				    $values['base'] = null;
532
            				    $values['owner'] = $line[6];
533
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
534
					    $values['cancel'] = date("Y-m-d",strtotime($line[8]));
535
					    $values['modes'] = $line[4];
536
					    $values['icao'] = $line[10];
537
					} elseif ($country == 'OY') {
538
            				    $values['registration'] = $line[0];
539
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[4]));
540
					    $values['modes'] = $line[5];
541
					    $values['icao'] = $line[6];
542
					} elseif ($country == 'PH') {
543
            				    $values['registration'] = $line[0];
544
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[3]));
545
					    $values['modes'] = $line[4];
546
					    $values['icao'] = $line[5];
547
					} elseif ($country == 'OM' || $country == 'TF') {
548
            				    $values['registration'] = $line[0];
549
            				    $values['base'] = null;
550
            				    $values['owner'] = $line[3];
551
            				    $values['date_first_reg'] = null;
552
					    $values['cancel'] = '';
553
					}
554
					if (isset($values['cancel']) && $values['cancel'] == '' && $values['registration'] != null && isset($values['owner'])) {
555
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
556
						$sth_dest->execute($query_dest_values);
557
					}
558
					if ($globalMasterSource && $values['registration'] != null && isset($values['modes']) && $values['modes'] != '') {
559
						$modescountry = $Spotter->countryFromAircraftRegistration($values['registration']);
560
						$query_modes_values = array(':registration' => $values['registration'],':modes' => $values['modes'],':modescountry' => $modescountry,':icaotypecode' => $values['icao'],':source' => $database_file);
561
						$sth_modes->execute($query_modes_values);
562
					}
563
				}
564
				if ($globalTransaction) $Connection->db->commit();
565
			} catch(PDOException $e) {
566
				return "error : ".$e->getMessage();
567
			}
568
		}
569
		return '';
570
	}
571
572
	/*
573
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
574
	*/
575
	public static function update_airports() {
576
		global $tmp_dir, $globalTransaction, $globalDebug;
577
578
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
579
		$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...
580
		$query = '
581
		    PREFIX dbo: <http://dbpedia.org/ontology/>
582
		    PREFIX dbp: <http://dbpedia.org/property/>
583
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
584
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
585
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
586
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
587
		    FROM <http://dbpedia.org>
588
		    WHERE {
589
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
590
591
			OPTIONAL {
592
			    ?airport dbo:icaoLocationIdentifier ?icao .
593
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
594
			}
595
596
			OPTIONAL {
597
			    ?airport dbo:iataLocationIdentifier ?iata .
598
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
599
			}
600
601
			OPTIONAL {
602
			    ?airport dbo:locationIdentifier ?lid .
603
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
604
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
605
			    OPTIONAL {
606
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
607
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
608
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
609
			    }
610
			    FILTER (!bound(?other_icao))
611
			}
612
613
			OPTIONAL {
614
			    ?airport dbo:faaLocationIdentifier ?faa .
615
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
616
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
617
			    OPTIONAL {
618
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
619
				?airport_x dbo:iataLocationIdentifier ?other_iata .
620
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
621
			    }
622
			    FILTER (!bound(?other_iata))
623
			}
624
625
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
626
	
627
			OPTIONAL {
628
			    ?airport rdfs:label ?name
629
			    FILTER (lang(?name) = "en")
630
			}
631
    
632
			OPTIONAL {
633
			    ?airport foaf:homepage ?homepage
634
			}
635
		    
636
			OPTIONAL {
637
			    ?airport dbp:coordinatesRegion ?country
638
			}
639
    
640
			OPTIONAL {
641
			    ?airport dbp:type ?type
642
			}
643
			
644
			OPTIONAL {
645
			    ?airport dbo:elevation ?altitude
646
			}
647
			OPTIONAL {
648
			    ?airport dbp:image ?image
649
			}
650
651
			{
652
			    ?airport geo:lat ?latitude .
653
			    ?airport geo:long ?longitude .
654
			    FILTER (datatype(?latitude) = xsd:float)
655
			    FILTER (datatype(?longitude) = xsd:float)
656
			} UNION {
657
			    ?airport geo:lat ?latitude .
658
			    ?airport geo:long ?longitude .
659
			    FILTER (datatype(?latitude) = xsd:double)
660
			    FILTER (datatype(?longitude) = xsd:double)
661
			    OPTIONAL {
662
				?airport geo:lat ?lat_f .
663
				?airport geo:long ?long_f .
664
				FILTER (datatype(?lat_f) = xsd:float)
665
				FILTER (datatype(?long_f) = xsd:float)
666
			    }
667
			    FILTER (!bound(?lat_f) && !bound(?long_f))
668
			}
669
670
		    }
671
		    ORDER BY ?airport
672
		';
673
		$result = sparql_query($query);
674
  
675
		/*
676
		$query = 'TRUNCATE TABLE airport';
677
		try {
678
			$Connection = new Connection();
679
			$sth = $Connection->db->prepare($query);
680
                        $sth->execute();
681
                } catch(PDOException $e) {
682
                        return "error : ".$e->getMessage();
683
                }
684
                */
685
                /*
686
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
687
		try {
688
			$Connection = new Connection();
689
			$sth = $Connection->db->prepare($query);
690
                        $sth->execute();
691
                } catch(PDOException $e) {
692
                        return "error : ".$e->getMessage();
693
                }
694
                */
695
696
		$query_dest = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image_thumb,image)
697
		    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
698
		$Connection = new Connection();
699
		$sth_dest = $Connection->db->prepare($query_dest);
700
		if ($globalTransaction) $Connection->db->beginTransaction();
701
  
702
		$i = 0;
703
		while($row = sparql_fetch_array($result))
704
		{
705
			if ($i >= 1) {
706
			//print_r($row);
707
			if (!isset($row['iata'])) $row['iata'] = '';
708
			if (!isset($row['icao'])) $row['icao'] = '';
709
			if (!isset($row['type'])) $row['type'] = '';
710
			if (!isset($row['altitude'])) $row['altitude'] = '';
711
			if (isset($row['city_bis'])) {
712
				$row['city'] = $row['city_bis'];
713
			}
714
			if (!isset($row['city'])) $row['city'] = '';
715
			if (!isset($row['country'])) $row['country'] = '';
716
			if (!isset($row['homepage'])) $row['homepage'] = '';
717
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
718
			if (!isset($row['name'])) continue;
719
			if (!isset($row['image'])) {
720
				$row['image'] = '';
721
				$row['image_thumb'] = '';
722
			} else {
723
				$image = str_replace(' ','_',$row['image']);
724
				$digest = md5($image);
725
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
726
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
727
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
728
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
729
			}
730
			
731
			$country = explode('-',$row['country']);
732
			$row['country'] = $country[0];
733
			
734
			$row['type'] = trim($row['type']);
735
			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'])) {
736
				$row['type'] = 'military';
737
			} 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') {
738
				$row['type'] = 'small_airport';
739
			}
740
			
741
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
742
			$query_dest_values = array(':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => round($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']);
743
			//print_r($query_dest_values);
744
			
745
			if ($row['icao'] != '') {
746
				try {
747
					$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
748
					$sth->execute(array(':icao' => $row['icao']));
749
				} catch(PDOException $e) {
750
					return "error : ".$e->getMessage();
751
				}
752
					if ($sth->fetchColumn() > 0) {
753
						// Update ?
754
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
755
						try {
756
							$sth = $Connection->db->prepare($query);
757
							$sth->execute(array(':icao' => $row['icao'],':type' => $row['type']));
758
						} catch(PDOException $e) {
759
							return "error : ".$e->getMessage();
760
						}
761
						echo $row['icao'].' : '.$row['type']."\n";
762
					} else {
763
						try {
764
							$sth_dest->execute($query_dest_values);
765
						} catch(PDOException $e) {
766
							return "error : ".$e->getMessage();
767
						}
768
					}
769
				}
770
			}
771
772
			$i++;
773
		}
774
		if ($globalTransaction) $Connection->db->commit();
775
		/*
776
		echo "Delete duplicate rows...\n";
777
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
778
		try {
779
			$Connection = new Connection();
780
			$sth = $Connection->db->prepare($query);
781
                        $sth->execute();
782
                } catch(PDOException $e) {
783
                        return "error : ".$e->getMessage();
784
                }
785
                */
786
787
788
		/*
789
		if ($globalDebug) echo "Insert Not available Airport...\n";
790
		$query = "INSERT INTO airport (airport_id,name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image,image_thumb)
791
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
792
		$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' => '');
793
		try {
794
			$Connection = new Connection();
795
			$sth = $Connection->db->prepare($query);
796
                        $sth->execute($query_values);
797
                } catch(PDOException $e) {
798
                        return "error : ".$e->getMessage();
799
                }
800
                */
801
		$i++;
802
/*
803
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
804
		try {
805
			$Connection = new Connection();
806
			$sth = $Connection->db->prepare($query);
807
                        $sth->execute();
808
                } catch(PDOException $e) {
809
                        return "error : ".$e->getMessage();
810
                }
811
*/
812
                
813
		echo "Download data from ourairports.com...\n";
814
		$delimiter = ',';
815
		$out_file = $tmp_dir.'airports.csv';
816
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
817
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
818
		echo "Add data from ourairports.com...\n";
819
820
		$header = NULL;
821
		if (($handle = fopen($out_file, 'r')) !== FALSE)
822
		{
823
			$Connection = new Connection();
824
			//$Connection->db->beginTransaction();
825
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
826
			{
827
				if(!$header) $header = $row;
828
				else {
829
					$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...
830
					$data = array_combine($header, $row);
831
					try {
832
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
833
						$sth->execute(array(':icao' => $data['ident']));
834
					} catch(PDOException $e) {
835
						return "error : ".$e->getMessage();
836
					}
837
					if ($sth->fetchColumn() > 0) {
838
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
839
						try {
840
							$sth = $Connection->db->prepare($query);
841
							$sth->execute(array(':icao' => $data['ident'],':type' => $data['type']));
842
						} catch(PDOException $e) {
843
							return "error : ".$e->getMessage();
844
						}
845
					} else {
846
						if ($data['gps_code'] == $data['ident']) {
847
						$query = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link)
848
						    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
849
						$query_values = array(':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => round($data['elevation_ft']),':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
850
						try {
851
							$sth = $Connection->db->prepare($query);
852
							$sth->execute($query_values);
853
						} catch(PDOException $e) {
854
							return "error : ".$e->getMessage();
855
						}
856
						$i++;
857
						}
858
					}
859
				}
860
			}
861
			fclose($handle);
862
			//$Connection->db->commit();
863
		}
864
		
865
		
866
		echo "Download data from another free database...\n";
867
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
868
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
869
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
870
		update_db::unzip($out_file);
871
		$header = NULL;
872
		echo "Add data from another free database...\n";
873
		$delimiter = ':';
874
		$Connection = new Connection();
875
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
876
		{
877
			//$Connection->db->beginTransaction();
878
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
879
			{
880
				if(!$header) $header = $row;
881
				else {
882
					$data = $row;
883
884
					$query = 'UPDATE airport SET city = :city, country = :country WHERE icao = :icao';
885
					try {
886
						$sth = $Connection->db->prepare($query);
887
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
888
					} catch(PDOException $e) {
889
						return "error : ".$e->getMessage();
890
					}
891
				}
892
			}
893
			fclose($handle);
894
			//$Connection->db->commit();
895
		}
896
897
		echo "Put type military for all air base";
898
		$Connection = new Connection();
899
		try {
900
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE name LIKE '%Air Base%'");
901
			$sth->execute();
902
		} catch(PDOException $e) {
903
			return "error : ".$e->getMessage();
904
		}
905
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
906
			$query2 = 'UPDATE airport SET type = :type WHERE icao = :icao';
907
			try {
908
				$sth2 = $Connection->db->prepare($query2);
909
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
910
			} catch(PDOException $e) {
911
				return "error : ".$e->getMessage();
912
			}
913
		}
914
		return "success";
915
	}
916
	
917
	public static function translation() {
918
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
919
		global $tmp_dir, $globalTransaction;
920
		$Spotter = new Spotter();
921
		//$out_file = $tmp_dir.'translation.zip';
922
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
923
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
924
		
925
		//$query = 'TRUNCATE TABLE translation';
926
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
927
		try {
928
			$Connection = new Connection();
929
			$sth = $Connection->db->prepare($query);
930
                        $sth->execute(array(':source' => 'translation.csv'));
931
                } catch(PDOException $e) {
932
                        return "error : ".$e->getMessage();
933
                }
934
935
		
936
		//update_db::unzip($out_file);
937
		$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...
938
		$delimiter = ';';
939
		$Connection = new Connection();
940
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
941
		{
942
			$i = 0;
943
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
944
			//$Connection->db->beginTransaction();
945
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
946
			{
947
				$i++;
948
				if($i > 12) {
949
					$data = $row;
950
					$operator = $data[2];
951
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
952
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
953
                                                //echo substr($operator, 0, 2)."\n";;
954
                                                if (count($airline_array) > 0) {
955
							//print_r($airline_array);
956
							$operator = $airline_array[0]['icao'].substr($operator,2);
957
                                                }
958
                                        }
959
					
960
					$operator_correct = $data[3];
961
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
962
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
963
                                                if (count($airline_array) > 0) {
964
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
965
                                            	}
966
                                        }
967
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
968
					try {
969
						$sth = $Connection->db->prepare($query);
970
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
971
					} catch(PDOException $e) {
972
						return "error : ".$e->getMessage();
973
					}
974
				}
975
			}
976
			fclose($handle);
977
			//$Connection->db->commit();
978
		}
979
		return '';
980
        }
981
	
982
	public static function translation_fam() {
983
		global $tmp_dir, $globalTransaction;
984
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
985
		try {
986
			$Connection = new Connection();
987
			$sth = $Connection->db->prepare($query);
988
			$sth->execute(array(':source' => 'website_fam'));
989
		} catch(PDOException $e) {
990
			return "error : ".$e->getMessage();
991
		}
992
		//update_db::unzip($out_file);
993
		$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...
994
		$delimiter = "\t";
995
		$Connection = new Connection();
996
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
997
		{
998
			$i = 0;
999
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1000
			//$Connection->db->beginTransaction();
1001
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1002
			{
1003
				if ($i > 0) {
1004
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
1005
					try {
1006
						$sth = $Connection->db->prepare($query);
1007
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
1008
					} catch(PDOException $e) {
1009
						return "error : ".$e->getMessage();
1010
					}
1011
				}
1012
				$i++;
1013
			}
1014
			fclose($handle);
1015
			//$Connection->db->commit();
1016
		}
1017
		return '';
1018
        }
1019
1020
	/*
1021
	* This function use FAA public data.
1022
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
1023
	*/
1024
	public static function modes_faa() {
1025
		global $tmp_dir, $globalTransaction, $globalDebug;
1026
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1027
		try {
1028
			$Connection = new Connection();
1029
			$sth = $Connection->db->prepare($query);
1030
                        $sth->execute(array(':source' => 'website_faa'));
1031
                } catch(PDOException $e) {
1032
                        return "error : ".$e->getMessage();
1033
                }
1034
1035
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1036
		try {
1037
			$Connection = new Connection();
1038
			$sth = $Connection->db->prepare($query);
1039
                        $sth->execute(array(':source' => 'website_faa'));
1040
                } catch(PDOException $e) {
1041
                        return "error : ".$e->getMessage();
1042
                }
1043
1044
		$delimiter = ",";
1045
		$mfr = array();
0 ignored issues
show
Unused Code introduced by
$mfr 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...
1046
		$Connection = new Connection();
1047
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1048
		{
1049
			$i = 0;
1050
			if ($globalTransaction) $Connection->db->beginTransaction();
1051
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1052
			{
1053
				if ($i > 0) {
1054
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1055
					try {
1056
						$sths = $Connection->db->prepare($query_search);
1057
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1058
					} catch(PDOException $e) {
1059
						return "error s : ".$e->getMessage();
1060
					}
1061
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1062
					if (!empty($result_search)) {
1063
						if ($globalDebug) echo '.';
1064
							//if ($globalDBdriver == 'mysql') {
1065
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1066
							//} else {
1067
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1068
							//}
1069
						try {
1070
							$sthi = $Connection->db->prepare($queryi);
1071
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1072
						} catch(PDOException $e) {
1073
							return "error u : ".$e->getMessage();
1074
						}
1075
					} else {
1076
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1077
						try {
1078
							$sthsm = $Connection->db->prepare($query_search_mfr);
1079
							$sthsm->execute(array(':mfr' => $data[2]));
1080
						} catch(PDOException $e) {
1081
							return "error mfr : ".$e->getMessage();
1082
						}
1083
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1084
						if (!empty($result_search_mfr)) {
1085
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1086
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1087
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1088
							try {
1089
								$sthf = $Connection->db->prepare($queryf);
1090
								$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'));
1091
							} catch(PDOException $e) {
1092
								return "error f : ".$e->getMessage();
1093
							}
1094
						}
1095
					}
1096
					if (strtotime($data[29]) > time()) {
1097
						if ($globalDebug) echo 'i';
1098
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1099
						try {
1100
							$sth = $Connection->db->prepare($query);
1101
							$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'));
1102
						} catch(PDOException $e) {
1103
							return "error i : ".$e->getMessage();
1104
						}
1105
					}
1106
				}
1107
				if ($i % 90 == 0) {
1108
					if ($globalTransaction) $Connection->db->commit();
1109
					if ($globalTransaction) $Connection->db->beginTransaction();
1110
				}
1111
				$i++;
1112
			}
1113
			fclose($handle);
1114
			if ($globalTransaction) $Connection->db->commit();
1115
		}
1116
		return '';
1117
	}
1118
1119
	public static function modes_fam() {
1120
		global $tmp_dir, $globalTransaction;
1121
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1122
		try {
1123
			$Connection = new Connection();
1124
			$sth = $Connection->db->prepare($query);
1125
			$sth->execute(array(':source' => 'website_fam'));
1126
		} catch(PDOException $e) {
1127
			return "error : ".$e->getMessage();
1128
		}
1129
		$delimiter = "\t";
1130
		$Connection = new Connection();
1131
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1132
		{
1133
			$i = 0;
1134
			if ($globalTransaction) $Connection->db->beginTransaction();
1135
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1136
			{
1137
				if ($i > 0) {
1138
					if ($data[1] == 'NULL') $data[1] = $data[0];
1139
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1140
					try {
1141
						$sth = $Connection->db->prepare($query);
1142
						$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'));
1143
					} catch(PDOException $e) {
1144
						return "error : ".$e->getMessage();
1145
					}
1146
				}
1147
				$i++;
1148
			}
1149
			fclose($handle);
1150
			if ($globalTransaction) $Connection->db->commit();
1151
		}
1152
		return '';
1153
	}
1154
1155
	public static function airlines_fam() {
1156
		global $tmp_dir, $globalTransaction;
1157
		$Connection = new Connection();
1158
		$query = "DELETE FROM airlines WHERE forsource IS NULL";
1159
		try {
1160
			$sth = $Connection->db->prepare($query);
1161
			$sth->execute();
1162
		} catch(PDOException $e) {
1163
			return "error : ".$e->getMessage();
1164
		}
1165
		$query = "LOCK TABLE airlines WRITE";
1166
		try {
1167
			$sth = $Connection->db->prepare($query);
1168
			$sth->execute();
1169
		} catch(PDOException $e) {
1170
			return "error : ".$e->getMessage();
1171
		}
1172
		$delimiter = "\t";
1173
		if (($handle = fopen($tmp_dir.'airlines.tsv', 'r')) !== FALSE)
1174
		{
1175
			$i = 0;
1176
			if ($globalTransaction) $Connection->db->beginTransaction();
1177
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1178
			{
1179
				if ($i > 0) {
1180
					if ($data[1] == 'NULL') $data[1] = $data[0];
1181
					$query = 'INSERT INTO airlines (name,alias,iata,icao,callsign,country,active,type,home,wikipedia_link,alliance,ban_eu) VALUES (:name,:alias,:iata,:icao,:callsign,:country,:active,:type,:home,:wikipedia_link,:alliance,:ban_eu)';
1182
					try {
1183
						$sth = $Connection->db->prepare($query);
1184
						$sth->execute(array(':name' => $data[0],':alias' => $data[1],':iata' => $data[2],':icao' => $data[3], ':callsign' => $data[4],':country' => $data[5],':active' => $data[6],':type' => $data[7],':home' => $data[8],':wikipedia_link' => $data[9],':alliance' => $data[10],':ban_eu' => $data[11]));
1185
					} catch(PDOException $e) {
1186
						return "error : ".$e->getMessage();
1187
					}
1188
				}
1189
				$i++;
1190
			}
1191
			fclose($handle);
1192
			if ($globalTransaction) $Connection->db->commit();
1193
		}
1194
		$query = "UNLOCK TABLES";
1195
		try {
1196
			$sth = $Connection->db->prepare($query);
1197
			$sth->execute();
1198
		} catch(PDOException $e) {
1199
			return "error : ".$e->getMessage();
1200
		}
1201
		return '';
1202
        }
1203
        
1204
	public static function owner_fam() {
1205
		global $tmp_dir, $globalTransaction;
1206
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1207
		try {
1208
			$Connection = new Connection();
1209
			$sth = $Connection->db->prepare($query);
1210
                        $sth->execute(array(':source' => 'website_fam'));
1211
                } catch(PDOException $e) {
1212
                        return "error : ".$e->getMessage();
1213
                }
1214
1215
		$delimiter = "\t";
1216
		$Connection = new Connection();
1217
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1218
		{
1219
			$i = 0;
1220
			if ($globalTransaction) $Connection->db->beginTransaction();
1221
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1222
			{
1223
				if ($i > 0) {
1224
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1225
					try {
1226
						$sth = $Connection->db->prepare($query);
1227
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1228
					} catch(PDOException $e) {
1229
						//print_r($data);
1230
						return "error : ".$e->getMessage();
1231
					}
1232
				}
1233
				$i++;
1234
			}
1235
			fclose($handle);
1236
			if ($globalTransaction) $Connection->db->commit();
1237
		}
1238
		return '';
1239
        }
1240
1241
	public static function routes_fam() {
1242
		global $tmp_dir, $globalTransaction, $globalDebug;
1243
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1244
		try {
1245
			$Connection = new Connection();
1246
			$sth = $Connection->db->prepare($query);
1247
			$sth->execute(array(':source' => 'website_fam'));
1248
		} catch(PDOException $e) {
1249
			return "error : ".$e->getMessage();
1250
		}
1251
		$delimiter = "\t";
1252
		$Connection = new Connection();
1253
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1254
		{
1255
			$i = 0;
1256
			if ($globalTransaction) $Connection->db->beginTransaction();
1257
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1258
			{
1259
				if ($i > 0) {
1260
					$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)';
1261
					try {
1262
						$sth = $Connection->db->prepare($query);
1263
						$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'));
1264
					} catch(PDOException $e) {
1265
						if ($globalDebug) echo "error: ".$e->getMessage()." - data: ".implode(',',$data);
1266
					}
1267
				}
1268
				$i++;
1269
			}
1270
			fclose($handle);
1271
			if ($globalTransaction) $Connection->db->commit();
1272
		}
1273
		return '';
1274
        }
1275
1276
	public static function marine_identity_fam() {
1277
		global $tmp_dir, $globalTransaction;
1278
		$query = "TRUNCATE TABLE marine_identity";
1279
		try {
1280
			$Connection = new Connection();
1281
			$sth = $Connection->db->prepare($query);
1282
                        $sth->execute();
1283
                } catch(PDOException $e) {
1284
                        return "error : ".$e->getMessage();
1285
                }
1286
1287
		
1288
		//update_db::unzip($out_file);
1289
		$delimiter = "\t";
1290
		$Connection = new Connection();
1291
		if (($handle = fopen($tmp_dir.'marine_identity.tsv', 'r')) !== FALSE)
1292
		{
1293
			$i = 0;
1294
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1295
			//$Connection->db->beginTransaction();
1296
			if ($globalTransaction) $Connection->db->beginTransaction();
1297
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1298
			{
1299
				if ($i > 0) {
1300
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1301
					$query = 'INSERT INTO marine_identity (mmsi,imo,call_sign,ship_name,length,gross_tonnage,dead_weight,width,country,engine_power,type) VALUES (:mmsi,:imo,:call_sign,:ship_name,:length,:gross_tonnage,:dead_weight,:width,:country,:engine_power,:type)';
1302
					try {
1303
						$sth = $Connection->db->prepare($query);
1304
						$sth->execute(array(':mmsi' => $data[0],':imo' => $data[1],':call_sign' => $data[2],':ship_name' => $data[3], ':length' => $data[4],':gross_tonnage' => $data[5],':dead_weight' => $data[6],':width' => $data[7],':country' => $data[8],':engine_power' => $data[9],':type' => $data[10]));
1305
					} catch(PDOException $e) {
1306
						return "error : ".$e->getMessage();
1307
					}
1308
				}
1309
				$i++;
1310
			}
1311
			fclose($handle);
1312
			if ($globalTransaction) $Connection->db->commit();
1313
		}
1314
		return '';
1315
        }
1316
1317
	public static function satellite_fam() {
1318
		global $tmp_dir, $globalTransaction;
1319
		$query = "TRUNCATE TABLE satellite";
1320
		try {
1321
			$Connection = new Connection();
1322
			$sth = $Connection->db->prepare($query);
1323
			$sth->execute();
1324
		} catch(PDOException $e) {
1325
			return "error : ".$e->getMessage();
1326
		}
1327
		$delimiter = "\t";
1328
		$Connection = new Connection();
1329
		if (($handle = fopen($tmp_dir.'satellite.tsv', 'r')) !== FALSE)
1330
		{
1331
			$i = 0;
1332
			if ($globalTransaction) $Connection->db->beginTransaction();
1333
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1334
			{
1335
				if ($i > 0) {
1336
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1337
					$query = 'INSERT INTO satellite (name, name_alternate, country_un, country_owner, owner, users, purpose, purpose_detailed, orbit, type, longitude_geo, perigee, apogee, eccentricity, inclination, period, launch_mass, dry_mass, power, launch_date, lifetime, contractor, country_contractor, launch_site, launch_vehicule, cospar, norad, comments, source_orbital, sources) 
1338
					    VALUES (:name, :name_alternate, :country_un, :country_owner, :owner, :users, :purpose, :purpose_detailed, :orbit, :type, :longitude_geo, :perigee, :apogee, :eccentricity, :inclination, :period, :launch_mass, :dry_mass, :power, :launch_date, :lifetime, :contractor, :country_contractor, :launch_site, :launch_vehicule, :cospar, :norad, :comments, :source_orbital, :sources)';
1339
					try {
1340
						$sth = $Connection->db->prepare($query);
1341
						$sth->execute(array(':name' => $data[0], ':name_alternate' => $data[1], ':country_un' => $data[2], ':country_owner' => $data[3], ':owner' => $data[4], ':users' => $data[5], ':purpose' => $data[6], ':purpose_detailed' => $data[7], ':orbit' => $data[8], ':type' => $data[9], ':longitude_geo' => $data[10], ':perigee' => !empty($data[11]) ? $data[11] : NULL, ':apogee' => !empty($data[12]) ? $data[12] : NULL, ':eccentricity' => $data[13], ':inclination' => $data[14], ':period' => !empty($data[15]) ? $data[15] : NULL, ':launch_mass' => !empty($data[16]) ? $data[16] : NULL, ':dry_mass' => !empty($data[17]) ? $data[17] : NULL, ':power' => !empty($data[18]) ? $data[18] : NULL, ':launch_date' => $data[19], ':lifetime' => $data[20], ':contractor' => $data[21],':country_contractor' => $data[22], ':launch_site' => $data[23], ':launch_vehicule' => $data[24], ':cospar' => $data[25], ':norad' => $data[26], ':comments' => $data[27], ':source_orbital' => $data[28], ':sources' => $data[29]));
1342
					} catch(PDOException $e) {
1343
						return "error : ".$e->getMessage();
1344
					}
1345
				}
1346
				$i++;
1347
			}
1348
			fclose($handle);
1349
			if ($globalTransaction) $Connection->db->commit();
1350
		}
1351
		return '';
1352
	}
1353
1354
	public static function banned_fam() {
1355
		global $tmp_dir, $globalTransaction;
1356
		$query = "UPDATE airlines SET ban_eu = 0";
1357
		try {
1358
			$Connection = new Connection();
1359
			$sth = $Connection->db->prepare($query);
1360
			$sth->execute();
1361
		} catch(PDOException $e) {
1362
			return "error : ".$e->getMessage();
1363
		}
1364
1365
		$Connection = new Connection();
1366
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1367
		{
1368
			if ($globalTransaction) $Connection->db->beginTransaction();
1369
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1370
			{
1371
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1372
				if ($data[0] != '') {
1373
					$icao = $data[0];
1374
					try {
1375
						$sth = $Connection->db->prepare($query);
1376
						$sth->execute(array(':icao' => $icao));
1377
					} catch(PDOException $e) {
1378
						return "error : ".$e->getMessage();
1379
					}
1380
				}
1381
			}
1382
			fclose($handle);
1383
			if ($globalTransaction) $Connection->db->commit();
1384
		}
1385
		return '';
1386
        }
1387
1388
	public static function tle($filename,$tletype) {
1389
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1390
		global $tmp_dir, $globalTransaction;
1391
		//$Spotter = new Spotter();
1392
		
1393
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1394
		try {
1395
			$Connection = new Connection();
1396
			$sth = $Connection->db->prepare($query);
1397
                        $sth->execute(array(':source' => $filename));
1398
                } catch(PDOException $e) {
1399
                        return "error : ".$e->getMessage();
1400
                }
1401
		
1402
		$Connection = new Connection();
1403
		if (($handle = fopen($filename, 'r')) !== FALSE)
1404
		{
1405
			$i = 0;
1406
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1407
			//$Connection->db->beginTransaction();
1408
			$dbdata = array();
1409
			while (($data = fgets($handle, 1000)) !== FALSE)
1410
			{
1411
				if ($i == 0) {
1412
					$dbdata['name'] = trim($data);
1413
					$i++;
1414
				} elseif ($i == 1) {
1415
					$dbdata['tle1'] = trim($data);
1416
					$i++;
1417
				} elseif ($i == 2) {
1418
					$dbdata['tle2'] = trim($data);
1419
					//print_r($dbdata);
1420
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1421
					try {
1422
						$sth = $Connection->db->prepare($query);
1423
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1424
					} catch(PDOException $e) {
1425
						return "error : ".$e->getMessage();
1426
					}
1427
1428
					$i = 0;
1429
				}
1430
			}
1431
			fclose($handle);
1432
			//$Connection->db->commit();
1433
		}
1434
		return '';
1435
        }
1436
1437
	public static function satellite_ucsdb($filename) {
1438
		global $tmp_dir, $globalTransaction;
1439
		$query = "DELETE FROM satellite";
1440
		try {
1441
			$Connection = new Connection();
1442
			$sth = $Connection->db->prepare($query);
1443
			$sth->execute(array(':source' => $filename));
1444
		} catch(PDOException $e) {
1445
			return "error : ".$e->getMessage();
1446
		}
1447
		
1448
		$Connection = new Connection();
1449
		if (($handle = fopen($filename, 'r')) !== FALSE)
1450
		{
1451
			$i = 0;
1452
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1453
			//$Connection->db->beginTransaction();
1454
			while (($data = fgetcsv($handle, 1000,"\t")) !== FALSE)
1455
			{
1456
				if ($i > 0 && $data[0] != '') {
1457
					$sources = trim($data[28].' '.$data[29].' '.$data[30].' '.$data[31].' '.$data[32].' '.$data[33]);
1458
					$period = str_replace(',','',$data[14]);
1459
					if (!empty($period) && strpos($period,'days')) $period = str_replace(' days','',$period)*24*60;
1460
					if ($data[18] != '') $launch_date = date('Y-m-d',strtotime($data[18]));
1461
					else $launch_date = NULL;
1462
					$data = array_map(function($value) {
1463
						return trim($value) === '' ? null : $value;
1464
					}, $data);
1465
					//print_r($data);
1466
					$query = 'INSERT INTO satellite (name, name_alternate, country_un, country_owner, owner, users, purpose, purpose_detailed, orbit, type, longitude_geo, perigee, apogee, eccentricity, inclination, period, launch_mass, dry_mass, power, launch_date, lifetime, contractor, country_contractor, launch_site, launch_vehicule, cospar, norad, comments, source_orbital, sources) 
1467
					    VALUES (:name, :name_alternate, :country_un, :country_owner, :owner, :users, :purpose, :purpose_detailed, :orbit, :type, :longitude_geo, :perigee, :apogee, :eccentricity, :inclination, :period, :launch_mass, :dry_mass, :power, :launch_date, :lifetime, :contractor, :country_contractor, :launch_site, :launch_vehicule, :cospar, :norad, :comments, :source_orbital, :sources)';
1468
					try {
1469
						$sth = $Connection->db->prepare($query);
1470
						$sth->execute(array(':name' => $data[0], ':name_alternate' => '', ':country_un' => $data[1], ':country_owner' => $data[2], ':owner' => $data[3], ':users' => $data[4], ':purpose' => $data[5], ':purpose_detailed' => $data[6], ':orbit' => $data[7], ':type' => $data[8], ':longitude_geo' => $data[9], ':perigee' => !empty($data[10]) ? str_replace(',','',$data[10]) : NULL, ':apogee' => !empty($data[11]) ? str_replace(',','',$data[11]) : NULL, ':eccentricity' => $data[12], ':inclination' => $data[13], ':period' => !empty($period) ? $period : NULL, ':launch_mass' => !empty($data[15]) ? str_replace(array('+',','),'',$data[15]) : NULL, ':dry_mass' => !empty($data[16]) ? str_replace(array(',','-1900',' (BOL)',' (EOL)'),'',$data[16]) : NULL, ':power' => !empty($data[17]) ? str_replace(array(',',' (BOL)',' (EOL)'),'',$data[17]) : NULL, ':launch_date' => $launch_date, ':lifetime' => $data[19], ':contractor' => $data[20],':country_contractor' => $data[21], ':launch_site' => $data[22], ':launch_vehicule' => $data[23], ':cospar' => $data[24], ':norad' => $data[25], ':comments' => $data[26], ':source_orbital' => $data[27], ':sources' => $sources));
1471
					} catch(PDOException $e) {
1472
						return "error : ".$e->getMessage();
1473
					}
1474
				}
1475
				$i++;
1476
			}
1477
			fclose($handle);
1478
			//$Connection->db->commit();
1479
		}
1480
		return '';
1481
	}
1482
1483
	public static function satellite_celestrak($filename) {
1484
		global $tmp_dir, $globalTransaction;
1485
		$satcat_sources = array(
1486
			'AB' => array('country' => 'Multinational', 'owner' => 'Arab Satellite Communications Org. (ASCO)'),
1487
			'ABS' => array('country' => 'Multinational', 'owner' => 'Asia Broadcast Satellite Ltd.'),
1488
			'AC' => array('country' => 'China', 'owner' => 'Asia Satellite Telecommunications Co. Ltd.'),
1489
			'ALG' => array('country' => 'Algeria', 'owner' => ''),
1490
			'ARGN' => array('country' => 'Argentina', 'owner' => ''),
1491
			'ASRA' => array('country' => 'Austria', 'owner' => ''),
1492
			'AUS' => array('country' => 'Australia', 'owner' => ''),
1493
			'AZER' => array('country' => 'Azerbaijan', 'owner' => ''),
1494
			'BEL' => array('country' => 'Belgium', 'owner' => ''),
1495
			'BELA' => array('country' => 'Belarus', 'owner' => ''),
1496
			'BERM' => array('country' => 'Bermuda', 'owner' => ''),
1497
			'BOL' => array('country' => 'Bolivia', 'owner' => ''),
1498
			'BUL' => array('country' => 'Bulgaria', 'owner' => ''),
1499
			'BRAZ' => array('country' => 'Brazil', 'owner' => ''),
1500
			'CA' => array('country' => 'Canada', 'owner' => ''),
1501
			'CHBZ' => array('country' => 'China/Brazil', 'owner' => ''),
1502
			'CHLE' => array('country' => 'Chile', 'owner' => ''),
1503
			'CIS' => array('country' => 'Russia', 'owner' => ''),
1504
			'COL' => array('country' => 'Colombia', 'owner' => ''),
1505
			'CZCH' => array('country' => 'Czech Republic (former Czechoslovakia)', 'owner' => ''),
1506
			'DEN' => array('country' => 'Denmark', 'owner' => ''),
1507
			'ECU' => array('country' => 'Ecuador', 'owner' => ''),
1508
			'EGYP' => array('country' => 'Egypt', 'owner' => ''),
1509
			'ESA' => array('country' => 'Multinational', 'owner' => 'European Space Agency'),
1510
			'ESRO' => array('country' => 'Multinational', 'owner' => 'European Space Research Organization'),
1511
			'EST' => array('country' => 'Estonia','owner' => ''),
1512
			'EUME' => array('country' => 'Multinational', 'owner' => 'EUMETSAT (European Organization for the Exploitation of Meteorological Satellites)'),
1513
			'EUTE' => array('country' => 'Multinational', 'owner' => 'European Telecommunications Satellite Consortium (EUTELSAT)'),
1514
			'FGER' => array('country' => 'France/Germany', 'owner' => ''),
1515
			'FIN' => array('country' => 'Finland', 'owner' => ''),
1516
			'FR' => array('country' => 'France', 'owner' => ''),
1517
			'FRIT' => array('country' => 'France/Italy', 'owner' => ''),
1518
			'GER' => array('country' => 'Germany', 'owner' => ''),
1519
			'GLOB' => array('country' => 'USA', 'owner' => 'Globalstar'),
1520
			'GREC' => array('country' => 'Greece', 'owner' => ''),
1521
			'HUN' => array('country' => 'Hungary', 'owner' => ''),
1522
			'IM' => array('country' => 'United Kingdom', 'owner' => 'INMARSAT, Ltd.'),
1523
			'IND' => array('country' => 'India', 'owner' => ''),
1524
			'INDO' => array('country' => 'Indonesia', 'owner' => ''),
1525
			'IRAN' => array('country' => 'Iran', 'owner' => ''),
1526
			'IRAQ' => array('country' => 'Iraq', 'owner' => ''),
1527
			'IRID' => array('country' => 'USA', 'owner' => 'Iridium Satellite LLC'),
1528
			'ISRA' => array('country' => 'Israel', 'owner' => ''),
1529
			'ISRO' => array('country' => 'India', 'owner' => 'Indian Space Research Organisation (ISRO)'),
1530
			'ISS' => array('country' => 'Multinational', 'owner' => 'NASA/Multinational'),
1531
			'IT' => array('country' => 'Italy', 'owner' => ''),
1532
			'ITSO' => array('country' => 'USA', 'owner' => 'Intelsat, S.A.'),
1533
			'JPN' => array('country' => 'Japan', 'owner' => ''),
1534
			'KAZ' => array('country' => 'Kazakhstan', 'owner' => ''),
1535
			'LAOS' => array('country' => 'Laos', 'owner' => ''),
1536
			'LTU' => array('country' => 'Lithuania', 'owner' => ''),
1537
			'LUXE' => array('country' => 'Luxembourg', 'owner' => ''),
1538
			'MALA' => array('country' => 'Malaysia', 'owner' => ''),
1539
			'MEX' => array('country' => 'Mexico', 'owner' => ''),
1540
			'NATO' => array('country' => 'Multinational', 'owner' => 'North Atlantic Treaty Organization'),
1541
			'NETH' => array('country' => 'Netherlands', 'owner' => ''),
1542
			'NICO' => array('country' => 'USA', 'owner' => 'New ICO'),
1543
			'NIG' => array('country' => 'Nigeria', 'owner' => ''),
1544
			'NKOR' => array('country' => 'North Korea', 'owner' => ''),
1545
			'NOR' => array('country' => 'Norway', 'owner' => ''),
1546
			'O3B' => array('country' => 'United Kingdom', 'owner' => 'O3b Networks Ltd.'),
1547
			'ORB' => array('country' => 'USA', 'owner' => 'ORBCOMM Inc.'),
1548
			'PAKI' => array('country' => 'Pakistan', 'owner' => ''),
1549
			'PERU' => array('country' => 'Peru', 'owner' => ''),
1550
			'POL' => array('country' => 'Poland', 'owner' => ''),
1551
			'POR' => array('country' => 'Portugal', 'owner' => ''),
1552
			'PRC' => array('country' => 'China', 'owner' => ''),
1553
			'PRES' => array('country' => 'Multinational', 'owner' => 'China/ESA'),
1554
			'RASC' => array('country' => 'Multinational', 'owner' => 'Regional African Satellite Communications Organisation (RASCOM)'),
1555
			'ROC' => array('country' => 'Taiwan', 'owner' => ''),
1556
			'ROM' => array('country' => 'Romania', 'owner' => ''),
1557
			'RP' => array('country' => 'Philippines', 'owner' => ''),
1558
			'SAFR' => array('country' => 'South Africa', 'owner' => ''),
1559
			'SAUD' => array('country' => 'Saudi Arabia', 'owner' => ''),
1560
			'SEAL' => array('country' => 'USA', 'owner' => ''),
1561
			'SES' => array('country' => 'Multinational', 'owner' => 'SES World Skies'),
1562
			'SING' => array('country' => 'Singapore', 'owner' => ''),
1563
			'SKOR' => array('country' => 'South Korea', 'owner' => ''),
1564
			'SPN' => array('country' => 'Spain', 'owner' => ''),
1565
			'STCT' => array('country' => 'Singapore/Taiwan', 'owner' => ''),
1566
			'SWED' => array('country' => 'Sweden', 'owner' => ''),
1567
			'SWTZ' => array('country' => 'Switzerland', 'owner' => ''),
1568
			'THAI' => array('country' => 'Thailand', 'owner' => ''),
1569
			'TMMC' => array('country' => 'Turkmenistan/Monaco', 'owner' => ''),
1570
			'TURK' => array('country' => 'Turkey', 'owner' => ''),
1571
			'UAE' => array('country' => 'United Arab Emirates', 'owner' => ''),
1572
			'UK' => array('country' => 'United Kingdom', 'owner' => ''),
1573
			'UKR' => array('country' => 'Ukraine', 'owner' => ''),
1574
			'URY' => array('country' => 'Uruguay', 'owner' => ''),
1575
			'US' => array('country' => 'USA', 'owner' => ''),
1576
			'USBZ' => array('country' => 'USA/Brazil', 'owner' => ''),
1577
			'VENZ' => array('country' => 'Venezuela', 'owner' => ''),
1578
			'VTNM' => array('country' => 'Vietnam', 'owner' => '')
1579
		);
1580
		$satcat_launch_site = array(
1581
			'AFETR' => 'Cape Canaveral',
1582
			'AFWTR' => 'Vandenberg AFB',
1583
			'CAS' => 'Canaries Airspace',
1584
			'DLS' => 'Dombarovsky Air Base',
1585
			'ERAS' => 'Eastern Range Airspace',
1586
			'FRGUI' => 'Guiana Space Center',
1587
			'HGSTR' => 'Hammaguira Space Track Range, Algeria',
1588
			'JSC' => 'Jiuquan Satellite Launch Center',
1589
			'KODAK' => 'Kodiak Launch Complex',
1590
			'KSCUT' => 'Uchinoura Space Center',
1591
			'KWAJ' => 'Kwajalein Island',
1592
			'KYMSC' => 'Kapustin Yar Missile and Space Complex, Russia',
1593
			'NSC' => 'Naro Space Center',
1594
			'PLMSC' => 'Plesetsk Cosmodrome',
1595
			'SEAL' => 'Sea Launch',
1596
			'SEMLS' => 'Semnan Satellite Launch Site, Iran',
1597
			'SNMLP' => 'San Marco Launch Platform, Indian Ocean (Kenya)',
1598
			'SRILR' => 'Satish Dhawan Space Center',
1599
			'SUBL' => 'Submarine Launch Platform (mobile), Russia',
1600
			'SVOBO' => 'Svobodny Cosmodrome',
1601
			'TAISC' => 'Taiyuan Launch Center',
1602
			'TANSC' => 'Tanegashima Space Center',
1603
			'TYMSC' => 'Baikonur Cosmodrome',
1604
			'VOSTO' => 'Vostochny Cosmodrome',
1605
			'WLPIS' => 'Wallops Island Flight Facility',
1606
			'WOMRA' => 'Woomera, Australia',
1607
			'WRAS' => 'Western Range Airspace',
1608
			'WSC' => 'Wenchang Satellite Launch Center',
1609
			'XICLF' => 'Xichang Satellite Launch Center',
1610
			'YAVNE' => 'Palmachim Launch Complex',
1611
			'YUN' => 'Yunsong Launch Site'
1612
		);
1613
1614
		/*
1615
		$query = "DELETE FROM satellite";
1616
		try {
1617
			$Connection = new Connection();
1618
			$sth = $Connection->db->prepare($query);
1619
			$sth->execute(array(':source' => $filename));
1620
		} catch(PDOException $e) {
1621
			return "error : ".$e->getMessage();
1622
		}
1623
		*/
1624
		
1625
		$Connection = new Connection();
1626
		if (($handle = fopen($filename, 'r')) !== FALSE)
1627
		{
1628
			$i = 0;
1629
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1630
			//$Connection->db->beginTransaction();
1631
			while (($data = fgets($handle, 1000)) !== FALSE)
1632
			{
1633
				$result = array();
1634
				$result['cospar'] = trim(substr($data,0,11));
1635
				$result['norad'] = trim(substr($data,13,6));
1636
				$result['operational'] = trim(substr($data,21,1));
1637
				$result['name'] = trim(substr($data,23,24));
1638
				/*
1639
				    * R/B(1) = Rocket body, first stage
1640
				    * R/B(2) = Rocket body, second stage
1641
				    * DEB = Debris
1642
				    * PLAT = Platform
1643
				    * Items in parentheses are alternate names
1644
				    * Items in brackets indicate type of object
1645
				    (e.g., BREEZE-M DEB [TANK] = tank)
1646
				    * An ampersand (&) indicates two or more objects are attached
1647
				*/
1648
				
1649
				$owner_code = trim(substr($data,49,5));
1650
				if ($owner_code != 'TBD') {
1651
					$result['country_owner'] = $satcat_sources[$owner_code]['country'];
1652
					$result['owner'] = $satcat_sources[$owner_code]['owner'];
1653
					$result['launch_date'] = trim(substr($data,56,10));
1654
					$launch_site_code = trim(substr($data,68,5));
1655
					$result['launch_site'] = $satcat_launch_site[$launch_site_code];
1656
					$result['lifetime'] = trim(substr($data,75,10));
1657
					$result['period'] = trim(substr($data,87,7));
1658
					$result['inclination'] = trim(substr($data,96,5));
1659
					$result['apogee'] = trim(substr($data,103,6));
1660
					$result['perigee'] = trim(substr($data,111,6));
1661
					//$result['radarcross'] = trim(substr($data,119,8));
1662
					$result['status'] = trim(substr($data,129,3));
1663
					//print_r($result);
1664
					$result = array_map(function($value) {
1665
						return trim($value) === '' ? null : $value;
1666
					}, $result);
1667
					//print_r($data);
1668
					if ($result['operational'] != 'D') {
1669
						$query = "SELECT * FROM satellite WHERE cospar = :cospar LIMIT 1";
1670
						try {
1671
							$Connection = new Connection();
1672
							$sth = $Connection->db->prepare($query);
1673
							$sth->execute(array(':cospar' => $result['cospar']));
1674
							$exist = $sth->fetchAll(PDO::FETCH_ASSOC);
1675
						} catch(PDOException $e) {
1676
							return "error : ".$e->getMessage();
1677
						}
1678
						if (empty($exist)) {
1679
							$query = 'INSERT INTO satellite (name, name_alternate, country_un, country_owner, owner, users, purpose, purpose_detailed, orbit, type, longitude_geo, perigee, apogee, eccentricity, inclination, period, launch_mass, dry_mass, power, launch_date, lifetime, contractor, country_contractor, launch_site, launch_vehicule, cospar, norad, comments, source_orbital, sources) 
1680
							    VALUES (:name, :name_alternate, :country_un, :country_owner, :owner, :users, :purpose, :purpose_detailed, :orbit, :type, :longitude_geo, :perigee, :apogee, :eccentricity, :inclination, :period, :launch_mass, :dry_mass, :power, :launch_date, :lifetime, :contractor, :country_contractor, :launch_site, :launch_vehicule, :cospar, :norad, :comments, :source_orbital, :sources)';
1681
							try {
1682
								$sth = $Connection->db->prepare($query);
1683
								$sth->execute(array(
1684
								    ':name' => $result['name'], ':name_alternate' => '', ':country_un' => '', ':country_owner' => $result['country_owner'], ':owner' => $result['owner'], ':users' => '', ':purpose' => '', ':purpose_detailed' => '', ':orbit' => $result['status'],
1685
								    ':type' => '', ':longitude_geo' => NULL, ':perigee' => !empty($result['perigee']) ? $result['perigee'] : NULL, ':apogee' => !empty($result['apogee']) ? $result['apogee'] : NULL, ':eccentricity' => NULL, ':inclination' => $result['inclination'],
1686
								    ':period' => !empty($result['period']) ? $result['period'] : NULL, ':launch_mass' => NULL, ':dry_mass' => NULL, ':power' => NULL, ':launch_date' => $result['launch_date'], ':lifetime' => $result['lifetime'], 
1687
								    ':contractor' => '',':country_contractor' => '', ':launch_site' => $result['launch_site'], ':launch_vehicule' => '', ':cospar' => $result['cospar'], ':norad' => $result['norad'], ':comments' => '', ':source_orbital' => '', ':sources' => ''
1688
								    )
1689
								);
1690
							} catch(PDOException $e) {
1691
								return "error : ".$e->getMessage();
1692
							}
1693
						} elseif ($exist[0]['name'] != $result['name'] && $exist[0]['name_alternate'] != $result['name']) {
1694
							$query = "UPDATE satellite SET name_alternate = :name_alternate WHERE cospar = :cospar";
1695
							try {
1696
								$Connection = new Connection();
1697
								$sth = $Connection->db->prepare($query);
1698
								$sth->execute(array(':name_alternate' => $result['name'],':cospar' => $result['cospar']));
1699
							} catch(PDOException $e) {
1700
								return "error : ".$e->getMessage();
1701
							}
1702
						}
1703
					}
1704
				}
1705
				
1706
				$i++;
1707
			}
1708
			fclose($handle);
1709
			//$Connection->db->commit();
1710
		}
1711
		return '';
1712
        }
1713
1714
	/**
1715
        * Convert a HTML table to an array
1716
        * @param String $data HTML page
1717
        * @return Array array of the tables in HTML page
1718
        */
1719
/*
1720
        private static function table2array($data) {
1721
                $html = str_get_html($data);
1722
                $tabledata=array();
1723
                foreach($html->find('tr') as $element)
1724
                {
1725
                        $td = array();
1726
                        foreach( $element->find('th') as $row)
1727
                        {
1728
                                $td [] = trim($row->plaintext);
1729
                        }
1730
                        $td=array_filter($td);
1731
                        $tabledata[] = $td;
1732
1733
                        $td = array();
1734
                        $tdi = array();
1735
                        foreach( $element->find('td') as $row)
1736
                        {
1737
                                $td [] = trim($row->plaintext);
1738
                                $tdi [] = trim($row->innertext);
1739
                        }
1740
                        $td=array_filter($td);
1741
                        $tdi=array_filter($tdi);
1742
                    //    $tabledata[]=array_merge($td,$tdi);
1743
                        $tabledata[]=$td;
1744
                }
1745
                return(array_filter($tabledata));
1746
        }
1747
*/
1748
       /**
1749
        * Get data from form result
1750
        * @param String $url form URL
1751
        * @return String the result
1752
        */
1753
/*
1754
        private static function getData($url) {
1755
                $ch = curl_init();
1756
                curl_setopt($ch, CURLOPT_URL, $url);
1757
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1758
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1759
                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');
1760
                return curl_exec($ch);
1761
        }
1762
*/
1763
/*
1764
	public static function waypoints() {
1765
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1766
		$table = update_db::table2array($data);
1767
//		print_r($table);
1768
		$query = 'TRUNCATE TABLE waypoints';
1769
		try {
1770
			$Connection = new Connection();
1771
			$sth = $Connection->db->prepare($query);
1772
                        $sth->execute();
1773
                } catch(PDOException $e) {
1774
                        return "error : ".$e->getMessage();
1775
                }
1776
1777
		$query_dest = 'INSERT INTO waypoints (ident,latitude,longitude,control,usage) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1778
		$Connection = new Connection();
1779
		$sth_dest = $Connection->db->prepare($query_dest);
1780
		$Connection->db->beginTransaction();
1781
                foreach ($table as $row) {
1782
            		if ($row[0] != 'Ident') {
1783
				$ident = $row[0];
1784
				$latitude = $row[2];
1785
				$longitude = $row[3];
1786
				$control = $row[4];
1787
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1788
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1789
				try {
1790
					$sth_dest->execute($query_dest_values);
1791
				} catch(PDOException $e) {
1792
					return "error : ".$e->getMessage();
1793
				}
1794
			}
1795
                }
1796
		$Connection->db->commit();
1797
1798
	}
1799
*/
1800
	public static function waypoints($filename) {
1801
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1802
		global $tmp_dir, $globalTransaction;
1803
		//$Spotter = new Spotter();
1804
		//$out_file = $tmp_dir.'translation.zip';
1805
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1806
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1807
		$Connection = new Connection();
1808
		//update_db::unzip($out_file);
1809
		$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...
1810
		$delimiter = ' ';
1811
		if (($handle = fopen($filename, 'r')) !== FALSE)
1812
		{
1813
			$i = 0;
1814
			if ($globalTransaction) $Connection->db->beginTransaction();
1815
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1816
			{
1817
				$i++;
1818
				if($i > 3 && count($row) > 2) {
1819
					$data = array_values(array_filter($row));
1820
					$cntdata = count($data);
1821
					if ($cntdata > 10) {
1822
						$value = $data[9];
1823
						
1824
						for ($i =10;$i < $cntdata;$i++) {
1825
							$value .= ' '.$data[$i];
1826
						}
1827
						$data[9] = $value;
1828
					}
1829
					//print_r($data);
1830
					if (count($data) > 9) {
1831
						$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)';
1832
						try {
1833
							$sth = $Connection->db->prepare($query);
1834
							$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]));
1835
						} catch(PDOException $e) {
1836
							return "error : ".$e->getMessage();
1837
						}
1838
					}
1839
				}
1840
			}
1841
			fclose($handle);
1842
			if ($globalTransaction) $Connection->db->commit();
1843
		}
1844
		return '';
1845
        }
1846
1847
	public static function ivao_airlines($filename) {
1848
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1849
		global $tmp_dir, $globalTransaction;
1850
		//$query = 'TRUNCATE TABLE airlines';
1851
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1852
		try {
1853
			$Connection = new Connection();
1854
			$sth = $Connection->db->prepare($query);
1855
                        $sth->execute();
1856
                } catch(PDOException $e) {
1857
                        return "error : ".$e->getMessage();
1858
                }
1859
1860
		$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...
1861
		$delimiter = ':';
1862
		$Connection = new Connection();
1863
		if (($handle = fopen($filename, 'r')) !== FALSE)
1864
		{
1865
			if ($globalTransaction) $Connection->db->beginTransaction();
1866
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1867
			{
1868
				if(count($row) > 1) {
1869
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1870
					try {
1871
						$sth = $Connection->db->prepare($query);
1872
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1873
					} catch(PDOException $e) {
1874
						return "error : ".$e->getMessage();
1875
					}
1876
				}
1877
			}
1878
			fclose($handle);
1879
			if ($globalTransaction) $Connection->db->commit();
1880
		}
1881
		return '';
1882
        }
1883
	
1884
	public static function update_airspace() {
1885
		global $tmp_dir, $globalDBdriver;
1886
		include_once('class.create_db.php');
1887
		$Connection = new Connection();
1888
		if ($Connection->tableExists('airspace')) {
1889
			$query = 'DROP TABLE airspace';
1890
			try {
1891
				$sth = $Connection->db->prepare($query);
1892
                    		$sth->execute();
1893
	                } catch(PDOException $e) {
1894
				return "error : ".$e->getMessage();
1895
	                }
1896
	        }
1897
1898
1899
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1900
		else {
1901
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1902
			$query = "CREATE EXTENSION postgis";
1903
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1904
			try {
1905
				$sth = $Connection->db->prepare($query);
1906
				$sth->execute();
1907
			} catch(PDOException $e) {
1908
				return "error : ".$e->getMessage();
1909
			}
1910
		}
1911
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1912
		return $error;
1913
	}
1914
1915
	public static function update_notam_fam() {
1916
		global $tmp_dir, $globalDebug;
1917
		include_once('class.create_db.php');
1918
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1919
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1920
		update_db::download('http://data.flightairmap.com/data/notam.txt.gz.md5',$tmp_dir.'notam.txt.gz.md5');
1921
		$error = '';
1922
		if (file_exists($tmp_dir.'notam.txt.gz.md5')) {
1923
			$notam_md5_file = explode(' ',file_get_contents($tmp_dir.'notam.txt.gz.md5'));
1924
			$notam_md5 = $notam_md5_file[0];
1925
			if (!update_db::check_notam_version($notam_md5)) {
1926
				update_db::download('http://data.flightairmap.com/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1927
				if (file_exists($tmp_dir.'notam.txt.gz')) {
1928
					if (md5_file($tmp_dir.'notam.txt.gz') == $notam_md5) {
1929
						if ($globalDebug) echo "Gunzip...";
1930
						update_db::gunzip($tmp_dir.'notam.txt.gz');
1931
						if ($globalDebug) echo "Add to DB...";
1932
						//$error = create_db::import_file($tmp_dir.'notam.sql');
1933
						$NOTAM = new NOTAM();
1934
						$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1935
						update_db::insert_notam_version($notam_md5);
1936
					} else $error = "File ".$tmp_dir.'notam.txt.gz'." md5 failed. Download failed.";
1937
				} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1938
			} elseif ($globalDebug) echo "No new version.";
1939
		} else $error = "File ".$tmp_dir.'notam.txt.gz.md5'." doesn't exist. Download failed.";
1940
		if ($error != '') {
1941
			return $error;
1942
		} elseif ($globalDebug) echo "Done\n";
1943
		return '';
1944
	}
1945
1946
	public static function update_vatsim() {
1947
		global $tmp_dir;
1948
		include_once('class.create_db.php');
1949
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1950
		return $error;
1951
	}
1952
	
1953
	public static function update_countries() {
1954
		global $tmp_dir, $globalDBdriver;
1955
		include_once('class.create_db.php');
1956
		$Connection = new Connection();
1957
		if ($Connection->tableExists('countries')) {
1958
			$query = 'DROP TABLE countries';
1959
			try {
1960
				$sth = $Connection->db->prepare($query);
1961
            	        	$sth->execute();
1962
	                } catch(PDOException $e) {
1963
    	                	echo "error : ".$e->getMessage();
1964
	                }
1965
		}
1966
		if ($globalDBdriver == 'mysql') {
1967
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1968
		} else {
1969
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1970
		}
1971
		$error = create_db::import_file($tmp_dir.'countries.sql');
1972
		return $error;
1973
	}
1974
1975
	
1976
	public static function update_waypoints() {
1977
		global $tmp_dir;
1978
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1979
//		update_db::unzip($tmp_dir.'AptNav.zip');
1980
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1981
//		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');
1982
		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');
1983
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1984
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1985
		return $error;
1986
	}
1987
1988
	public static function update_ivao() {
1989
		global $tmp_dir, $globalDebug;
1990
		$Common = new Common();
1991
		$error = '';
1992
		//Direct download forbidden
1993
		//if ($globalDebug) echo "IVAO : Download...";
1994
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1995
		if (extension_loaded('zip')) {
1996
			if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1997
				if ($globalDebug) echo "Unzip...";
1998
				update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1999
				if ($globalDebug) echo "Add to DB...";
2000
				update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
2001
				if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
2002
				if (is_writable(dirname(__FILE__).'/../images/airlines')) {
2003
					if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
2004
				} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
2005
			} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
2006
		} else $error = "ZIP module not loaded but required for IVAO.";
2007
		if ($error != '') {
2008
			return $error;
2009
		} elseif ($globalDebug) echo "Done\n";
2010
		return '';
2011
	}
2012
2013
	public static function update_routes() {
2014
		global $tmp_dir, $globalDebug;
2015
		$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...
2016
		if ($globalDebug) echo "Routes : Download...";
2017
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
2018
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
2019
			if ($globalDebug) echo "Gunzip...";
2020
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
2021
			if ($globalDebug) echo "Add to DB...";
2022
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
2023
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
2024
		if ($error != '') {
2025
			return $error;
2026
		} elseif ($globalDebug) echo "Done\n";
2027
		return '';
2028
	}
2029
	public static function update_oneworld() {
2030
		global $tmp_dir, $globalDebug;
2031
		$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...
2032
		if ($globalDebug) echo "Schedules Oneworld : Download...";
2033
		update_db::download('http://data.flightairmap.com/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
2034
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
2035
			if ($globalDebug) echo "Gunzip...";
2036
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
2037
			if ($globalDebug) echo "Add to DB...";
2038
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
2039
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
2040
		if ($error != '') {
2041
			return $error;
2042
		} elseif ($globalDebug) echo "Done\n";
2043
		return '';
2044
	}
2045
	public static function update_skyteam() {
2046
		global $tmp_dir, $globalDebug;
2047
		$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...
2048
		if ($globalDebug) echo "Schedules Skyteam : Download...";
2049
		update_db::download('http://data.flightairmap.com/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
2050
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
2051
			if ($globalDebug) echo "Gunzip...";
2052
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
2053
			if ($globalDebug) echo "Add to DB...";
2054
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
2055
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
2056
		if ($error != '') {
2057
			return $error;
2058
		} elseif ($globalDebug) echo "Done\n";
2059
		return '';
2060
	}
2061
	public static function update_ModeS() {
2062
		global $tmp_dir, $globalDebug;
2063
/*
2064
		if ($globalDebug) echo "Modes : Download...";
2065
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
2066
		if ($globalDebug) echo "Unzip...";
2067
		update_db::unzip($tmp_dir.'basestation_latest.zip');
2068
		if ($globalDebug) echo "Add to DB...";
2069
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
2070
		if ($error != true) {
2071
			echo $error;
2072
			exit;
2073
		} elseif ($globalDebug) echo "Done\n";
2074
*/
2075
		if ($globalDebug) echo "Modes : Download...";
2076
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
2077
		update_db::download('http://data.flightairmap.com/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
2078
2079
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
2080
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
2081
			if ($globalDebug) echo "Unzip...";
2082
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
2083
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
2084
			if ($globalDebug) echo "Add to DB...";
2085
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
2086
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
2087
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
2088
		if ($error != '') {
2089
			return $error;
2090
		} elseif ($globalDebug) echo "Done\n";
2091
		return '';
2092
	}
2093
2094
	public static function update_ModeS_faa() {
2095
		global $tmp_dir, $globalDebug;
2096
		if ($globalDebug) echo "Modes FAA: Download...";
2097
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
2098
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
2099
			if ($globalDebug) echo "Unzip...";
2100
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
2101
			if ($globalDebug) echo "Add to DB...";
2102
			$error = update_db::modes_faa();
2103
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
2104
		if ($error != '') {
2105
			return $error;
2106
		} elseif ($globalDebug) echo "Done\n";
2107
		return '';
2108
	}
2109
2110
	public static function update_ModeS_flarm() {
2111
		global $tmp_dir, $globalDebug;
2112
		if ($globalDebug) echo "Modes Flarmnet: Download...";
2113
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
2114
		if (file_exists($tmp_dir.'data.fln')) {
2115
			if ($globalDebug) echo "Add to DB...";
2116
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
2117
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
2118
		if ($error != '') {
2119
			return $error;
2120
		} elseif ($globalDebug) echo "Done\n";
2121
		return '';
2122
	}
2123
2124
	public static function update_ModeS_ogn() {
2125
		global $tmp_dir, $globalDebug;
2126
		if ($globalDebug) echo "Modes OGN: Download...";
2127
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
2128
		if (file_exists($tmp_dir.'ogn.csv')) {
2129
			if ($globalDebug) echo "Add to DB...";
2130
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
2131
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
2132
		if ($error != '') {
2133
			return $error;
2134
		} elseif ($globalDebug) echo "Done\n";
2135
		return '';
2136
	}
2137
2138
	public static function update_owner() {
2139
		global $tmp_dir, $globalDebug, $globalMasterSource;
2140
		
2141
		if ($globalDebug) echo "Owner France: Download...";
2142
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
2143
		if (file_exists($tmp_dir.'owner_f.csv')) {
2144
			if ($globalDebug) echo "Add to DB...";
2145
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
2146
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
2147
		if ($error != '') {
2148
			return $error;
2149
		} elseif ($globalDebug) echo "Done\n";
2150
		
2151
		if ($globalDebug) echo "Owner Ireland: Download...";
2152
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
2153
		if (file_exists($tmp_dir.'owner_ei.csv')) {
2154
			if ($globalDebug) echo "Add to DB...";
2155
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
2156
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
2157
		if ($error != '') {
2158
			return $error;
2159
		} elseif ($globalDebug) echo "Done\n";
2160
		if ($globalDebug) echo "Owner Switzerland: Download...";
2161
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
2162
		if (file_exists($tmp_dir.'owner_hb.csv')) {
2163
			if ($globalDebug) echo "Add to DB...";
2164
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
2165
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
2166
		if ($error != '') {
2167
			return $error;
2168
		} elseif ($globalDebug) echo "Done\n";
2169
		if ($globalDebug) echo "Owner Czech Republic: Download...";
2170
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
2171
		if (file_exists($tmp_dir.'owner_ok.csv')) {
2172
			if ($globalDebug) echo "Add to DB...";
2173
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
2174
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
2175
		if ($error != '') {
2176
			return $error;
2177
		} elseif ($globalDebug) echo "Done\n";
2178
		if ($globalDebug) echo "Owner Australia: Download...";
2179
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
2180
		if (file_exists($tmp_dir.'owner_vh.csv')) {
2181
			if ($globalDebug) echo "Add to DB...";
2182
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
2183
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
2184
		if ($error != '') {
2185
			return $error;
2186
		} elseif ($globalDebug) echo "Done\n";
2187
		if ($globalDebug) echo "Owner Austria: Download...";
2188
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
2189
		if (file_exists($tmp_dir.'owner_oe.csv')) {
2190
			if ($globalDebug) echo "Add to DB...";
2191
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
2192
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
2193
		if ($error != '') {
2194
			return $error;
2195
		} elseif ($globalDebug) echo "Done\n";
2196
		if ($globalDebug) echo "Owner Chile: Download...";
2197
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
2198
		if (file_exists($tmp_dir.'owner_cc.csv')) {
2199
			if ($globalDebug) echo "Add to DB...";
2200
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
2201
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
2202
		if ($error != '') {
2203
			return $error;
2204
		} elseif ($globalDebug) echo "Done\n";
2205
		if ($globalDebug) echo "Owner Colombia: Download...";
2206
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
2207
		if (file_exists($tmp_dir.'owner_hj.csv')) {
2208
			if ($globalDebug) echo "Add to DB...";
2209
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
2210
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
2211
		if ($error != '') {
2212
			return $error;
2213
		} elseif ($globalDebug) echo "Done\n";
2214
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
2215
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
2216
		if (file_exists($tmp_dir.'owner_e7.csv')) {
2217
			if ($globalDebug) echo "Add to DB...";
2218
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
2219
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
2220
		if ($error != '') {
2221
			return $error;
2222
		} elseif ($globalDebug) echo "Done\n";
2223
		if ($globalDebug) echo "Owner Brazil: Download...";
2224
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
2225
		if (file_exists($tmp_dir.'owner_pp.csv')) {
2226
			if ($globalDebug) echo "Add to DB...";
2227
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
2228
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
2229
		if ($error != '') {
2230
			return $error;
2231
		} elseif ($globalDebug) echo "Done\n";
2232
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
2233
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
2234
		if (file_exists($tmp_dir.'owner_vp.csv')) {
2235
			if ($globalDebug) echo "Add to DB...";
2236
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
2237
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
2238
		if ($error != '') {
2239
			return $error;
2240
		} elseif ($globalDebug) echo "Done\n";
2241
		if ($globalDebug) echo "Owner Croatia: Download...";
2242
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
2243
		if (file_exists($tmp_dir.'owner_9a.csv')) {
2244
			if ($globalDebug) echo "Add to DB...";
2245
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
2246
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
2247
		if ($error != '') {
2248
			return $error;
2249
		} elseif ($globalDebug) echo "Done\n";
2250
		if ($globalDebug) echo "Owner Luxembourg: Download...";
2251
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
2252
		if (file_exists($tmp_dir.'owner_lx.csv')) {
2253
			if ($globalDebug) echo "Add to DB...";
2254
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
2255
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
2256
		if ($error != '') {
2257
			return $error;
2258
		} elseif ($globalDebug) echo "Done\n";
2259
		if ($globalDebug) echo "Owner Maldives: Download...";
2260
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
2261
		if (file_exists($tmp_dir.'owner_8q.csv')) {
2262
			if ($globalDebug) echo "Add to DB...";
2263
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
2264
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
2265
		if ($error != '') {
2266
			return $error;
2267
		} elseif ($globalDebug) echo "Done\n";
2268
		if ($globalDebug) echo "Owner New Zealand: Download...";
2269
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
2270
		if (file_exists($tmp_dir.'owner_zk.csv')) {
2271
			if ($globalDebug) echo "Add to DB...";
2272
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
2273
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
2274
		if ($error != '') {
2275
			return $error;
2276
		} elseif ($globalDebug) echo "Done\n";
2277
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
2278
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
2279
		if (file_exists($tmp_dir.'owner_p2.csv')) {
2280
			if ($globalDebug) echo "Add to DB...";
2281
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
2282
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
2283
		if ($error != '') {
2284
			return $error;
2285
		} elseif ($globalDebug) echo "Done\n";
2286
		if ($globalDebug) echo "Owner Slovakia: Download...";
2287
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
2288
		if (file_exists($tmp_dir.'owner_om.csv')) {
2289
			if ($globalDebug) echo "Add to DB...";
2290
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
2291
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
2292
		if ($error != '') {
2293
			return $error;
2294
		} elseif ($globalDebug) echo "Done\n";
2295
		if ($globalDebug) echo "Owner Ecuador: Download...";
2296
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
2297
		if (file_exists($tmp_dir.'owner_hc.csv')) {
2298
			if ($globalDebug) echo "Add to DB...";
2299
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
2300
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
2301
		if ($error != '') {
2302
			return $error;
2303
		} elseif ($globalDebug) echo "Done\n";
2304
		if ($globalDebug) echo "Owner Iceland: Download...";
2305
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
2306
		if (file_exists($tmp_dir.'owner_tf.csv')) {
2307
			if ($globalDebug) echo "Add to DB...";
2308
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
2309
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
2310
		if ($error != '') {
2311
			return $error;
2312
		} elseif ($globalDebug) echo "Done\n";
2313
		if ($globalDebug) echo "Owner Isle of Man: Download...";
2314
		update_db::download('http://antonakis.co.uk/registers/IsleOfMan.txt',$tmp_dir.'owner_m.csv');
2315
		if (file_exists($tmp_dir.'owner_m.csv')) {
2316
			if ($globalDebug) echo "Add to DB...";
2317
			$error = update_db::retrieve_owner($tmp_dir.'owner_m.csv','M');
2318
		} else $error = "File ".$tmp_dir.'owner_m.csv'." doesn't exist. Download failed.";
2319
		if ($error != '') {
2320
			return $error;
2321
		} elseif ($globalDebug) echo "Done\n";
2322
		if ($globalMasterSource) {
2323
			if ($globalDebug) echo "ModeS Netherlands: Download...";
2324
			update_db::download('http://antonakis.co.uk/registers/Netherlands.txt',$tmp_dir.'owner_ph.csv');
2325
			if (file_exists($tmp_dir.'owner_ph.csv')) {
2326
				if ($globalDebug) echo "Add to DB...";
2327
				$error = update_db::retrieve_owner($tmp_dir.'owner_ph.csv','PH');
2328
			} else $error = "File ".$tmp_dir.'owner_ph.csv'." doesn't exist. Download failed.";
2329
			if ($error != '') {
2330
				return $error;
2331
			} elseif ($globalDebug) echo "Done\n";
2332
			if ($globalDebug) echo "ModeS Denmark: Download...";
2333
			update_db::download('http://antonakis.co.uk/registers/Denmark.txt',$tmp_dir.'owner_oy.csv');
2334
			if (file_exists($tmp_dir.'owner_oy.csv')) {
2335
				if ($globalDebug) echo "Add to DB...";
2336
				$error = update_db::retrieve_owner($tmp_dir.'owner_oy.csv','OY');
2337
			} else $error = "File ".$tmp_dir.'owner_oy.csv'." doesn't exist. Download failed.";
2338
			if ($error != '') {
2339
				return $error;
2340
			} elseif ($globalDebug) echo "Done\n";
2341
		} elseif ($globalDebug) echo "Done\n";
2342
		return '';
2343
	}
2344
2345
	public static function update_translation() {
2346
		global $tmp_dir, $globalDebug;
2347
		$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...
2348
		if ($globalDebug) echo "Translation : Download...";
2349
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
2350
		if (file_exists($tmp_dir.'translation.zip')) {
2351
			if ($globalDebug) echo "Unzip...";
2352
			update_db::unzip($tmp_dir.'translation.zip');
2353
			if ($globalDebug) echo "Add to DB...";
2354
			$error = update_db::translation();
2355
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
2356
		if ($error != '') {
2357
			return $error;
2358
		} elseif ($globalDebug) echo "Done\n";
2359
		return '';
2360
	}
2361
2362
	public static function update_translation_fam() {
2363
		global $tmp_dir, $globalDebug;
2364
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
2365
		update_db::download('http://data.flightairmap.com/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
2366
		update_db::download('http://data.flightairmap.com/data/translation.tsv.gz.md5',$tmp_dir.'translation.tsv.gz.md5');
2367
		if (file_exists($tmp_dir.'translation.tsv.gz') && file_exists($tmp_dir.'translation.tsv.gz')) {
2368
			$translation_md5_file = explode(' ',file_get_contents($tmp_dir.'translation.tsv.gz.md5'));
2369
			$translation_md5 = $translation_md5_file[0];
2370
			if (md5_file($tmp_dir.'translation.tsv.gz') == $translation_md5) {
2371
				if ($globalDebug) echo "Gunzip...";
2372
				update_db::gunzip($tmp_dir.'translation.tsv.gz');
2373
				if ($globalDebug) echo "Add to DB...";
2374
				$error = update_db::translation_fam();
2375
			} else $error = "File ".$tmp_dir.'translation.tsv.gz'." md5 failed. Download failed.";
2376
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
2377
		if ($error != '') {
2378
			return $error;
2379
		} elseif ($globalDebug) echo "Done\n";
2380
		return '';
2381
	}
2382
	public static function update_ModeS_fam() {
2383
		global $tmp_dir, $globalDebug;
2384
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
2385
		update_db::download('http://data.flightairmap.com/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
2386
		update_db::download('http://data.flightairmap.com/data/modes.tsv.gz.md5',$tmp_dir.'modes.tsv.gz.md5');
2387
		if (file_exists($tmp_dir.'modes.tsv.gz') && file_exists($tmp_dir.'modes.tsv.gz.md5')) {
2388
			$modes_md5_file = explode(' ',file_get_contents($tmp_dir.'modes.tsv.gz.md5'));
2389
			$modes_md5 = $modes_md5_file[0];
2390
			if (md5_file($tmp_dir.'modes.tsv.gz') == $modes_md5) {
2391
				if ($globalDebug) echo "Gunzip...";
2392
				update_db::gunzip($tmp_dir.'modes.tsv.gz');
2393
				if ($globalDebug) echo "Add to DB...";
2394
				$error = update_db::modes_fam();
2395
			} else $error = "File ".$tmp_dir.'modes.tsv.gz'." md5 failed. Download failed.";
2396
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
2397
		if ($error != '') {
2398
			return $error;
2399
		} elseif ($globalDebug) echo "Done\n";
2400
		return '';
2401
	}
2402
2403
	public static function update_airlines_fam() {
2404
		global $tmp_dir, $globalDebug;
2405
		if ($globalDebug) echo "Airlines from FlightAirMap website : Download...";
2406
		update_db::download('http://data.flightairmap.com/data/airlines.tsv.gz',$tmp_dir.'airlines.tsv.gz');
2407
		if (file_exists($tmp_dir.'airlines.tsv.gz.md5')) {
2408
			$airlines_md5_file = explode(' ',file_get_contents($tmp_dir.'airlines.tsv.gz.md5'));
2409
			$airlines_md5 = $airlines_md5_file[0];
2410
			if (!update_db::check_airlines_version($airlines_md5)) {
2411
				update_db::download('http://data.flightairmap.com/data/airliness.tsv.gz.md5',$tmp_dir.'airlines.tsv.gz.md5');
2412
				if (file_exists($tmp_dir.'airlines.tsv.gz')) {
2413
					if (md5_file($tmp_dir.'airlines.tsv.gz') == $airlines_md5) {
2414
						if ($globalDebug) echo "Gunzip...";
2415
						update_db::gunzip($tmp_dir.'airlines.tsv.gz');
2416
						if ($globalDebug) echo "Add to DB...";
2417
						$error = update_db::airlines_fam();
2418
						update_db::insert_airlines_version($airlines_md5);
2419
					} else $error = "File ".$tmp_dir.'airlines.tsv.gz'." md5 failed. Download failed.";
2420
			    } else $error = "File ".$tmp_dir.'airlines.tsv.gz'." doesn't exist. Download failed.";
2421
			} elseif ($globalDebug) echo "No update";
2422
		} else $error = "File ".$tmp_dir.'airlines.tsv.gz.md5'." doesn't exist. Download failed.";
2423
		if ($error != '') {
2424
			return $error;
0 ignored issues
show
Bug introduced by
The variable $error does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2425
		} else {
2426
			if ($globalDebug) echo "Done\n";
2427
		}
2428
		return '';
2429
	}
2430
2431
	public static function update_owner_fam() {
2432
		global $tmp_dir, $globalDebug, $globalOwner;
2433
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
2434
		if ($globalOwner === TRUE) {
2435
			update_db::download('http://data.flightairmap.com/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
2436
			update_db::download('http://data.flightairmap.com/data/owners_all.tsv.gz.md5',$tmp_dir.'owners.tsv.gz.md5');
2437
		} else {
2438
			update_db::download('http://data.flightairmap.com/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
2439
			update_db::download('http://data.flightairmap.com/data/owners.tsv.gz.md5',$tmp_dir.'owners.tsv.gz.md5');
2440
		}
2441
		if (file_exists($tmp_dir.'owners.tsv.gz') && file_exists($tmp_dir.'owners.tsv.gz.md5')) {
2442
			$owners_md5_file = explode(' ',file_get_contents($tmp_dir.'owners.tsv.gz.md5'));
2443
			$owners_md5 = $owners_md5_file[0];
2444
			if (md5_file($tmp_dir.'owners.tsv.gz') == $owners_md5) {
2445
				if ($globalDebug) echo "Gunzip...";
2446
				update_db::gunzip($tmp_dir.'owners.tsv.gz');
2447
				if ($globalDebug) echo "Add to DB...";
2448
				$error = update_db::owner_fam();
2449
			} else $error = "File ".$tmp_dir.'owners.tsv.gz'." md5 failed. Download failed.";
2450
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
2451
		if ($error != '') {
2452
			return $error;
2453
		} elseif ($globalDebug) echo "Done\n";
2454
		return '';
2455
	}
2456
	public static function update_routes_fam() {
2457
		global $tmp_dir, $globalDebug;
2458
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
2459
		update_db::download('http://data.flightairmap.com/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
2460
		update_db::download('http://data.flightairmap.com/data/routes.tsv.gz.md5',$tmp_dir.'routes.tsv.gz.md5');
2461
		if (file_exists($tmp_dir.'routes.tsv.gz') && file_exists($tmp_dir.'routes.tsv.gz.md5')) {
2462
			$routes_md5_file = explode(' ',file_get_contents($tmp_dir.'routes.tsv.gz.md5'));
2463
			$routes_md5 = $routes_md5_file[0];
2464
			if (md5_file($tmp_dir.'routes.tsv.gz') == $routes_md5) {
2465
				if ($globalDebug) echo "Gunzip...";
2466
				update_db::gunzip($tmp_dir.'routes.tsv.gz');
2467
				if ($globalDebug) echo "Add to DB...";
2468
				$error = update_db::routes_fam();
2469
			} else $error = "File ".$tmp_dir.'routes.tsv.gz'." md5 failed. Download failed.";
2470
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
2471
		if ($error != '') {
2472
			return $error;
2473
		} elseif ($globalDebug) echo "Done\n";
2474
		return '';
2475
	}
2476
	public static function update_marine_identity_fam() {
2477
		global $tmp_dir, $globalDebug;
2478
		update_db::download('http://data.flightairmap.com/data/marine_identity.tsv.gz.md5',$tmp_dir.'marine_identity.tsv.gz.md5');
2479
		if (file_exists($tmp_dir.'marine_identity.tsv.gz.md5')) {
2480
			$marine_identity_md5_file = explode(' ',file_get_contents($tmp_dir.'marine_identity.tsv.gz.md5'));
2481
			$marine_identity_md5 = $marine_identity_md5_file[0];
2482
			if (!update_db::check_marine_identity_version($marine_identity_md5)) {
2483
				if ($globalDebug) echo "Marine identity from FlightAirMap website : Download...";
2484
				update_db::download('http://data.flightairmap.com/data/marine_identity.tsv.gz',$tmp_dir.'marine_identity.tsv.gz');
2485
				if (file_exists($tmp_dir.'marine_identity.tsv.gz')) {
2486
					if (md5_file($tmp_dir.'marine_identity.tsv.gz') == $marine_identity_md5) {
2487
						if ($globalDebug) echo "Gunzip...";
2488
						update_db::gunzip($tmp_dir.'marine_identity.tsv.gz');
2489
						if ($globalDebug) echo "Add to DB...";
2490
						$error = update_db::marine_identity_fam();
2491
					} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." md5 failed. Download failed.";
2492
				} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." doesn't exist. Download failed.";
2493
				if ($error != '') {
2494
					return $error;
2495
				} else {
2496
					update_db::insert_marine_identity_version($marine_identity_md5);
2497
					if ($globalDebug) echo "Done\n";
2498
				}
2499
			}
2500
		}
2501
		return '';
2502
	}
2503
2504
	public static function update_satellite_fam() {
2505
		global $tmp_dir, $globalDebug;
2506
		update_db::download('http://data.flightairmap.com/data/satellite.tsv.gz.md5',$tmp_dir.'satellite.tsv.gz.md5');
2507
		if (file_exists($tmp_dir.'satellite.tsv.gz.md5')) {
2508
			$satellite_md5_file = explode(' ',file_get_contents($tmp_dir.'satellite.tsv.gz.md5'));
2509
			$satellite_md5 = $satellite_md5_file[0];
2510
			if (!update_db::check_satellite_version($satellite_md5)) {
2511
				if ($globalDebug) echo "Satellite from FlightAirMap website : Download...";
2512
				update_db::download('http://data.flightairmap.com/data/satellite.tsv.gz',$tmp_dir.'satellite.tsv.gz');
2513
				if (file_exists($tmp_dir.'satellite.tsv.gz')) {
2514
					if (md5_file($tmp_dir.'satellite.tsv.gz') == $satellite_md5) {
2515
						if ($globalDebug) echo "Gunzip...";
2516
						update_db::gunzip($tmp_dir.'satellite.tsv.gz');
2517
						if ($globalDebug) echo "Add to DB...";
2518
						$error = update_db::satellite_fam();
2519
					} else $error = "File ".$tmp_dir.'satellite.tsv.gz'." md5 failed. Download failed.";
2520
				} else $error = "File ".$tmp_dir.'satellite.tsv.gz'." doesn't exist. Download failed.";
2521
				if ($error != '') {
2522
					return $error;
2523
				} else {
2524
					update_db::insert_satellite_version($satellite_md5);
2525
					if ($globalDebug) echo "Done\n";
2526
				}
2527
			}
2528
		}
2529
		return '';
2530
	}
2531
	public static function update_banned_fam() {
2532
		global $tmp_dir, $globalDebug;
2533
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
2534
		update_db::download('http://data.flightairmap.com/data/ban-eu.csv',$tmp_dir.'ban_eu.csv');
2535
		if (file_exists($tmp_dir.'ban_eu.csv')) {
2536
			//if ($globalDebug) echo "Gunzip...";
2537
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
2538
			if ($globalDebug) echo "Add to DB...";
2539
			$error = update_db::banned_fam();
2540
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
2541
		if ($error != '') {
2542
			return $error;
2543
		} elseif ($globalDebug) echo "Done\n";
2544
		return '';
2545
	}
2546
2547
	public static function update_airspace_fam() {
2548
		global $tmp_dir, $globalDebug, $globalDBdriver;
2549
		include_once('class.create_db.php');
2550
		$error = '';
2551
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
2552
		if ($globalDBdriver == 'mysql') {
2553
			update_db::download('http://data.flightairmap.com/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2554
		} else {
2555
			update_db::download('http://data.flightairmap.com/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2556
		}
2557
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
2558
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
2559
			$airspace_md5 = $airspace_md5_file[0];
2560
			if (!update_db::check_airspace_version($airspace_md5)) {
2561
				if ($globalDBdriver == 'mysql') {
2562
					update_db::download('http://data.flightairmap.com/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
2563
				} else {
2564
					update_db::download('http://data.flightairmap.com/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
2565
				}
2566
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
2567
					if (md5_file($tmp_dir.'airspace.sql.gz') == $airspace_md5) {
2568
						if ($globalDebug) echo "Gunzip...";
2569
						update_db::gunzip($tmp_dir.'airspace.sql.gz');
2570
						if ($globalDebug) echo "Add to DB...";
2571
						$Connection = new Connection();
2572
						if ($Connection->tableExists('airspace')) {
2573
							$query = 'DROP TABLE airspace';
2574
							try {
2575
								$sth = $Connection->db->prepare($query);
2576
								$sth->execute();
2577
							} catch(PDOException $e) {
2578
								return "error : ".$e->getMessage();
2579
							}
2580
						}
2581
						$error = create_db::import_file($tmp_dir.'airspace.sql');
2582
						update_db::insert_airspace_version($airspace_md5);
2583
					} else $error = "File ".$tmp_dir.'airspace.sql.gz'." md5 failed. Download failed.";
2584
				} else $error = "File ".$tmp_dir.'airspace.sql.gz'." doesn't exist. Download failed.";
2585
			}
2586
		} else $error = "File ".$tmp_dir.'airspace.sql.gz.md5'." doesn't exist. Download failed.";
2587
		if ($error != '') {
2588
			return $error;
2589
		} elseif ($globalDebug) echo "Done\n";
2590
		return '';
2591
	}
2592
2593
	public static function update_geoid_fam() {
2594
		global $tmp_dir, $globalDebug, $globalGeoidSource;
2595
		$error = '';
2596
		if ($globalDebug) echo "Geoid from FlightAirMap website : Download...";
2597
		update_db::download('http://data.flightairmap.com/data/geoid/'.$globalGeoidSource.'.pgm.gz.md5',$tmp_dir.$globalGeoidSource.'.pgm.gz.md5');
2598
		if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz.md5')) {
2599
			$geoid_md5_file = explode(' ',file_get_contents($tmp_dir.$globalGeoidSource.'.pgm.gz.md5'));
2600
			$geoid_md5 = $geoid_md5_file[0];
2601
			if (!update_db::check_geoid_version($geoid_md5)) {
2602
				update_db::download('http://data.flightairmap.com/data/geoid/'.$globalGeoidSource.'.pgm.gz',$tmp_dir.$globalGeoidSource.'.pgm.gz');
2603
				if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz')) {
2604
					if (md5_file($tmp_dir.$globalGeoidSource.'.pgm.gz') == $geoid_md5) {
2605
						if ($globalDebug) echo "Gunzip...";
2606
						update_db::gunzip($tmp_dir.$globalGeoidSource.'.pgm.gz',dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm');
2607
						if (file_exists(dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm')) {
2608
							update_db::insert_geoid_version($geoid_md5);
2609
						}
2610
					} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." md5 failed. Download failed.";
2611
				} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." doesn't exist. Download failed.";
2612
			}
2613
		} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz.md5'." doesn't exist. Download failed.";
2614
		if ($error != '') {
2615
			return $error;
2616
		} elseif ($globalDebug) echo "Done\n";
2617
		return '';
2618
	}
2619
2620
	public static function update_tle() {
2621
		global $tmp_dir, $globalDebug;
2622
		if ($globalDebug) echo "Download TLE : Download...";
2623
		$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',
2624
		'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',
2625
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt','visual.txt','sarsat.txt','argos.txt','ses.txt','iridium-NEXT.txt','beidou.txt');
2626
		foreach ($alltle as $filename) {
2627
			if ($globalDebug) echo "downloading ".$filename.'...';
2628
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
2629
			if (file_exists($tmp_dir.$filename)) {
2630
				if ($globalDebug) echo "Add to DB ".$filename."...";
2631
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
2632
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
2633
			if ($error != '') {
2634
				echo $error."\n";
2635
			} elseif ($globalDebug) echo "Done\n";
2636
		}
2637
		return '';
2638
	}
2639
2640
	public static function update_ucsdb() {
2641
		global $tmp_dir, $globalDebug;
2642
		if ($globalDebug) echo "Download UCS DB : Download...";
2643
		update_db::download('https://s3.amazonaws.com/ucs-documents/nuclear-weapons/sat-database/4-11-17-update/UCS_Satellite_Database_officialname_1-1-17.txt',$tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt');
2644
		if (file_exists($tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt')) {
2645
			if ($globalDebug) echo "Add to DB...";
2646
			$error = update_db::satellite_ucsdb($tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt');
2647
		} else $error = "File ".$tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt'." doesn't exist. Download failed.";
2648
		if ($error != '') {
2649
			echo $error."\n";
2650
		} elseif ($globalDebug) echo "Done\n";
2651
		return '';
2652
	}
2653
2654
	public static function update_celestrak() {
2655
		global $tmp_dir, $globalDebug;
2656
		if ($globalDebug) echo "Download Celestrak DB : Download...";
2657
		update_db::download('http://celestrak.com/pub/satcat.txt',$tmp_dir.'satcat.txt');
2658
		if (file_exists($tmp_dir.'satcat.txt')) {
2659
			if ($globalDebug) echo "Add to DB...";
2660
			$error = update_db::satellite_celestrak($tmp_dir.'satcat.txt');
2661
		} else $error = "File ".$tmp_dir.'satcat.txt'." doesn't exist. Download failed.";
2662
		if ($error != '') {
2663
			echo $error."\n";
2664
		} elseif ($globalDebug) echo "Done\n";
2665
		return '';
2666
	}
2667
2668
	public static function update_models() {
2669
		global $tmp_dir, $globalDebug;
2670
		$error = '';
2671
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2672
		update_db::download('http://data.flightairmap.com/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2673
		if (file_exists($tmp_dir.'models.md5sum')) {
2674
			if ($globalDebug) echo "Check files...\n";
2675
			$newmodelsdb = array();
2676
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2677
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2678
					$model = trim($row[2]);
2679
					$newmodelsdb[$model] = trim($row[0]);
2680
				}
2681
			}
2682
			$modelsdb = array();
2683
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2684
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2685
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2686
						$model = trim($row[2]);
2687
						$modelsdb[$model] = trim($row[0]);
2688
					}
2689
				}
2690
			}
2691
			$diff = array_diff($newmodelsdb,$modelsdb);
2692
			foreach ($diff as $key => $value) {
2693
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2694
				update_db::download('http://data.flightairmap.com/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2695
				
2696
			}
2697
			update_db::download('http://data.flightairmap.com/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2698
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2699
		if ($error != '') {
2700
			return $error;
2701
		} elseif ($globalDebug) echo "Done\n";
2702
		return '';
2703
	}
2704
2705
	public static function update_space_models() {
2706
		global $tmp_dir, $globalDebug;
2707
		$error = '';
2708
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2709
		update_db::download('http://data.flightairmap.com/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2710
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2711
			if ($globalDebug) echo "Check files...\n";
2712
			$newmodelsdb = array();
2713
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2714
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2715
					$model = trim($row[2]);
2716
					$newmodelsdb[$model] = trim($row[0]);
2717
				}
2718
			}
2719
			$modelsdb = array();
2720
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2721
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2722
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2723
						$model = trim($row[2]);
2724
						$modelsdb[$model] = trim($row[0]);
2725
					}
2726
				}
2727
			}
2728
			$diff = array_diff($newmodelsdb,$modelsdb);
2729
			foreach ($diff as $key => $value) {
2730
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2731
				update_db::download('http://data.flightairmap.com/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2732
				
2733
			}
2734
			update_db::download('http://data.flightairmap.com/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2735
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2736
		if ($error != '') {
2737
			return $error;
2738
		} elseif ($globalDebug) echo "Done\n";
2739
		return '';
2740
	}
2741
2742
	public static function update_vehicules_models() {
2743
		global $tmp_dir, $globalDebug;
2744
		$error = '';
2745
		if ($globalDebug) echo "Vehicules models from FlightAirMap website : Download...";
2746
		update_db::download('http://data.flightairmap.com/data/models/vehicules/vehicules_models.md5sum',$tmp_dir.'vehicules_models.md5sum');
2747
		if (file_exists($tmp_dir.'vehicules_models.md5sum')) {
2748
			if ($globalDebug) echo "Check files...\n";
2749
			$newmodelsdb = array();
2750
			if (($handle = fopen($tmp_dir.'vehicules_models.md5sum','r')) !== FALSE) {
2751
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2752
					$model = trim($row[2]);
2753
					$newmodelsdb[$model] = trim($row[0]);
2754
				}
2755
			}
2756
			$modelsdb = array();
2757
			if (file_exists(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum')) {
2758
				if (($handle = fopen(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum','r')) !== FALSE) {
2759
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2760
						$model = trim($row[2]);
2761
						$modelsdb[$model] = trim($row[0]);
2762
					}
2763
				}
2764
			}
2765
			$diff = array_diff($newmodelsdb,$modelsdb);
2766
			foreach ($diff as $key => $value) {
2767
				if ($globalDebug) echo 'Downloading vehicules model '.$key.' ...'."\n";
2768
				update_db::download('http://data.flightairmap.com/data/models/vehicules/'.$key,dirname(__FILE__).'/../models/vehicules/'.$key);
2769
				
2770
			}
2771
			update_db::download('http://data.flightairmap.com/data/models/vehicules/vehicules_models.md5sum',dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum');
2772
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2773
		if ($error != '') {
2774
			return $error;
2775
		} elseif ($globalDebug) echo "Done\n";
2776
		return '';
2777
	}
2778
2779
	public static function update_aircraft() {
2780
		global $tmp_dir, $globalDebug;
2781
		date_default_timezone_set('UTC');
2782
		//$error = '';
2783
		/*
2784
		if ($globalDebug) echo "Aircrafts : Download...";
2785
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2786
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2787
		//$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);
2788
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2789
//		echo strlen($data_req);
2790
		echo $data;
2791
		*/
2792
		if (file_exists($tmp_dir.'aircrafts.html')) {
2793
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2794
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2795
		    $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...
2796
		    //echo $result;
2797
		    //var_dump(str_get_html($result));
2798
		    //print_r(self::table2array($result));
2799
		}
2800
2801
	}
2802
	
2803
	public static function update_notam() {
2804
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2805
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2806
		$Common = new Common();
2807
		date_default_timezone_set('UTC');
2808
		$query = 'TRUNCATE TABLE notam';
2809
		try {
2810
			$Connection = new Connection();
2811
			$sth = $Connection->db->prepare($query);
2812
                        $sth->execute();
2813
                } catch(PDOException $e) {
2814
                        return "error : ".$e->getMessage();
2815
                }
2816
2817
		$error = '';
2818
		if ($globalDebug) echo "Notam : Download...";
2819
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2820
		if (file_exists($tmp_dir.'notam.rss')) {
2821
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2822
			foreach ($notams['channel']['item'] as $notam) {
2823
				$title = explode(':',$notam['title']);
2824
				$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...
2825
				unset($title[0]);
2826
				$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...
2827
				$description = strip_tags($notam['description'],'<pre>');
2828
				preg_match(':^(.*?)<pre>:',$description,$match);
2829
				$q = explode('/',$match[1]);
2830
				$data['fir'] = $q[0];
2831
				$data['code'] = $q[1];
2832
				$ifrvfr = $q[2];
2833
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2834
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2835
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2836
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2837
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2838
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2839
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2840
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2841
				//$data['scope'] = $q[4];
2842
				$data['lower_limit'] = $q[5];
2843
				$data['upper_limit'] = $q[6];
2844
				$latlonrad = $q[7];
2845
				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...
2846
				$latitude = $Common->convertDec($las,'latitude');
2847
				$longitude = $Common->convertDec($lns,'longitude');
2848
				if ($lac == 'S') $latitude = '-'.$latitude;
2849
				if ($lnc == 'W') $longitude = '-'.$longitude;
2850
				$data['center_latitude'] = $latitude;
2851
				$data['center_longitude'] = $longitude;
2852
				$data['radius'] = intval($radius);
2853
				
2854
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2855
				$data['text'] = $match[1];
2856
				preg_match(':</pre>(.*?)$:',$description,$match);
2857
				$fromto = $match[1];
2858
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2859
				$fromall = trim($match[1]);
2860
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2861
				$from = trim($match[1]);
2862
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2863
				preg_match('#TO:(.*?)$#',$fromto,$match);
2864
				$toall = trim($match[1]);
2865
				if (!preg_match(':Permanent:',$toall)) {
2866
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2867
					$to = trim($match[1]);
2868
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2869
					$data['permanent'] = 0;
2870
				} else {
2871
				    $data['date_end'] = NULL;
2872
				    $data['permanent'] = 1;
2873
				}
2874
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2875
				$NOTAM = new NOTAM();
2876
				$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']);
2877
				unset($data);
2878
			} 
2879
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2880
		if ($error != '') {
2881
			return $error;
2882
		} elseif ($globalDebug) echo "Done\n";
2883
		return '';
2884
	}
2885
	
2886
	public static function create_airspace() {
2887
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2888
		$Connection = new Connection();
2889
		if ($Connection->tableExists('airspace')) {
2890
			if ($globalDBdriver == 'mysql') {
2891
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2892
			} else {
2893
				$query = 'DROP TABLE airspace';
2894
			}
2895
			try {
2896
				$Connection = new Connection();
2897
				$sth = $Connection->db->prepare($query);
2898
				$sth->execute();
2899
			} catch(PDOException $e) {
2900
				return "error : ".$e->getMessage();
2901
			}
2902
		}
2903
		$Common = new Common();
2904
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2905
		$airspace_json = json_decode($airspace_lst,true);
2906
		foreach ($airspace_json['records'] as $airspace) {
2907
			if ($globalDebug) echo $airspace['name']."...\n";
2908
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2909
			if (file_exists($tmp_dir.$airspace['name'])) {
2910
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2911
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2912
				if ($globalDBdriver == 'mysql') {
2913
					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'].'"');
2914
				} else {
2915
					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'].'"');
2916
				}
2917
			}
2918
		}
2919
	}
2920
	
2921
	public static function fix_icaotype() {
2922
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
2923
		$Spotter = new Spotter();
2924
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
2925
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
2926
			try {
2927
				$Connection = new Connection();
2928
				$sth = $Connection->db->prepare($query);
2929
				$sth->execute(array(':new' => $new, ':old' => $old));
2930
			} catch(PDOException $e) {
2931
				return "error : ".$e->getMessage();
2932
			}
2933
		}
2934
	}
2935
2936
	public static function check_last_update() {
2937
		global $globalDBdriver;
2938
		if ($globalDBdriver == 'mysql') {
2939
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2940
		} else {
2941
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2942
		}
2943
		try {
2944
			$Connection = new Connection();
2945
			$sth = $Connection->db->prepare($query);
2946
                        $sth->execute();
2947
                } catch(PDOException $e) {
2948
                        return "error : ".$e->getMessage();
2949
                }
2950
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2951
                if ($row['nb'] > 0) return false;
2952
                else return true;
2953
	}
2954
2955
	public static function insert_last_update() {
2956
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2957
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2958
		try {
2959
			$Connection = new Connection();
2960
			$sth = $Connection->db->prepare($query);
2961
                        $sth->execute();
2962
                } catch(PDOException $e) {
2963
                        return "error : ".$e->getMessage();
2964
                }
2965
	}
2966
2967
	public static function check_airspace_version($version) {
2968
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2969
		try {
2970
			$Connection = new Connection();
2971
			$sth = $Connection->db->prepare($query);
2972
                        $sth->execute(array(':version' => $version));
2973
                } catch(PDOException $e) {
2974
                        return "error : ".$e->getMessage();
2975
                }
2976
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2977
                if ($row['nb'] > 0) return true;
2978
                else return false;
2979
	}
2980
2981
	public static function check_geoid_version($version) {
2982
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'geoid_version' AND value = :version";
2983
		try {
2984
			$Connection = new Connection();
2985
			$sth = $Connection->db->prepare($query);
2986
                        $sth->execute(array(':version' => $version));
2987
                } catch(PDOException $e) {
2988
                        return "error : ".$e->getMessage();
2989
                }
2990
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2991
                if ($row['nb'] > 0) return true;
2992
                else return false;
2993
	}
2994
2995
	public static function check_marine_identity_version($version) {
2996
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'marine_identity_version' AND value = :version";
2997
		try {
2998
			$Connection = new Connection();
2999
			$sth = $Connection->db->prepare($query);
3000
			$sth->execute(array(':version' => $version));
3001
		} catch(PDOException $e) {
3002
			return "error : ".$e->getMessage();
3003
		}
3004
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3005
		if ($row['nb'] > 0) return true;
3006
		else return false;
3007
	}
3008
3009
	public static function check_satellite_version($version) {
3010
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'satellite_version' AND value = :version";
3011
		try {
3012
			$Connection = new Connection();
3013
			$sth = $Connection->db->prepare($query);
3014
			$sth->execute(array(':version' => $version));
3015
		} catch(PDOException $e) {
3016
			return "error : ".$e->getMessage();
3017
		}
3018
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3019
		if ($row['nb'] > 0) return true;
3020
		else return false;
3021
	}
3022
3023
	public static function check_airlines_version($version) {
3024
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airlines_version' AND value = :version";
3025
		try {
3026
			$Connection = new Connection();
3027
			$sth = $Connection->db->prepare($query);
3028
			$sth->execute(array(':version' => $version));
3029
		} catch(PDOException $e) {
3030
			return "error : ".$e->getMessage();
3031
		}
3032
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3033
		if ($row['nb'] > 0) return true;
3034
		else return false;
3035
	}
3036
3037
	public static function check_notam_version($version) {
3038
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'notam_version' AND value = :version";
3039
		try {
3040
			$Connection = new Connection();
3041
			$sth = $Connection->db->prepare($query);
3042
			$sth->execute(array(':version' => $version));
3043
		} catch(PDOException $e) {
3044
			return "error : ".$e->getMessage();
3045
		}
3046
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3047
		if ($row['nb'] > 0) return true;
3048
		else return false;
3049
	}
3050
3051
	public static function insert_airlines_version($version) {
3052
		$query = "DELETE FROM config WHERE name = 'airlines_version';
3053
			INSERT INTO config (name,value) VALUES ('airlines_version',:version);";
3054
		try {
3055
			$Connection = new Connection();
3056
			$sth = $Connection->db->prepare($query);
3057
			$sth->execute(array(':version' => $version));
3058
		} catch(PDOException $e) {
3059
			return "error : ".$e->getMessage();
3060
		}
3061
	}
3062
3063
	public static function insert_notam_version($version) {
3064
		$query = "DELETE FROM config WHERE name = 'notam_version';
3065
			INSERT INTO config (name,value) VALUES ('notam_version',:version);";
3066
		try {
3067
			$Connection = new Connection();
3068
			$sth = $Connection->db->prepare($query);
3069
			$sth->execute(array(':version' => $version));
3070
		} catch(PDOException $e) {
3071
			return "error : ".$e->getMessage();
3072
		}
3073
	}
3074
3075
	public static function insert_airspace_version($version) {
3076
		$query = "DELETE FROM config WHERE name = 'airspace_version';
3077
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
3078
		try {
3079
			$Connection = new Connection();
3080
			$sth = $Connection->db->prepare($query);
3081
			$sth->execute(array(':version' => $version));
3082
		} catch(PDOException $e) {
3083
			return "error : ".$e->getMessage();
3084
		}
3085
	}
3086
	
3087
	public static function insert_geoid_version($version) {
3088
		$query = "DELETE FROM config WHERE name = 'geoid_version';
3089
			INSERT INTO config (name,value) VALUES ('geoid_version',:version);";
3090
		try {
3091
			$Connection = new Connection();
3092
			$sth = $Connection->db->prepare($query);
3093
                        $sth->execute(array(':version' => $version));
3094
                } catch(PDOException $e) {
3095
                        return "error : ".$e->getMessage();
3096
                }
3097
	}
3098
3099
	public static function insert_marine_identity_version($version) {
3100
		$query = "DELETE FROM config WHERE name = 'marine_identity_version';
3101
			INSERT INTO config (name,value) VALUES ('marine_identity_version',:version);";
3102
		try {
3103
			$Connection = new Connection();
3104
			$sth = $Connection->db->prepare($query);
3105
			$sth->execute(array(':version' => $version));
3106
		} catch(PDOException $e) {
3107
			return "error : ".$e->getMessage();
3108
		}
3109
	}
3110
3111
	public static function insert_satellite_version($version) {
3112
		$query = "DELETE FROM config WHERE name = 'satellite_version';
3113
			INSERT INTO config (name,value) VALUES ('satellite_version',:version);";
3114
		try {
3115
			$Connection = new Connection();
3116
			$sth = $Connection->db->prepare($query);
3117
			$sth->execute(array(':version' => $version));
3118
		} catch(PDOException $e) {
3119
			return "error : ".$e->getMessage();
3120
		}
3121
	}
3122
3123
	public static function check_last_notam_update() {
3124
		global $globalDBdriver;
3125
		if ($globalDBdriver == 'mysql') {
3126
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
3127
		} else {
3128
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
3129
		}
3130
		try {
3131
			$Connection = new Connection();
3132
			$sth = $Connection->db->prepare($query);
3133
                        $sth->execute();
3134
                } catch(PDOException $e) {
3135
                        return "error : ".$e->getMessage();
3136
                }
3137
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3138
                if ($row['nb'] > 0) return false;
3139
                else return true;
3140
	}
3141
3142
	public static function insert_last_notam_update() {
3143
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
3144
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
3145
		try {
3146
			$Connection = new Connection();
3147
			$sth = $Connection->db->prepare($query);
3148
                        $sth->execute();
3149
                } catch(PDOException $e) {
3150
                        return "error : ".$e->getMessage();
3151
                }
3152
	}
3153
3154
	public static function check_last_airspace_update() {
3155
		global $globalDBdriver;
3156
		if ($globalDBdriver == 'mysql') {
3157
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3158
		} else {
3159
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3160
		}
3161
		try {
3162
			$Connection = new Connection();
3163
			$sth = $Connection->db->prepare($query);
3164
                        $sth->execute();
3165
                } catch(PDOException $e) {
3166
                        return "error : ".$e->getMessage();
3167
                }
3168
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3169
                if ($row['nb'] > 0) return false;
3170
                else return true;
3171
	}
3172
3173
	public static function insert_last_airspace_update() {
3174
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
3175
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
3176
		try {
3177
			$Connection = new Connection();
3178
			$sth = $Connection->db->prepare($query);
3179
                        $sth->execute();
3180
                } catch(PDOException $e) {
3181
                        return "error : ".$e->getMessage();
3182
                }
3183
	}
3184
3185
	public static function check_last_geoid_update() {
3186
		global $globalDBdriver;
3187
		if ($globalDBdriver == 'mysql') {
3188
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3189
		} else {
3190
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3191
		}
3192
		try {
3193
			$Connection = new Connection();
3194
			$sth = $Connection->db->prepare($query);
3195
                        $sth->execute();
3196
                } catch(PDOException $e) {
3197
                        return "error : ".$e->getMessage();
3198
                }
3199
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3200
                if ($row['nb'] > 0) return false;
3201
                else return true;
3202
	}
3203
3204
	public static function insert_last_geoid_update() {
3205
		$query = "DELETE FROM config WHERE name = 'last_update_geoid';
3206
			INSERT INTO config (name,value) VALUES ('last_update_geoid',NOW());";
3207
		try {
3208
			$Connection = new Connection();
3209
			$sth = $Connection->db->prepare($query);
3210
                        $sth->execute();
3211
                } catch(PDOException $e) {
3212
                        return "error : ".$e->getMessage();
3213
                }
3214
	}
3215
3216
	public static function check_last_owner_update() {
3217
		global $globalDBdriver;
3218
		if ($globalDBdriver == 'mysql') {
3219
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3220
		} else {
3221
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3222
		}
3223
		try {
3224
			$Connection = new Connection();
3225
			$sth = $Connection->db->prepare($query);
3226
                        $sth->execute();
3227
                } catch(PDOException $e) {
3228
                        return "error : ".$e->getMessage();
3229
                }
3230
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3231
                if ($row['nb'] > 0) return false;
3232
                else return true;
3233
	}
3234
3235
	public static function insert_last_owner_update() {
3236
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
3237
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
3238
		try {
3239
			$Connection = new Connection();
3240
			$sth = $Connection->db->prepare($query);
3241
                        $sth->execute();
3242
                } catch(PDOException $e) {
3243
                        return "error : ".$e->getMessage();
3244
                }
3245
	}
3246
	public static function check_last_schedules_update() {
3247
		global $globalDBdriver;
3248
		if ($globalDBdriver == 'mysql') {
3249
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3250
		} else {
3251
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3252
		}
3253
		try {
3254
			$Connection = new Connection();
3255
			$sth = $Connection->db->prepare($query);
3256
                        $sth->execute();
3257
                } catch(PDOException $e) {
3258
                        return "error : ".$e->getMessage();
3259
                }
3260
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3261
                if ($row['nb'] > 0) return false;
3262
                else return true;
3263
	}
3264
3265
	public static function insert_last_schedules_update() {
3266
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
3267
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
3268
		try {
3269
			$Connection = new Connection();
3270
			$sth = $Connection->db->prepare($query);
3271
			$sth->execute();
3272
		} catch(PDOException $e) {
3273
			return "error : ".$e->getMessage();
3274
		}
3275
	}
3276
3277
	public static function check_last_tle_update() {
3278
		global $globalDBdriver;
3279
		if ($globalDBdriver == 'mysql') {
3280
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3281
		} else {
3282
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3283
		}
3284
		try {
3285
			$Connection = new Connection();
3286
			$sth = $Connection->db->prepare($query);
3287
			$sth->execute();
3288
		} catch(PDOException $e) {
3289
			return "error : ".$e->getMessage();
3290
		}
3291
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3292
		if ($row['nb'] > 0) return false;
3293
		else return true;
3294
	}
3295
3296
	public static function insert_last_tle_update() {
3297
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
3298
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
3299
		try {
3300
			$Connection = new Connection();
3301
			$sth = $Connection->db->prepare($query);
3302
			$sth->execute();
3303
		} catch(PDOException $e) {
3304
			return "error : ".$e->getMessage();
3305
		}
3306
	}
3307
3308
	public static function check_last_ucsdb_update() {
3309
		global $globalDBdriver;
3310
		if ($globalDBdriver == 'mysql') {
3311
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
3312
		} else {
3313
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 MONTH'";
3314
		}
3315
		try {
3316
			$Connection = new Connection();
3317
			$sth = $Connection->db->prepare($query);
3318
			$sth->execute();
3319
		} catch(PDOException $e) {
3320
			return "error : ".$e->getMessage();
3321
		}
3322
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3323
		if ($row['nb'] > 0) return false;
3324
		else return true;
3325
	}
3326
3327
	public static function insert_last_ucsdb_update() {
3328
		$query = "DELETE FROM config WHERE name = 'last_update_ucsdb';
3329
			INSERT INTO config (name,value) VALUES ('last_update_ucsdb',NOW());";
3330
		try {
3331
			$Connection = new Connection();
3332
			$sth = $Connection->db->prepare($query);
3333
			$sth->execute();
3334
		} catch(PDOException $e) {
3335
			return "error : ".$e->getMessage();
3336
		}
3337
	}
3338
3339
	public static function check_last_celestrak_update() {
3340
		global $globalDBdriver;
3341
		if ($globalDBdriver == 'mysql') {
3342
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3343
		} else {
3344
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3345
		}
3346
		try {
3347
			$Connection = new Connection();
3348
			$sth = $Connection->db->prepare($query);
3349
			$sth->execute();
3350
		} catch(PDOException $e) {
3351
			return "error : ".$e->getMessage();
3352
		}
3353
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3354
		if ($row['nb'] > 0) return false;
3355
		else return true;
3356
	}
3357
3358
	public static function insert_last_celestrak_update() {
3359
		$query = "DELETE FROM config WHERE name = 'last_update_celestrak';
3360
			INSERT INTO config (name,value) VALUES ('last_update_celestrak',NOW());";
3361
		try {
3362
			$Connection = new Connection();
3363
			$sth = $Connection->db->prepare($query);
3364
			$sth->execute();
3365
		} catch(PDOException $e) {
3366
			return "error : ".$e->getMessage();
3367
		}
3368
	}
3369
3370
	public static function check_last_marine_identity_update() {
3371
		global $globalDBdriver;
3372
		if ($globalDBdriver == 'mysql') {
3373
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3374
		} else {
3375
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3376
		}
3377
		try {
3378
			$Connection = new Connection();
3379
			$sth = $Connection->db->prepare($query);
3380
			$sth->execute();
3381
		} catch(PDOException $e) {
3382
			return "error : ".$e->getMessage();
3383
		}
3384
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3385
		if ($row['nb'] > 0) return false;
3386
		else return true;
3387
	}
3388
3389
	public static function check_last_satellite_update() {
3390
		global $globalDBdriver;
3391
		if ($globalDBdriver == 'mysql') {
3392
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
3393
		} else {
3394
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
3395
		}
3396
		try {
3397
			$Connection = new Connection();
3398
			$sth = $Connection->db->prepare($query);
3399
			$sth->execute();
3400
		} catch(PDOException $e) {
3401
			return "error : ".$e->getMessage();
3402
		}
3403
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3404
		if ($row['nb'] > 0) return false;
3405
		else return true;
3406
	}
3407
3408
	public static function insert_last_marine_identity_update() {
3409
		$query = "DELETE FROM config WHERE name = 'last_update_marine_identity';
3410
			INSERT INTO config (name,value) VALUES ('last_update_marine_identity',NOW());";
3411
		try {
3412
			$Connection = new Connection();
3413
			$sth = $Connection->db->prepare($query);
3414
			$sth->execute();
3415
		} catch(PDOException $e) {
3416
			return "error : ".$e->getMessage();
3417
		}
3418
	}
3419
3420
	public static function insert_last_satellite_update() {
3421
		$query = "DELETE FROM config WHERE name = 'last_update_satellite';
3422
			INSERT INTO config (name,value) VALUES ('last_update_satellite',NOW());";
3423
		try {
3424
			$Connection = new Connection();
3425
			$sth = $Connection->db->prepare($query);
3426
			$sth->execute();
3427
		} catch(PDOException $e) {
3428
			return "error : ".$e->getMessage();
3429
		}
3430
	}
3431
3432
	public static function delete_duplicatemodes() {
3433
		global $globalDBdriver;
3434
		if ($globalDBdriver == 'mysql') {
3435
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
3436
		} else {
3437
			$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'";
3438
		}
3439
		try {
3440
			$Connection = new Connection();
3441
			$sth = $Connection->db->prepare($query);
3442
                        $sth->execute();
3443
                } catch(PDOException $e) {
3444
                        return "error : ".$e->getMessage();
3445
                }
3446
	}
3447
	public static function delete_duplicateowner() {
3448
		global $globalDBdriver;
3449
		if ($globalDBdriver == 'mysql') {
3450
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
3451
		} else {
3452
			$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)";
3453
		}
3454
		try {
3455
			$Connection = new Connection();
3456
			$sth = $Connection->db->prepare($query);
3457
                        $sth->execute();
3458
                } catch(PDOException $e) {
3459
                        return "error : ".$e->getMessage();
3460
                }
3461
	}
3462
	
3463
	public static function update_all() {
3464
		global $globalMasterServer, $globalMasterSource;
3465
		if (!isset($globalMasterServer) || !$globalMasterServer) {
3466
			if (isset($globalMasterSource) && $globalMasterSource) {
3467
				echo update_db::update_routes();
3468
				echo update_db::update_translation();
3469
				//echo update_db::update_notam_fam();
3470
				echo update_db::update_ModeS();
3471
				//echo update_db::update_ModeS_flarm();
3472
				echo update_db::update_ModeS_ogn();
3473
				echo update_db::update_ModeS_faa();
3474
				echo update_db::fix_icaotype();
3475
				echo update_db::update_banned_fam();
3476
				//echo update_db::update_celestrak();
3477
				//echo update_db::delete_duplicatemodes();
3478
			} else {
3479
				//echo update_db::update_routes();
3480
				echo update_db::update_routes_fam();
3481
				//echo update_db::update_translation();
3482
				echo update_db::update_translation_fam();
3483
				//echo update_db::update_notam_fam();
3484
				//echo update_db::update_ModeS();
3485
				echo update_db::update_ModeS_fam();
3486
				//echo update_db::update_ModeS_flarm();
3487
				echo update_db::update_ModeS_ogn();
3488
				//echo update_db::delete_duplicatemodes();
3489
				echo update_db::update_banned_fam();
3490
			}
3491
		}
3492
	}
3493
}
3494
3495
//echo update_db::update_airports();
3496
//echo update_db::translation();
3497
//echo update_db::update_waypoints();
3498
//echo update_db::update_airspace();
3499
//echo update_db::update_notam();
3500
//echo update_db::update_ivao();
3501
//echo update_db::update_ModeS_flarm();
3502
//echo update_db::update_ModeS_ogn();
3503
//echo update_db::update_aircraft();
3504
//$update_db = new update_db();
3505
//echo update_db::update_owner();
3506
//update_db::update_translation_fam();
3507
//echo update_db::update_routes();
3508
//update_db::update_models();
3509
//echo $update_db::update_skyteam();
3510
//echo $update_db::update_tle();
3511
//echo update_db::update_notam_fam();
3512
//echo update_db::create_airspace();
3513
//echo update_db::update_ModeS();
3514
//echo update_db::update_ModeS_fam();
3515
//echo update_db::update_routes_fam();
3516
//echo update_db::update_ModeS_faa();
3517
//echo update_db::update_banned_fam();
3518
//echo update_db::modes_faa();
3519
//echo update_db::update_owner_fam();
3520
//echo update_db::delete_duplicateowner();
3521
//echo update_db::fix_icaotype();
3522
//echo update_db::satellite_ucsdb('tmp/UCS_Satellite_Database_officialname_1-1-17.txt');
3523
//echo update_db::satellite_celestrak('tmp/satcat.txt');
3524
?>
3525