Completed
Push — master ( 4b9f50...005bcb )
by Yannick
28:37
created

update_db::satellite_celestrak()   D

Complexity

Conditions 14
Paths 11

Size

Total Lines 228
Code Lines 184

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 184
nc 11
nop 1
dl 0
loc 228
rs 4.9516
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
		//$file = str_replace('/',DIRECTORY_SEPARATOR,$file);
15
		$fp = fopen($file, 'w+');
16
		$ch = curl_init();
17
		curl_setopt($ch, CURLOPT_URL, $url);
18
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
19
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
20
		if ($referer != '') curl_setopt($ch, CURLOPT_REFERER, $referer);
21
		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');
22
		curl_setopt($ch, CURLOPT_FILE, $fp);
23
		curl_exec($ch);
24
		curl_close($ch);
25
		fclose($fp);
26
	}
27
28
	public static function gunzip($in_file,$out_file_name = '') {
29
		//echo $in_file.' -> '.$out_file_name."\n";
30
		$buffer_size = 4096; // read 4kb at a time
31
		if ($out_file_name == '') $out_file_name = str_replace('.gz', '', $in_file); 
32
		if ($in_file != '' && file_exists($in_file)) {
33
			// PHP version of Ubuntu use gzopen64 instead of gzopen
34
			if (function_exists('gzopen')) $file = gzopen($in_file,'rb');
35
			elseif (function_exists('gzopen64')) $file = gzopen64($in_file,'rb');
36
			else {
37
				echo 'gzopen not available';
38
				die;
39
			}
40
			$out_file = fopen($out_file_name, 'wb'); 
41
			while(!gzeof($file)) {
42
				fwrite($out_file, gzread($file, $buffer_size));
43
			}  
44
			fclose($out_file);
45
			gzclose($file);
46
		}
47
	}
48
49
	public static function unzip($in_file) {
50
		if ($in_file != '' && file_exists($in_file)) {
51
			$path = pathinfo(realpath($in_file), PATHINFO_DIRNAME);
52
			$zip = new ZipArchive;
53
			$res = $zip->open($in_file);
54
			if ($res === TRUE) {
55
				$zip->extractTo($path);
56
				$zip->close();
57
			} else return false;
58
		} else return false;
59
	}
60
	
61
	public static function connect_sqlite($database) {
62
		try {
63
			self::$db_sqlite = new PDO('sqlite:'.$database);
64
			self::$db_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
65
		} catch(PDOException $e) {
66
			return "error : ".$e->getMessage();
67
		}
68
	}
69
	
70
	public static function retrieve_route_sqlite_to_dest($database_file) {
71
		global $globalDebug, $globalTransaction;
72
		//$query = 'TRUNCATE TABLE routes';
73
		if ($globalDebug) echo " - Delete previous routes from DB -";
74
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
75
		$Connection = new Connection();
76
		try {
77
			//$Connection = new Connection();
78
			$sth = $Connection->db->prepare($query);
79
                        $sth->execute(array(':source' => $database_file));
80
                } catch(PDOException $e) {
81
                        return "error : ".$e->getMessage();
82
                }
83
84
    		if ($globalDebug) echo " - Add routes to DB -";
85
    		update_db::connect_sqlite($database_file);
86
		//$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';
87
		$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";
88
		try {
89
                        $sth = update_db::$db_sqlite->prepare($query);
90
                        $sth->execute();
91
                } catch(PDOException $e) {
92
                        return "error : ".$e->getMessage();
93
                }
94
		//$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)';
95
		$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,ToAirport_ICAO,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
96
		$Connection = new Connection();
97
		$sth_dest = $Connection->db->prepare($query_dest);
98
		try {
99
			if ($globalTransaction) $Connection->db->beginTransaction();
100
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
101
				//$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);
102
				$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);
103
				$sth_dest->execute($query_dest_values);
104
            		}
105
			if ($globalTransaction) $Connection->db->commit();
106
		} catch(PDOException $e) {
107
			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...
108
			return "error : ".$e->getMessage();
109
		}
110
                return '';
111
	}
112
	public static function retrieve_route_oneworld($database_file) {
113
		global $globalDebug, $globalTransaction;
114
		//$query = 'TRUNCATE TABLE routes';
115
		if ($globalDebug) echo " - Delete previous routes from DB -";
116
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
117
		$Connection = new Connection();
118
		try {
119
			//$Connection = new Connection();
120
			$sth = $Connection->db->prepare($query);
121
                        $sth->execute(array(':source' => 'oneworld'));
122
                } catch(PDOException $e) {
123
                        return "error : ".$e->getMessage();
124
                }
125
126
    		if ($globalDebug) echo " - Add routes to DB -";
127
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
128
		$Spotter = new Spotter();
129
		if ($fh = fopen($database_file,"r")) {
130
			$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)';
131
			$Connection = new Connection();
132
			$sth_dest = $Connection->db->prepare($query_dest);
133
			if ($globalTransaction) $Connection->db->beginTransaction();
134
			while (!feof($fh)) {
135
				$line = fgetcsv($fh,9999,',');
136
				if ($line[0] != '') {
137
					if (($line[2] == '-' || ($line[2] != '-' && (strtotime($line[2]) > time()))) && ($line[3] == '-' || ($line[3] != '-' && (strtotime($line[3]) < time())))) {
138
						try {
139
							$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');
140
							$sth_dest->execute($query_dest_values);
141
						} catch(PDOException $e) {
142
							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...
143
							return "error : ".$e->getMessage();
144
						}
145
					}
146
				}
147
			}
148
			if ($globalTransaction) $Connection->db->commit();
149
		}
150
                return '';
151
	}
152
	
153
	public static function retrieve_route_skyteam($database_file) {
154
		global $globalDebug, $globalTransaction;
155
		//$query = 'TRUNCATE TABLE routes';
156
		if ($globalDebug) echo " - Delete previous routes from DB -";
157
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
158
		$Connection = new Connection();
159
		try {
160
			//$Connection = new Connection();
161
			$sth = $Connection->db->prepare($query);
162
                        $sth->execute(array(':source' => 'skyteam'));
163
                } catch(PDOException $e) {
164
                        return "error : ".$e->getMessage();
165
                }
166
167
    		if ($globalDebug) echo " - Add routes to DB -";
168
169
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
170
		$Spotter = new Spotter();
171
		if ($fh = fopen($database_file,"r")) {
172
			$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)';
173
			$Connection = new Connection();
174
			$sth_dest = $Connection->db->prepare($query_dest);
175
			try {
176
				if ($globalTransaction) $Connection->db->beginTransaction();
177
				while (!feof($fh)) {
178
					$line = fgetcsv($fh,9999,',');
179
					if ($line[0] != '') {
180
						$datebe = explode('  -  ',$line[2]);
181
						if (strtotime($datebe[0]) > time() && strtotime($datebe[1]) < time()) {
182
							$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');
183
							$sth_dest->execute($query_dest_values);
184
						}
185
					}
186
				}
187
				if ($globalTransaction) $Connection->db->commit();
188
			} catch(PDOException $e) {
189
				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...
190
				return "error : ".$e->getMessage();
191
			}
192
		}
193
                return '';
194
	}
195
	public static function retrieve_modes_sqlite_to_dest($database_file) {
196
		global $globalTransaction;
197
		//$query = 'TRUNCATE TABLE aircraft_modes';
198
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
199
		try {
200
			$Connection = new Connection();
201
			$sth = $Connection->db->prepare($query);
202
                        $sth->execute(array(':source' => $database_file));
203
                } catch(PDOException $e) {
204
                        return "error : ".$e->getMessage();
205
                }
206
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
207
		try {
208
			$Connection = new Connection();
209
			$sth = $Connection->db->prepare($query);
210
                        $sth->execute(array(':source' => $database_file));
211
                } catch(PDOException $e) {
212
                        return "error : ".$e->getMessage();
213
                }
214
215
    		update_db::connect_sqlite($database_file);
216
		$query = 'select * from Aircraft';
217
		try {
218
                        $sth = update_db::$db_sqlite->prepare($query);
219
                        $sth->execute();
220
                } catch(PDOException $e) {
221
                        return "error : ".$e->getMessage();
222
                }
223
		//$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)';
224
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
225
		
226
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
227
		
228
		$Connection = new Connection();
229
		$sth_dest = $Connection->db->prepare($query_dest);
230
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
231
		try {
232
			if ($globalTransaction) $Connection->db->beginTransaction();
233
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
234
			//$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']);
235
				if ($values['UserString4'] == 'M') $type = 'military';
236
				else $type = null;
237
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
238
				$sth_dest->execute($query_dest_values);
239
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
240
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
241
				    $sth_dest_owner->execute($query_dest_owner_values);
242
				}
243
            		}
244
			if ($globalTransaction) $Connection->db->commit();
245
		} catch(PDOException $e) {
246
			return "error : ".$e->getMessage();
247
		}
248
249
		// Remove data already in DB from ACARS
250
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
251
		try {
252
			$Connection = new Connection();
253
			$sth = $Connection->db->prepare($query);
254
                        $sth->execute(array(':source' => $database_file));
255
                } catch(PDOException $e) {
256
                        return "error : ".$e->getMessage();
257
                }
258
		return '';
259
	}
260
261
	public static function retrieve_modes_flarmnet($database_file) {
262
		global $globalTransaction;
263
		$Common = new Common();
264
		//$query = 'TRUNCATE TABLE aircraft_modes';
265
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
266
		try {
267
			$Connection = new Connection();
268
			$sth = $Connection->db->prepare($query);
269
                        $sth->execute(array(':source' => $database_file));
270
                } catch(PDOException $e) {
271
                        return "error : ".$e->getMessage();
272
                }
273
		
274
		if ($fh = fopen($database_file,"r")) {
275
			//$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)';
276
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
277
		
278
			$Connection = new Connection();
279
			$sth_dest = $Connection->db->prepare($query_dest);
280
			try {
281
				if ($globalTransaction) $Connection->db->beginTransaction();
282
            			while (!feof($fh)) {
283
            				$values = array();
284
            				$line = $Common->hex2str(fgets($fh,9999));
285
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
286
            				$values['ModeS'] = substr($line,0,6);
287
            				$values['Registration'] = trim(substr($line,69,6));
288
            				$aircraft_name = trim(substr($line,48,6));
289
            				// Check if we can find ICAO, else set it to GLID
290
            				$aircraft_name_split = explode(' ',$aircraft_name);
291
            				$search_more = '';
292
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
293
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
294
            				$sth_search = $Connection->db->prepare($query_search);
295
					try {
296
                                    		$sth_search->execute();
297
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
298
	            				//if (count($result) > 0) {
299
	            				if (isset($result['icao']) && $result['icao'] != '') {
300
	            				    $values['ICAOTypeCode'] = $result['icao'];
301
	            				} 
302
					} catch(PDOException $e) {
303
						return "error : ".$e->getMessage();
304
					}
305
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
306
					// Add data to db
307
					if ($values['Registration'] != '' && $values['Registration'] != '0000') {
308
						//$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']);
309
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':source_type' => 'flarm');
310
						//print_r($query_dest_values);
311
						$sth_dest->execute($query_dest_values);
312
					}
313
				}
314
				if ($globalTransaction) $Connection->db->commit();
315
			} catch(PDOException $e) {
316
				return "error : ".$e->getMessage();
317
			}
318
		}
319
320
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
321
		try {
322
			$Connection = new Connection();
323
			$sth = $Connection->db->prepare($query);
324
                        $sth->execute(array(':source' => $database_file));
325
                } catch(PDOException $e) {
326
                        return "error : ".$e->getMessage();
327
                }
328
		return '';
329
	}
330
331
	public static function retrieve_modes_ogn($database_file) {
332
		global $globalTransaction;
333
		//$query = 'TRUNCATE TABLE aircraft_modes';
334
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
335
		try {
336
			$Connection = new Connection();
337
			$sth = $Connection->db->prepare($query);
338
                        $sth->execute(array(':source' => $database_file));
339
                } catch(PDOException $e) {
340
                        return "error : ".$e->getMessage();
341
                }
342
		
343
		if ($fh = fopen($database_file,"r")) {
344
			//$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)';
345
			$query_dest = 'INSERT INTO aircraft_modes (LastModified,ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:lastmodified,:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
346
		
347
			$Connection = new Connection();
348
			$sth_dest = $Connection->db->prepare($query_dest);
349
			try {
350
				if ($globalTransaction) $Connection->db->beginTransaction();
351
				$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...
352
            			while (!feof($fh)) {
353
            				$line = fgetcsv($fh,9999,',',"'");
354
            				
355
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
356
					//print_r($line);
357
            				$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...
358
            				$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...
359
            				$values['ICAOTypeCode'] = '';
360
            				$aircraft_name = $line[2];
361
            				// Check if we can find ICAO, else set it to GLID
362
            				$aircraft_name_split = explode(' ',$aircraft_name);
363
            				$search_more = '';
364
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
365
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
366
            				$sth_search = $Connection->db->prepare($query_search);
367
					try {
368
                                    		$sth_search->execute();
369
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
370
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
371
					} catch(PDOException $e) {
372
						return "error : ".$e->getMessage();
373
					}
374
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
375
					// Add data to db
376
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
377
						//$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']);
378
						$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');
379
						//print_r($query_dest_values);
380
						$sth_dest->execute($query_dest_values);
381
					}
382
				}
383
				if ($globalTransaction) $Connection->db->commit();
384
			} catch(PDOException $e) {
385
				return "error : ".$e->getMessage();
386
			}
387
		}
388
389
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
390
		try {
391
			$Connection = new Connection();
392
			$sth = $Connection->db->prepare($query);
393
                        $sth->execute(array(':source' => $database_file));
394
                } catch(PDOException $e) {
395
                        return "error : ".$e->getMessage();
396
                }
397
		return '';
398
	}
399
400
	public static function retrieve_owner($database_file,$country = 'F') {
401
		global $globalTransaction, $globalMasterSource;
402
		//$query = 'TRUNCATE TABLE aircraft_modes';
403
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source; DELETE FROM aircraft_modes WHERE Source = :source;";
404
		try {
405
			$Connection = new Connection();
406
			$sth = $Connection->db->prepare($query);
407
                        $sth->execute(array(':source' => $database_file));
408
                } catch(PDOException $e) {
409
                        return "error : ".$e->getMessage();
410
                }
411
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
412
		$Spotter = new Spotter();
413
		if ($fh = fopen($database_file,"r")) {
414
			//$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)';
415
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
416
		        $query_modes = 'INSERT INTO aircraft_modes (ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:modes,:modescountry,:registration,:icaotypecode,:source)';
417
		        
418
			$Connection = new Connection();
419
			$sth_dest = $Connection->db->prepare($query_dest);
420
			$sth_modes = $Connection->db->prepare($query_modes);
421
			try {
422
				if ($globalTransaction) $Connection->db->beginTransaction();
423
				$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...
424
            			while (!feof($fh)) {
425
            				$line = fgetcsv($fh,9999,',','"');
426
            				$values = array();
427
            				//print_r($line);
428
            				if ($country == 'F') {
429
            				    $values['registration'] = $line[0];
430
            				    $values['base'] = $line[4];
431
            				    $values['owner'] = $line[5];
432
            				    if ($line[6] == '') $values['date_first_reg'] = null;
433
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
434
					    $values['cancel'] = $line[7];
435
					} elseif ($country == 'EI') {
436
					    // TODO : add modeS & reg to aircraft_modes
437
            				    $values['registration'] = $line[0];
438
            				    $values['base'] = $line[3];
439
            				    $values['owner'] = $line[2];
440
            				    if ($line[1] == '') $values['date_first_reg'] = null;
441
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
442
					    $values['cancel'] = '';
443
					    $values['modes'] = $line[7];
444
					    $values['icao'] = $line[8];
445
					    
446
					} elseif ($country == 'HB') {
447
					    // TODO : add modeS & reg to aircraft_modes
448
            				    $values['registration'] = $line[0];
449
            				    $values['base'] = null;
450
            				    $values['owner'] = $line[5];
451
            				    $values['date_first_reg'] = null;
452
					    $values['cancel'] = '';
453
					    $values['modes'] = $line[4];
454
					    $values['icao'] = $line[7];
455
					} elseif ($country == 'OK') {
456
					    // TODO : add modeS & reg to aircraft_modes
457
            				    $values['registration'] = $line[3];
458
            				    $values['base'] = null;
459
            				    $values['owner'] = $line[5];
460
            				    if ($line[18] == '') $values['date_first_reg'] = null;
461
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
462
					    $values['cancel'] = '';
463
					} elseif ($country == 'VH') {
464
					    // TODO : add modeS & reg to aircraft_modes
465
            				    $values['registration'] = $line[0];
466
            				    $values['base'] = null;
467
            				    $values['owner'] = $line[12];
468
            				    if ($line[28] == '') $values['date_first_reg'] = null;
469
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
470
471
					    $values['cancel'] = $line[39];
472
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
473
            				    $values['registration'] = $line[0];
474
            				    $values['base'] = null;
475
            				    $values['owner'] = $line[4];
476
            				    $values['date_first_reg'] = null;
477
					    $values['cancel'] = '';
478
					} elseif ($country == 'CC') {
479
            				    $values['registration'] = $line[0];
480
            				    $values['base'] = null;
481
            				    $values['owner'] = $line[6];
482
            				    $values['date_first_reg'] = null;
483
					    $values['cancel'] = '';
484
					} elseif ($country == 'HJ') {
485
            				    $values['registration'] = $line[0];
486
            				    $values['base'] = null;
487
            				    $values['owner'] = $line[8];
488
            				    if ($line[7] == '') $values['date_first_reg'] = null;
489
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
490
					    $values['cancel'] = '';
491
					} elseif ($country == 'PP') {
492
            				    $values['registration'] = $line[0];
493
            				    $values['base'] = null;
494
            				    $values['owner'] = $line[4];
495
            				    if ($line[6] == '') $values['date_first_reg'] = null;
496
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
497
					    $values['cancel'] = $line[7];
498
					} elseif ($country == 'E7') {
499
            				    $values['registration'] = $line[0];
500
            				    $values['base'] = null;
501
            				    $values['owner'] = $line[4];
502
            				    if ($line[5] == '') $values['date_first_reg'] = null;
503
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
504
					    $values['cancel'] = '';
505
					} elseif ($country == '8Q') {
506
            				    $values['registration'] = $line[0];
507
            				    $values['base'] = null;
508
            				    $values['owner'] = $line[3];
509
            				    if ($line[7] == '') $values['date_first_reg'] = null;
510
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
511
					    $values['cancel'] = '';
512
					} elseif ($country == 'ZK') {
513
            				    $values['registration'] = $line[0];
514
            				    $values['base'] = null;
515
            				    $values['owner'] = $line[3];
516
            				    $values['date_first_reg'] = null;
517
					    $values['cancel'] = '';
518
					    $values['modes'] = $line[5];
519
					    $values['icao'] = $line[9];
520
					} elseif ($country == 'M') {
521
            				    $values['registration'] = $line[0];
522
            				    $values['base'] = null;
523
            				    $values['owner'] = $line[6];
524
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
525
					    $values['cancel'] = date("Y-m-d",strtotime($line[8]));
526
					    $values['modes'] = $line[4];
527
					    $values['icao'] = $line[10];
528
					} elseif ($country == 'OY') {
529
            				    $values['registration'] = $line[0];
530
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[4]));
531
					    $values['modes'] = $line[5];
532
					    $values['icao'] = $line[6];
533
					} elseif ($country == 'PH') {
534
            				    $values['registration'] = $line[0];
535
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[3]));
536
					    $values['modes'] = $line[4];
537
					    $values['icao'] = $line[5];
538
					} elseif ($country == 'OM' || $country == 'TF') {
539
            				    $values['registration'] = $line[0];
540
            				    $values['base'] = null;
541
            				    $values['owner'] = $line[3];
542
            				    $values['date_first_reg'] = null;
543
					    $values['cancel'] = '';
544
					}
545
					if (isset($values['cancel']) && $values['cancel'] == '' && $values['registration'] != null && isset($values['owner'])) {
546
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
547
						$sth_dest->execute($query_dest_values);
548
					}
549
					if ($globalMasterSource && $values['registration'] != null && isset($values['modes']) && $values['modes'] != '') {
550
						$modescountry = $Spotter->countryFromAircraftRegistration($values['registration']);
551
						$query_modes_values = array(':registration' => $values['registration'],':modes' => $values['modes'],':modescountry' => $modescountry,':icaotypecode' => $values['icao'],':source' => $database_file);
552
						$sth_modes->execute($query_modes_values);
553
					}
554
				}
555
				if ($globalTransaction) $Connection->db->commit();
556
			} catch(PDOException $e) {
557
				return "error : ".$e->getMessage();
558
			}
559
		}
560
		return '';
561
	}
562
563
	/*
564
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
565
	*/
566
	public static function update_airports() {
567
		global $tmp_dir, $globalTransaction, $globalDebug;
568
569
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
570
		$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...
571
		$query = '
572
		    PREFIX dbo: <http://dbpedia.org/ontology/>
573
		    PREFIX dbp: <http://dbpedia.org/property/>
574
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
575
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
576
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
577
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
578
		    FROM <http://dbpedia.org>
579
		    WHERE {
580
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
581
582
			OPTIONAL {
583
			    ?airport dbo:icaoLocationIdentifier ?icao .
584
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
585
			}
586
587
			OPTIONAL {
588
			    ?airport dbo:iataLocationIdentifier ?iata .
589
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
590
			}
591
592
			OPTIONAL {
593
			    ?airport dbo:locationIdentifier ?lid .
594
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
595
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
596
			    OPTIONAL {
597
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
598
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
599
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
600
			    }
601
			    FILTER (!bound(?other_icao))
602
			}
603
604
			OPTIONAL {
605
			    ?airport dbo:faaLocationIdentifier ?faa .
606
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
607
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
608
			    OPTIONAL {
609
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
610
				?airport_x dbo:iataLocationIdentifier ?other_iata .
611
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
612
			    }
613
			    FILTER (!bound(?other_iata))
614
			}
615
616
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
617
	
618
			OPTIONAL {
619
			    ?airport rdfs:label ?name
620
			    FILTER (lang(?name) = "en")
621
			}
622
    
623
			OPTIONAL {
624
			    ?airport foaf:homepage ?homepage
625
			}
626
		    
627
			OPTIONAL {
628
			    ?airport dbp:coordinatesRegion ?country
629
			}
630
    
631
			OPTIONAL {
632
			    ?airport dbp:type ?type
633
			}
634
			
635
			OPTIONAL {
636
			    ?airport dbo:elevation ?altitude
637
			}
638
			OPTIONAL {
639
			    ?airport dbp:image ?image
640
			}
641
642
			{
643
			    ?airport geo:lat ?latitude .
644
			    ?airport geo:long ?longitude .
645
			    FILTER (datatype(?latitude) = xsd:float)
646
			    FILTER (datatype(?longitude) = xsd:float)
647
			} UNION {
648
			    ?airport geo:lat ?latitude .
649
			    ?airport geo:long ?longitude .
650
			    FILTER (datatype(?latitude) = xsd:double)
651
			    FILTER (datatype(?longitude) = xsd:double)
652
			    OPTIONAL {
653
				?airport geo:lat ?lat_f .
654
				?airport geo:long ?long_f .
655
				FILTER (datatype(?lat_f) = xsd:float)
656
				FILTER (datatype(?long_f) = xsd:float)
657
			    }
658
			    FILTER (!bound(?lat_f) && !bound(?long_f))
659
			}
660
661
		    }
662
		    ORDER BY ?airport
663
		';
664
		$result = sparql_query($query);
665
  
666
		/*
667
		$query = 'TRUNCATE TABLE airport';
668
		try {
669
			$Connection = new Connection();
670
			$sth = $Connection->db->prepare($query);
671
                        $sth->execute();
672
                } catch(PDOException $e) {
673
                        return "error : ".$e->getMessage();
674
                }
675
                */
676
                /*
677
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
678
		try {
679
			$Connection = new Connection();
680
			$sth = $Connection->db->prepare($query);
681
                        $sth->execute();
682
                } catch(PDOException $e) {
683
                        return "error : ".$e->getMessage();
684
                }
685
                */
686
687
		$query_dest = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image_thumb,image)
688
		    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
689
		$Connection = new Connection();
690
		$sth_dest = $Connection->db->prepare($query_dest);
691
		if ($globalTransaction) $Connection->db->beginTransaction();
692
  
693
		$i = 0;
694
		while($row = sparql_fetch_array($result))
695
		{
696
			if ($i >= 1) {
697
			//print_r($row);
698
			if (!isset($row['iata'])) $row['iata'] = '';
699
			if (!isset($row['icao'])) $row['icao'] = '';
700
			if (!isset($row['type'])) $row['type'] = '';
701
			if (!isset($row['altitude'])) $row['altitude'] = '';
702
			if (isset($row['city_bis'])) {
703
				$row['city'] = $row['city_bis'];
704
			}
705
			if (!isset($row['city'])) $row['city'] = '';
706
			if (!isset($row['country'])) $row['country'] = '';
707
			if (!isset($row['homepage'])) $row['homepage'] = '';
708
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
709
			if (!isset($row['name'])) continue;
710
			if (!isset($row['image'])) {
711
				$row['image'] = '';
712
				$row['image_thumb'] = '';
713
			} else {
714
				$image = str_replace(' ','_',$row['image']);
715
				$digest = md5($image);
716
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
717
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
718
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
719
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
720
			}
721
			
722
			$country = explode('-',$row['country']);
723
			$row['country'] = $country[0];
724
			
725
			$row['type'] = trim($row['type']);
726
			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'])) {
727
				$row['type'] = 'military';
728
			} 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') {
729
				$row['type'] = 'small_airport';
730
			}
731
			
732
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
733
			$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']);
734
			//print_r($query_dest_values);
735
			
736
			if ($row['icao'] != '') {
737
				try {
738
					$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
739
					$sth->execute(array(':icao' => $row['icao']));
740
				} catch(PDOException $e) {
741
					return "error : ".$e->getMessage();
742
				}
743
					if ($sth->fetchColumn() > 0) {
744
						// Update ?
745
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
746
						try {
747
							$sth = $Connection->db->prepare($query);
748
							$sth->execute(array(':icao' => $row['icao'],':type' => $row['type']));
749
						} catch(PDOException $e) {
750
							return "error : ".$e->getMessage();
751
						}
752
						echo $row['icao'].' : '.$row['type']."\n";
753
					} else {
754
						try {
755
							$sth_dest->execute($query_dest_values);
756
						} catch(PDOException $e) {
757
							return "error : ".$e->getMessage();
758
						}
759
					}
760
				}
761
			}
762
763
			$i++;
764
		}
765
		if ($globalTransaction) $Connection->db->commit();
766
		/*
767
		echo "Delete duplicate rows...\n";
768
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
769
		try {
770
			$Connection = new Connection();
771
			$sth = $Connection->db->prepare($query);
772
                        $sth->execute();
773
                } catch(PDOException $e) {
774
                        return "error : ".$e->getMessage();
775
                }
776
                */
777
778
779
		/*
780
		if ($globalDebug) echo "Insert Not available Airport...\n";
781
		$query = "INSERT INTO airport (airport_id,name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image,image_thumb)
782
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
783
		$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' => '');
784
		try {
785
			$Connection = new Connection();
786
			$sth = $Connection->db->prepare($query);
787
                        $sth->execute($query_values);
788
                } catch(PDOException $e) {
789
                        return "error : ".$e->getMessage();
790
                }
791
                */
792
		$i++;
793
/*
794
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
795
		try {
796
			$Connection = new Connection();
797
			$sth = $Connection->db->prepare($query);
798
                        $sth->execute();
799
                } catch(PDOException $e) {
800
                        return "error : ".$e->getMessage();
801
                }
802
*/
803
                
804
		echo "Download data from ourairports.com...\n";
805
		$delimiter = ',';
806
		$out_file = $tmp_dir.'airports.csv';
807
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
808
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
809
		echo "Add data from ourairports.com...\n";
810
811
		$header = NULL;
812
		if (($handle = fopen($out_file, 'r')) !== FALSE)
813
		{
814
			$Connection = new Connection();
815
			//$Connection->db->beginTransaction();
816
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
817
			{
818
				if(!$header) $header = $row;
819
				else {
820
					$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...
821
					$data = array_combine($header, $row);
822
					try {
823
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
824
						$sth->execute(array(':icao' => $data['ident']));
825
					} catch(PDOException $e) {
826
						return "error : ".$e->getMessage();
827
					}
828
					if ($sth->fetchColumn() > 0) {
829
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
830
						try {
831
							$sth = $Connection->db->prepare($query);
832
							$sth->execute(array(':icao' => $data['ident'],':type' => $data['type']));
833
						} catch(PDOException $e) {
834
							return "error : ".$e->getMessage();
835
						}
836
					} else {
837
						if ($data['gps_code'] == $data['ident']) {
838
						$query = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link)
839
						    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
840
						$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']);
841
						try {
842
							$sth = $Connection->db->prepare($query);
843
							$sth->execute($query_values);
844
						} catch(PDOException $e) {
845
							return "error : ".$e->getMessage();
846
						}
847
						$i++;
848
						}
849
					}
850
				}
851
			}
852
			fclose($handle);
853
			//$Connection->db->commit();
854
		}
855
		
856
		
857
		echo "Download data from another free database...\n";
858
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
859
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
860
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
861
		update_db::unzip($out_file);
862
		$header = NULL;
863
		echo "Add data from another free database...\n";
864
		$delimiter = ':';
865
		$Connection = new Connection();
866
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
867
		{
868
			//$Connection->db->beginTransaction();
869
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
870
			{
871
				if(!$header) $header = $row;
872
				else {
873
					$data = $row;
874
875
					$query = 'UPDATE airport SET city = :city, country = :country WHERE icao = :icao';
876
					try {
877
						$sth = $Connection->db->prepare($query);
878
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
879
					} catch(PDOException $e) {
880
						return "error : ".$e->getMessage();
881
					}
882
				}
883
			}
884
			fclose($handle);
885
			//$Connection->db->commit();
886
		}
887
888
		echo "Put type military for all air base";
889
		$Connection = new Connection();
890
		try {
891
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE name LIKE '%Air Base%'");
892
			$sth->execute();
893
		} catch(PDOException $e) {
894
			return "error : ".$e->getMessage();
895
		}
896
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
897
			$query2 = 'UPDATE airport SET type = :type WHERE icao = :icao';
898
			try {
899
				$sth2 = $Connection->db->prepare($query2);
900
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
901
			} catch(PDOException $e) {
902
				return "error : ".$e->getMessage();
903
			}
904
		}
905
		return "success";
906
	}
907
	
908
	public static function translation() {
909
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
910
		global $tmp_dir, $globalTransaction;
911
		$Spotter = new Spotter();
912
		//$out_file = $tmp_dir.'translation.zip';
913
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
914
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
915
		
916
		//$query = 'TRUNCATE TABLE translation';
917
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
918
		try {
919
			$Connection = new Connection();
920
			$sth = $Connection->db->prepare($query);
921
                        $sth->execute(array(':source' => 'translation.csv'));
922
                } catch(PDOException $e) {
923
                        return "error : ".$e->getMessage();
924
                }
925
926
		
927
		//update_db::unzip($out_file);
928
		$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...
929
		$delimiter = ';';
930
		$Connection = new Connection();
931
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
932
		{
933
			$i = 0;
934
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
935
			//$Connection->db->beginTransaction();
936
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
937
			{
938
				$i++;
939
				if($i > 12) {
940
					$data = $row;
941
					$operator = $data[2];
942
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
943
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
944
                                                //echo substr($operator, 0, 2)."\n";;
945
                                                if (count($airline_array) > 0) {
946
							//print_r($airline_array);
947
							$operator = $airline_array[0]['icao'].substr($operator,2);
948
                                                }
949
                                        }
950
					
951
					$operator_correct = $data[3];
952
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
953
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
954
                                                if (count($airline_array) > 0) {
955
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
956
                                            	}
957
                                        }
958
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
959
					try {
960
						$sth = $Connection->db->prepare($query);
961
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
962
					} catch(PDOException $e) {
963
						return "error : ".$e->getMessage();
964
					}
965
				}
966
			}
967
			fclose($handle);
968
			//$Connection->db->commit();
969
		}
970
		return '';
971
        }
972
	
973
	public static function translation_fam() {
974
		global $tmp_dir, $globalTransaction;
975
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
976
		try {
977
			$Connection = new Connection();
978
			$sth = $Connection->db->prepare($query);
979
			$sth->execute(array(':source' => 'website_fam'));
980
		} catch(PDOException $e) {
981
			return "error : ".$e->getMessage();
982
		}
983
		//update_db::unzip($out_file);
984
		$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...
985
		$delimiter = "\t";
986
		$Connection = new Connection();
987
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
988
		{
989
			$i = 0;
990
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
991
			//$Connection->db->beginTransaction();
992
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
993
			{
994
				if ($i > 0) {
995
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
996
					try {
997
						$sth = $Connection->db->prepare($query);
998
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
999
					} catch(PDOException $e) {
1000
						return "error : ".$e->getMessage();
1001
					}
1002
				}
1003
				$i++;
1004
			}
1005
			fclose($handle);
1006
			//$Connection->db->commit();
1007
		}
1008
		return '';
1009
        }
1010
1011
	/*
1012
	* This function use FAA public data.
1013
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
1014
	*/
1015
	public static function modes_faa() {
1016
		global $tmp_dir, $globalTransaction, $globalDebug;
1017
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1018
		try {
1019
			$Connection = new Connection();
1020
			$sth = $Connection->db->prepare($query);
1021
                        $sth->execute(array(':source' => 'website_faa'));
1022
                } catch(PDOException $e) {
1023
                        return "error : ".$e->getMessage();
1024
                }
1025
1026
		$query = "DELETE FROM aircraft_owner 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
		$delimiter = ",";
1036
		$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...
1037
		$Connection = new Connection();
1038
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1039
		{
1040
			$i = 0;
1041
			if ($globalTransaction) $Connection->db->beginTransaction();
1042
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1043
			{
1044
				if ($i > 0) {
1045
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1046
					try {
1047
						$sths = $Connection->db->prepare($query_search);
1048
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1049
					} catch(PDOException $e) {
1050
						return "error s : ".$e->getMessage();
1051
					}
1052
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1053
					if (!empty($result_search)) {
1054
						if ($globalDebug) echo '.';
1055
							//if ($globalDBdriver == 'mysql') {
1056
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1057
							//} else {
1058
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1059
							//}
1060
						try {
1061
							$sthi = $Connection->db->prepare($queryi);
1062
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1063
						} catch(PDOException $e) {
1064
							return "error u : ".$e->getMessage();
1065
						}
1066
					} else {
1067
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1068
						try {
1069
							$sthsm = $Connection->db->prepare($query_search_mfr);
1070
							$sthsm->execute(array(':mfr' => $data[2]));
1071
						} catch(PDOException $e) {
1072
							return "error mfr : ".$e->getMessage();
1073
						}
1074
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1075
						if (!empty($result_search_mfr)) {
1076
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1077
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1078
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1079
							try {
1080
								$sthf = $Connection->db->prepare($queryf);
1081
								$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'));
1082
							} catch(PDOException $e) {
1083
								return "error f : ".$e->getMessage();
1084
							}
1085
						}
1086
					}
1087
					if (strtotime($data[29]) > time()) {
1088
						if ($globalDebug) echo 'i';
1089
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1090
						try {
1091
							$sth = $Connection->db->prepare($query);
1092
							$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'));
1093
						} catch(PDOException $e) {
1094
							return "error i : ".$e->getMessage();
1095
						}
1096
					}
1097
				}
1098
				if ($i % 90 == 0) {
1099
					if ($globalTransaction) $Connection->db->commit();
1100
					if ($globalTransaction) $Connection->db->beginTransaction();
1101
				}
1102
				$i++;
1103
			}
1104
			fclose($handle);
1105
			if ($globalTransaction) $Connection->db->commit();
1106
		}
1107
		//print_r($mfr);
1108
		return '';
1109
        }
1110
	public static function modes_fam() {
1111
		global $tmp_dir, $globalTransaction;
1112
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1113
		try {
1114
			$Connection = new Connection();
1115
			$sth = $Connection->db->prepare($query);
1116
                        $sth->execute(array(':source' => 'website_fam'));
1117
                } catch(PDOException $e) {
1118
                        return "error : ".$e->getMessage();
1119
                }
1120
1121
		
1122
		//update_db::unzip($out_file);
1123
		$delimiter = "\t";
1124
		$Connection = new Connection();
1125
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1126
		{
1127
			$i = 0;
1128
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1129
			//$Connection->db->beginTransaction();
1130
			if ($globalTransaction) $Connection->db->beginTransaction();
1131
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1132
			{
1133
				if ($i > 0) {
1134
					if ($data[1] == 'NULL') $data[1] = $data[0];
1135
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1136
					try {
1137
						$sth = $Connection->db->prepare($query);
1138
						$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'));
1139
					} catch(PDOException $e) {
1140
						return "error : ".$e->getMessage();
1141
					}
1142
				}
1143
				$i++;
1144
			}
1145
			fclose($handle);
1146
			if ($globalTransaction) $Connection->db->commit();
1147
		}
1148
		return '';
1149
        }
1150
        
1151
	public static function owner_fam() {
1152
		global $tmp_dir, $globalTransaction;
1153
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1154
		try {
1155
			$Connection = new Connection();
1156
			$sth = $Connection->db->prepare($query);
1157
                        $sth->execute(array(':source' => 'website_fam'));
1158
                } catch(PDOException $e) {
1159
                        return "error : ".$e->getMessage();
1160
                }
1161
1162
		$delimiter = "\t";
1163
		$Connection = new Connection();
1164
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1165
		{
1166
			$i = 0;
1167
			if ($globalTransaction) $Connection->db->beginTransaction();
1168
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1169
			{
1170
				if ($i > 0) {
1171
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1172
					try {
1173
						$sth = $Connection->db->prepare($query);
1174
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1175
					} catch(PDOException $e) {
1176
						//print_r($data);
1177
						return "error : ".$e->getMessage();
1178
					}
1179
				}
1180
				$i++;
1181
			}
1182
			fclose($handle);
1183
			if ($globalTransaction) $Connection->db->commit();
1184
		}
1185
		return '';
1186
        }
1187
1188
	public static function routes_fam() {
1189
		global $tmp_dir, $globalTransaction, $globalDebug;
1190
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1191
		try {
1192
			$Connection = new Connection();
1193
			$sth = $Connection->db->prepare($query);
1194
			$sth->execute(array(':source' => 'website_fam'));
1195
		} catch(PDOException $e) {
1196
			return "error : ".$e->getMessage();
1197
		}
1198
		$delimiter = "\t";
1199
		$Connection = new Connection();
1200
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1201
		{
1202
			$i = 0;
1203
			if ($globalTransaction) $Connection->db->beginTransaction();
1204
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1205
			{
1206
				if ($i > 0) {
1207
					$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)';
1208
					try {
1209
						$sth = $Connection->db->prepare($query);
1210
						$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'));
1211
					} catch(PDOException $e) {
1212
						if ($globalDebug) echo "error: ".$e->getMessage()." - data: ".implode(',',$data);
1213
					}
1214
				}
1215
				$i++;
1216
			}
1217
			fclose($handle);
1218
			if ($globalTransaction) $Connection->db->commit();
1219
		}
1220
		return '';
1221
        }
1222
1223
	public static function marine_identity_fam() {
1224
		global $tmp_dir, $globalTransaction;
1225
		$query = "TRUNCATE TABLE marine_identity";
1226
		try {
1227
			$Connection = new Connection();
1228
			$sth = $Connection->db->prepare($query);
1229
                        $sth->execute();
1230
                } catch(PDOException $e) {
1231
                        return "error : ".$e->getMessage();
1232
                }
1233
1234
		
1235
		//update_db::unzip($out_file);
1236
		$delimiter = "\t";
1237
		$Connection = new Connection();
1238
		if (($handle = fopen($tmp_dir.'marine_identity.tsv', 'r')) !== FALSE)
1239
		{
1240
			$i = 0;
1241
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1242
			//$Connection->db->beginTransaction();
1243
			if ($globalTransaction) $Connection->db->beginTransaction();
1244
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1245
			{
1246
				if ($i > 0) {
1247
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1248
					$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)';
1249
					try {
1250
						$sth = $Connection->db->prepare($query);
1251
						$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]));
1252
					} catch(PDOException $e) {
1253
						return "error : ".$e->getMessage();
1254
					}
1255
				}
1256
				$i++;
1257
			}
1258
			fclose($handle);
1259
			if ($globalTransaction) $Connection->db->commit();
1260
		}
1261
		return '';
1262
        }
1263
1264
	public static function satellite_fam() {
1265
		global $tmp_dir, $globalTransaction;
1266
		$query = "TRUNCATE TABLE satellite";
1267
		try {
1268
			$Connection = new Connection();
1269
			$sth = $Connection->db->prepare($query);
1270
			$sth->execute();
1271
		} catch(PDOException $e) {
1272
			return "error : ".$e->getMessage();
1273
		}
1274
		$delimiter = "\t";
1275
		$Connection = new Connection();
1276
		if (($handle = fopen($tmp_dir.'satellite.tsv', 'r')) !== FALSE)
1277
		{
1278
			$i = 0;
1279
			if ($globalTransaction) $Connection->db->beginTransaction();
1280
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1281
			{
1282
				if ($i > 0) {
1283
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1284
					$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) 
1285
					    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)';
1286
					try {
1287
						$sth = $Connection->db->prepare($query);
1288
						$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]));
1289
					} catch(PDOException $e) {
1290
						return "error : ".$e->getMessage();
1291
					}
1292
				}
1293
				$i++;
1294
			}
1295
			fclose($handle);
1296
			if ($globalTransaction) $Connection->db->commit();
1297
		}
1298
		return '';
1299
	}
1300
1301
	public static function banned_fam() {
1302
		global $tmp_dir, $globalTransaction;
1303
		$query = "UPDATE airlines SET ban_eu = 0";
1304
		try {
1305
			$Connection = new Connection();
1306
			$sth = $Connection->db->prepare($query);
1307
			$sth->execute();
1308
		} catch(PDOException $e) {
1309
			return "error : ".$e->getMessage();
1310
		}
1311
1312
		$Connection = new Connection();
1313
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1314
		{
1315
			if ($globalTransaction) $Connection->db->beginTransaction();
1316
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1317
			{
1318
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1319
				if ($data[0] != '') {
1320
					$icao = $data[0];
1321
					try {
1322
						$sth = $Connection->db->prepare($query);
1323
						$sth->execute(array(':icao' => $icao));
1324
					} catch(PDOException $e) {
1325
						return "error : ".$e->getMessage();
1326
					}
1327
				}
1328
			}
1329
			fclose($handle);
1330
			if ($globalTransaction) $Connection->db->commit();
1331
		}
1332
		return '';
1333
        }
1334
1335
	public static function tle($filename,$tletype) {
1336
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1337
		global $tmp_dir, $globalTransaction;
1338
		//$Spotter = new Spotter();
1339
		
1340
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1341
		try {
1342
			$Connection = new Connection();
1343
			$sth = $Connection->db->prepare($query);
1344
                        $sth->execute(array(':source' => $filename));
1345
                } catch(PDOException $e) {
1346
                        return "error : ".$e->getMessage();
1347
                }
1348
		
1349
		$Connection = new Connection();
1350
		if (($handle = fopen($filename, 'r')) !== FALSE)
1351
		{
1352
			$i = 0;
1353
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1354
			//$Connection->db->beginTransaction();
1355
			$dbdata = array();
1356
			while (($data = fgets($handle, 1000)) !== FALSE)
1357
			{
1358
				if ($i == 0) {
1359
					$dbdata['name'] = trim($data);
1360
					$i++;
1361
				} elseif ($i == 1) {
1362
					$dbdata['tle1'] = trim($data);
1363
					$i++;
1364
				} elseif ($i == 2) {
1365
					$dbdata['tle2'] = trim($data);
1366
					//print_r($dbdata);
1367
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1368
					try {
1369
						$sth = $Connection->db->prepare($query);
1370
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1371
					} catch(PDOException $e) {
1372
						return "error : ".$e->getMessage();
1373
					}
1374
1375
					$i = 0;
1376
				}
1377
			}
1378
			fclose($handle);
1379
			//$Connection->db->commit();
1380
		}
1381
		return '';
1382
        }
1383
1384
	public static function satellite_ucsdb($filename) {
1385
		global $tmp_dir, $globalTransaction;
1386
		$query = "DELETE FROM satellite";
1387
		try {
1388
			$Connection = new Connection();
1389
			$sth = $Connection->db->prepare($query);
1390
			$sth->execute(array(':source' => $filename));
1391
		} catch(PDOException $e) {
1392
			return "error : ".$e->getMessage();
1393
		}
1394
		
1395
		$Connection = new Connection();
1396
		if (($handle = fopen($filename, 'r')) !== FALSE)
1397
		{
1398
			$i = 0;
1399
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1400
			//$Connection->db->beginTransaction();
1401
			$dbdata = array();
0 ignored issues
show
Unused Code introduced by
$dbdata 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...
1402
			while (($data = fgetcsv($handle, 1000,"\t")) !== FALSE)
1403
			{
1404
				if ($i > 0 && $data[0] != '') {
1405
					$sources = trim($data[28].' '.$data[29].' '.$data[30].' '.$data[31].' '.$data[32].' '.$data[33]);
1406
					$period = str_replace(',','',$data[14]);
1407
					if (!empty($period) && strpos($period,'days')) $period = str_replace(' days','',$period)*24*60;
1408
					if ($data[18] != '') $launch_date = date('Y-m-d',strtotime($data[18]));
1409
					else $launch_date = NULL;
1410
					$data = array_map(function($value) {
1411
						return trim($value) === '' ? null : $value;
1412
					}, $data);
1413
					//print_r($data);
1414
					$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) 
1415
					    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)';
1416
					try {
1417
						$sth = $Connection->db->prepare($query);
1418
						$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));
1419
					} catch(PDOException $e) {
1420
						return "error : ".$e->getMessage();
1421
					}
1422
				}
1423
				$i++;
1424
			}
1425
			fclose($handle);
1426
			//$Connection->db->commit();
1427
		}
1428
		return '';
1429
	}
1430
1431
	public static function satellite_celestrak($filename) {
1432
		global $tmp_dir, $globalTransaction;
1433
		$satcat_sources = array(
1434
			'AB' => array('country' => 'Multinational', 'owner' => 'Arab Satellite Communications Org. (ASCO)'),
1435
			'ABS' => array('country' => 'Multinational', 'owner' => 'Asia Broadcast Satellite Ltd.'),
1436
			'AC' => array('country' => 'China', 'owner' => 'Asia Satellite Telecommunications Co. Ltd.'),
1437
			'ALG' => array('country' => 'Algeria', 'owner' => ''),
1438
			'ARGN' => array('country' => 'Argentina', 'owner' => ''),
1439
			'ASRA' => array('country' => 'Austria', 'owner' => ''),
1440
			'AUS' => array('country' => 'Australia', 'owner' => ''),
1441
			'AZER' => array('country' => 'Azerbaijan', 'owner' => ''),
1442
			'BEL' => array('country' => 'Belgium', 'owner' => ''),
1443
			'BELA' => array('country' => 'Belarus', 'owner' => ''),
1444
			'BERM' => array('country' => 'Bermuda', 'owner' => ''),
1445
			'BOL' => array('country' => 'Bolivia', 'owner' => ''),
1446
			'BRAZ' => array('country' => 'Brazil', 'owner' => ''),
1447
			'CA' => array('country' => 'Canada', 'owner' => ''),
1448
			'CHBZ' => array('country' => 'China/Brazil', 'owner' => ''),
1449
			'CHLE' => array('country' => 'Chile', 'owner' => ''),
1450
			'CIS' => array('country' => 'Russia', 'owner' => ''),
1451
			'COL' => array('country' => 'Colombia', 'owner' => ''),
1452
			'CZCH' => array('country' => 'Czech Republic (former Czechoslovakia)', 'owner' => ''),
1453
			'DEN' => array('country' => 'Denmark', 'owner' => ''),
1454
			'ECU' => array('country' => 'Ecuador', 'owner' => ''),
1455
			'EGYP' => array('country' => 'Egypt', 'owner' => ''),
1456
			'ESA' => array('country' => 'Multinational', 'owner' => 'European Space Agency'),
1457
			'ESRO' => array('country' => 'Multinational', 'owner' => 'European Space Research Organization'),
1458
			'EST' => array('country' => 'Estonia','owner' => ''),
1459
			'EUME' => array('country' => 'Multinational', 'owner' => 'EUMETSAT (European Organization for the Exploitation of Meteorological Satellites)'),
1460
			'EUTE' => array('country' => 'Multinational', 'owner' => 'European Telecommunications Satellite Consortium (EUTELSAT)'),
1461
			'FGER' => array('country' => 'France/Germany', 'owner' => ''),
1462
			'FIN' => array('country' => 'Finland', 'owner' => ''),
1463
			'FR' => array('country' => 'France', 'owner' => ''),
1464
			'FRIT' => array('country' => 'France/Italy', 'owner' => ''),
1465
			'GER' => array('country' => 'Germany', 'owner' => ''),
1466
			'GLOB' => array('country' => 'USA', 'owner' => 'Globalstar'),
1467
			'GREC' => array('country' => 'Greece', 'owner' => ''),
1468
			'HUN' => array('country' => 'Hungary', 'owner' => ''),
1469
			'IM' => array('country' => 'United Kingdom', 'owner' => 'INMARSAT, Ltd.'),
1470
			'IND' => array('country' => 'India', 'owner' => ''),
1471
			'INDO' => array('country' => 'Indonesia', 'owner' => ''),
1472
			'IRAN' => array('country' => 'Iran', 'owner' => ''),
1473
			'IRAQ' => array('country' => 'Iraq', 'owner' => ''),
1474
			'IRID' => array('country' => 'USA', 'owner' => 'Iridium Satellite LLC'),
1475
			'ISRA' => array('country' => 'Israel', 'owner' => ''),
1476
			'ISRO' => array('country' => 'India', 'owner' => 'Indian Space Research Organisation (ISRO)'),
1477
			'ISS' => array('country' => 'Multinational', 'owner' => 'NASA/Multinational'),
1478
			'IT' => array('country' => 'Italy', 'owner' => ''),
1479
			'ITSO' => array('country' => 'USA', 'owner' => 'Intelsat, S.A.'),
1480
			'JPN' => array('country' => 'Japan', 'owner' => ''),
1481
			'KAZ' => array('country' => 'Kazakhstan', 'owner' => ''),
1482
			'LAOS' => array('country' => 'Laos', 'owner' => ''),
1483
			'LTU' => array('country' => 'Lithuania', 'owner' => ''),
1484
			'LUXE' => array('country' => 'Luxembourg', 'owner' => ''),
1485
			'MALA' => array('country' => 'Malaysia', 'owner' => ''),
1486
			'MEX' => array('country' => 'Mexico', 'owner' => ''),
1487
			'NATO' => array('country' => 'Multinational', 'owner' => 'North Atlantic Treaty Organization'),
1488
			'NETH' => array('country' => 'Netherlands', 'owner' => ''),
1489
			'NICO' => array('country' => 'USA', 'owner' => 'New ICO'),
1490
			'NIG' => array('country' => 'Nigeria', 'owner' => ''),
1491
			'NKOR' => array('country' => 'North Korea', 'owner' => ''),
1492
			'NOR' => array('country' => 'Norway', 'owner' => ''),
1493
			'O3B' => array('country' => 'United Kingdom', 'owner' => 'O3b Networks Ltd.'),
1494
			'ORB' => array('country' => 'USA', 'owner' => 'ORBCOMM Inc.'),
1495
			'PAKI' => array('country' => 'Pakistan', 'owner' => ''),
1496
			'PERU' => array('country' => 'Peru', 'owner' => ''),
1497
			'POL' => array('country' => 'Poland', 'owner' => ''),
1498
			'POR' => array('country' => 'Portugal', 'owner' => ''),
1499
			'PRC' => array('country' => 'China', 'owner' => ''),
1500
			'PRES' => array('country' => 'Multinational', 'owner' => 'China/ESA'),
1501
			'RASC' => array('country' => 'Multinational', 'owner' => 'Regional African Satellite Communications Organisation (RASCOM)'),
1502
			'ROC' => array('country' => 'Taiwan', 'owner' => ''),
1503
			'ROM' => array('country' => 'Romania', 'owner' => ''),
1504
			'RP' => array('country' => 'Philippines', 'owner' => ''),
1505
			'SAFR' => array('country' => 'South Africa', 'owner' => ''),
1506
			'SAUD' => array('country' => 'Saudi Arabia', 'owner' => ''),
1507
			'SEAL' => array('country' => 'USA', 'owner' => ''),
1508
			'SES' => array('country' => 'Multinational', 'owner' => 'SES World Skies'),
1509
			'SING' => array('country' => 'Singapore', 'owner' => ''),
1510
			'SKOR' => array('country' => 'South Korea', 'owner' => ''),
1511
			'SPN' => array('country' => 'Spain', 'owner' => ''),
1512
			'STCT' => array('country' => 'Singapore/Taiwan', 'owner' => ''),
1513
			'SWED' => array('country' => 'Sweden', 'owner' => ''),
1514
			'SWTZ' => array('country' => 'Switzerland', 'owner' => ''),
1515
			'THAI' => array('country' => 'Thailand', 'owner' => ''),
1516
			'TMMC' => array('country' => 'Turkmenistan/Monaco', 'owner' => ''),
1517
			'TURK' => array('country' => 'Turkey', 'owner' => ''),
1518
			'UAE' => array('country' => 'United Arab Emirates', 'owner' => ''),
1519
			'UK' => array('country' => 'United Kingdom', 'owner' => ''),
1520
			'UKR' => array('country' => 'Ukraine', 'owner' => ''),
1521
			'URY' => array('country' => 'Uruguay', 'owner' => ''),
1522
			'US' => array('country' => 'USA', 'owner' => ''),
1523
			'USBZ' => array('country' => 'USA/Brazil', 'owner' => ''),
1524
			'VENZ' => array('country' => 'Venezuela', 'owner' => ''),
1525
			'VTNM' => array('country' => 'Vietnam', 'owner' => '')
1526
		);
1527
		$satcat_launch_site = array(
1528
			'AFETR' => 'Cape Canaveral',
1529
			'AFWTR' => 'Vandenberg AFB',
1530
			'CAS' => 'Canaries Airspace',
1531
			'DLS' => 'Dombarovsky Air Base',
1532
			'ERAS' => 'Eastern Range Airspace',
1533
			'FRGUI' => 'Guiana Space Center',
1534
			'HGSTR' => 'Hammaguira Space Track Range, Algeria',
1535
			'JSC' => 'Jiuquan Satellite Launch Center',
1536
			'KODAK' => 'Kodiak Launch Complex',
1537
			'KSCUT' => 'Uchinoura Space Center',
1538
			'KWAJ' => 'Kwajalein Island',
1539
			'KYMSC' => 'Kapustin Yar Missile and Space Complex, Russia',
1540
			'NSC' => 'Naro Space Center',
1541
			'PLMSC' => 'Plesetsk Cosmodrome',
1542
			'SEAL' => 'Sea Launch',
1543
			'SEMLS' => 'Semnan Satellite Launch Site, Iran',
1544
			'SNMLP' => 'San Marco Launch Platform, Indian Ocean (Kenya)',
1545
			'SRILR' => 'Satish Dhawan Space Center',
1546
			'SUBL' => 'Submarine Launch Platform (mobile), Russia',
1547
			'SVOBO' => 'Svobodny Cosmodrome',
1548
			'TAISC' => 'Taiyuan Launch Center',
1549
			'TANSC' => 'Tanegashima Space Center',
1550
			'TYMSC' => 'Baikonur Cosmodrome',
1551
			'VOSTO' => 'Vostochny Cosmodrome',
1552
			'WLPIS' => 'Wallops Island Flight Facility',
1553
			'WOMRA' => 'Woomera, Australia',
1554
			'WRAS' => 'Western Range Airspace',
1555
			'WSC' => 'Wenchang Satellite Launch Center',
1556
			'XICLF' => 'Xichang Satellite Launch Center',
1557
			'YAVNE' => 'Palmachim Launch Complex',
1558
			'YUN' => 'Yunsong Launch Site'
1559
		);
1560
1561
		/*
1562
		$query = "DELETE FROM satellite";
1563
		try {
1564
			$Connection = new Connection();
1565
			$sth = $Connection->db->prepare($query);
1566
			$sth->execute(array(':source' => $filename));
1567
		} catch(PDOException $e) {
1568
			return "error : ".$e->getMessage();
1569
		}
1570
		*/
1571
		
1572
		$Connection = new Connection();
1573
		if (($handle = fopen($filename, 'r')) !== FALSE)
1574
		{
1575
			$i = 0;
1576
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1577
			//$Connection->db->beginTransaction();
1578
			$dbdata = array();
0 ignored issues
show
Unused Code introduced by
$dbdata 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...
1579
			while (($data = fgets($handle, 1000)) !== FALSE)
1580
			{
1581
				$result = array();
1582
				$result['cospar'] = trim(substr($data,0,11));
1583
				$result['norad'] = trim(substr($data,13,6));
1584
				$result['operational'] = trim(substr($data,21,1));
1585
				$result['name'] = trim(substr($data,23,24));
1586
				/*
1587
				    * R/B(1) = Rocket body, first stage
1588
				    * R/B(2) = Rocket body, second stage
1589
				    * DEB = Debris
1590
				    * PLAT = Platform
1591
				    * Items in parentheses are alternate names
1592
				    * Items in brackets indicate type of object
1593
				    (e.g., BREEZE-M DEB [TANK] = tank)
1594
				    * An ampersand (&) indicates two or more objects are attached
1595
				*/
1596
				
1597
				$owner_code = trim(substr($data,49,5));
1598
				$result['country_owner'] = $satcat_sources[$owner_code]['country'];
1599
				$result['owner'] = $satcat_sources[$owner_code]['owner'];
1600
				$result['launch_date'] = trim(substr($data,56,10));
1601
				$launch_site_code = trim(substr($data,68,5));
1602
				$result['launch_site'] = $satcat_launch_site[$launch_site_code];
1603
				$result['lifetime'] = trim(substr($data,75,10));
1604
				$result['period'] = trim(substr($data,87,7));
1605
				$result['inclination'] = trim(substr($data,96,5));
1606
				$result['apogee'] = trim(substr($data,103,6));
1607
				$result['perigee'] = trim(substr($data,111,6));
1608
				//$result['radarcross'] = trim(substr($data,119,8));
1609
				$result['status'] = trim(substr($data,129,3));
1610
				print_r($result);
1611
				$result = array_map(function($value) {
1612
					return trim($value) === '' ? null : $value;
1613
				}, $result);
1614
				//print_r($data);
1615
				if ($result['operational'] != 'D') {
1616
					$query = "SELECT * FROM satellite WHERE cospar = :cospar LIMIT 1";
1617
					try {
1618
						$Connection = new Connection();
1619
						$sth = $Connection->db->prepare($query);
1620
						$sth->execute(array(':cospar' => $result['cospar']));
1621
						$exist = $sth->fetchAll(PDO::FETCH_ASSOC);
1622
					} catch(PDOException $e) {
1623
						return "error : ".$e->getMessage();
1624
					}
1625
					if (empty($exist)) {
1626
						$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) 
1627
						    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)';
1628
						try {
1629
							$sth = $Connection->db->prepare($query);
1630
							$sth->execute(array(
1631
							    ':name' => $result['name'], ':name_alternate' => '', ':country_un' => '', ':country_owner' => $result['country_owner'], ':owner' => $result['owner'], ':users' => '', ':purpose' => '', ':purpose_detailed' => '', ':orbit' => $result['status'],
1632
							    ':type' => '', ':longitude_geo' => NULL, ':perigee' => !empty($result['perigee']) ? $result['perigee'] : NULL, ':apogee' => !empty($result['apogee']) ? $result['apogee'] : NULL, ':eccentricity' => NULL, ':inclination' => $result['inclination'],
1633
							    ':period' => !empty($result['period']) ? $result['period'] : NULL, ':launch_mass' => NULL, ':dry_mass' => NULL, ':power' => NULL, ':launch_date' => $result['launch_date'], ':lifetime' => $result['lifetime'], 
1634
							    ':contractor' => '',':country_contractor' => '', ':launch_site' => $result['launch_site'], ':launch_vehicule' => '', ':cospar' => $result['cospar'], ':norad' => $result['norad'], ':comments' => '', ':source_orbital' => '', ':sources' => ''
1635
							    )
1636
							);
1637
						} catch(PDOException $e) {
1638
							return "error : ".$e->getMessage();
1639
						}
1640
					} elseif ($exist[0]['name'] != $result['name'] && $exist[0]['name_alternate'] != $result['name']) {
1641
						$query = "UPDATE satellite SET name_alternate = :name_alternate WHERE cospar = :cospar";
1642
						try {
1643
							$Connection = new Connection();
1644
							$sth = $Connection->db->prepare($query);
1645
							$sth->execute(array(':name_alternate' => $result['name'],':cospar' => $result['cospar']));
1646
						} catch(PDOException $e) {
1647
							return "error : ".$e->getMessage();
1648
						}
1649
					}
1650
				}
1651
				
1652
				$i++;
1653
			}
1654
			fclose($handle);
1655
			//$Connection->db->commit();
1656
		}
1657
		return '';
1658
        }
1659
1660
	/**
1661
        * Convert a HTML table to an array
1662
        * @param String $data HTML page
1663
        * @return Array array of the tables in HTML page
1664
        */
1665
/*
1666
        private static function table2array($data) {
1667
                $html = str_get_html($data);
1668
                $tabledata=array();
1669
                foreach($html->find('tr') as $element)
1670
                {
1671
                        $td = array();
1672
                        foreach( $element->find('th') as $row)
1673
                        {
1674
                                $td [] = trim($row->plaintext);
1675
                        }
1676
                        $td=array_filter($td);
1677
                        $tabledata[] = $td;
1678
1679
                        $td = array();
1680
                        $tdi = array();
1681
                        foreach( $element->find('td') as $row)
1682
                        {
1683
                                $td [] = trim($row->plaintext);
1684
                                $tdi [] = trim($row->innertext);
1685
                        }
1686
                        $td=array_filter($td);
1687
                        $tdi=array_filter($tdi);
1688
                    //    $tabledata[]=array_merge($td,$tdi);
1689
                        $tabledata[]=$td;
1690
                }
1691
                return(array_filter($tabledata));
1692
        }
1693
*/
1694
       /**
1695
        * Get data from form result
1696
        * @param String $url form URL
1697
        * @return String the result
1698
        */
1699
/*
1700
        private static function getData($url) {
1701
                $ch = curl_init();
1702
                curl_setopt($ch, CURLOPT_URL, $url);
1703
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1704
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1705
                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');
1706
                return curl_exec($ch);
1707
        }
1708
*/
1709
/*
1710
	public static function waypoints() {
1711
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1712
		$table = update_db::table2array($data);
1713
//		print_r($table);
1714
		$query = 'TRUNCATE TABLE waypoints';
1715
		try {
1716
			$Connection = new Connection();
1717
			$sth = $Connection->db->prepare($query);
1718
                        $sth->execute();
1719
                } catch(PDOException $e) {
1720
                        return "error : ".$e->getMessage();
1721
                }
1722
1723
		$query_dest = 'INSERT INTO waypoints (ident,latitude,longitude,control,usage) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1724
		$Connection = new Connection();
1725
		$sth_dest = $Connection->db->prepare($query_dest);
1726
		$Connection->db->beginTransaction();
1727
                foreach ($table as $row) {
1728
            		if ($row[0] != 'Ident') {
1729
				$ident = $row[0];
1730
				$latitude = $row[2];
1731
				$longitude = $row[3];
1732
				$control = $row[4];
1733
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1734
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1735
				try {
1736
					$sth_dest->execute($query_dest_values);
1737
				} catch(PDOException $e) {
1738
					return "error : ".$e->getMessage();
1739
				}
1740
			}
1741
                }
1742
		$Connection->db->commit();
1743
1744
	}
1745
*/
1746
	public static function waypoints($filename) {
1747
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1748
		global $tmp_dir, $globalTransaction;
1749
		//$Spotter = new Spotter();
1750
		//$out_file = $tmp_dir.'translation.zip';
1751
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1752
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1753
		$Connection = new Connection();
1754
		//update_db::unzip($out_file);
1755
		$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...
1756
		$delimiter = ' ';
1757
		if (($handle = fopen($filename, 'r')) !== FALSE)
1758
		{
1759
			$i = 0;
1760
			if ($globalTransaction) $Connection->db->beginTransaction();
1761
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1762
			{
1763
				$i++;
1764
				if($i > 3 && count($row) > 2) {
1765
					$data = array_values(array_filter($row));
1766
					$cntdata = count($data);
1767
					if ($cntdata > 10) {
1768
						$value = $data[9];
1769
						
1770
						for ($i =10;$i < $cntdata;$i++) {
1771
							$value .= ' '.$data[$i];
1772
						}
1773
						$data[9] = $value;
1774
					}
1775
					//print_r($data);
1776
					if (count($data) > 9) {
1777
						$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)';
1778
						try {
1779
							$sth = $Connection->db->prepare($query);
1780
							$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]));
1781
						} catch(PDOException $e) {
1782
							return "error : ".$e->getMessage();
1783
						}
1784
					}
1785
				}
1786
			}
1787
			fclose($handle);
1788
			if ($globalTransaction) $Connection->db->commit();
1789
		}
1790
		return '';
1791
        }
1792
1793
	public static function ivao_airlines($filename) {
1794
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1795
		global $tmp_dir, $globalTransaction;
1796
		//$query = 'TRUNCATE TABLE airlines';
1797
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1798
		try {
1799
			$Connection = new Connection();
1800
			$sth = $Connection->db->prepare($query);
1801
                        $sth->execute();
1802
                } catch(PDOException $e) {
1803
                        return "error : ".$e->getMessage();
1804
                }
1805
1806
		$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...
1807
		$delimiter = ':';
1808
		$Connection = new Connection();
1809
		if (($handle = fopen($filename, 'r')) !== FALSE)
1810
		{
1811
			if ($globalTransaction) $Connection->db->beginTransaction();
1812
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1813
			{
1814
				if(count($row) > 1) {
1815
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1816
					try {
1817
						$sth = $Connection->db->prepare($query);
1818
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1819
					} catch(PDOException $e) {
1820
						return "error : ".$e->getMessage();
1821
					}
1822
				}
1823
			}
1824
			fclose($handle);
1825
			if ($globalTransaction) $Connection->db->commit();
1826
		}
1827
		return '';
1828
        }
1829
	
1830
	public static function update_airspace() {
1831
		global $tmp_dir, $globalDBdriver;
1832
		include_once('class.create_db.php');
1833
		$Connection = new Connection();
1834
		if ($Connection->tableExists('airspace')) {
1835
			$query = 'DROP TABLE airspace';
1836
			try {
1837
				$sth = $Connection->db->prepare($query);
1838
                    		$sth->execute();
1839
	                } catch(PDOException $e) {
1840
				return "error : ".$e->getMessage();
1841
	                }
1842
	        }
1843
1844
1845
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1846
		else {
1847
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1848
			$query = "CREATE EXTENSION postgis";
1849
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1850
			try {
1851
				$sth = $Connection->db->prepare($query);
1852
				$sth->execute();
1853
			} catch(PDOException $e) {
1854
				return "error : ".$e->getMessage();
1855
			}
1856
		}
1857
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1858
		return $error;
1859
	}
1860
1861
	public static function update_notam_fam() {
1862
		global $tmp_dir, $globalDebug;
1863
		include_once('class.create_db.php');
1864
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1865
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1866
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1867
		$error = '';
1868
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1869
			if ($globalDebug) echo "Gunzip...";
1870
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1871
			if ($globalDebug) echo "Add to DB...";
1872
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1873
			$NOTAM = new NOTAM();
1874
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1875
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1876
		if ($error != '') {
1877
			return $error;
1878
		} elseif ($globalDebug) echo "Done\n";
1879
		return '';
1880
	}
1881
1882
	public static function update_vatsim() {
1883
		global $tmp_dir;
1884
		include_once('class.create_db.php');
1885
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1886
		return $error;
1887
	}
1888
	
1889
	public static function update_countries() {
1890
		global $tmp_dir, $globalDBdriver;
1891
		include_once('class.create_db.php');
1892
		$Connection = new Connection();
1893
		if ($Connection->tableExists('countries')) {
1894
			$query = 'DROP TABLE countries';
1895
			try {
1896
				$sth = $Connection->db->prepare($query);
1897
            	        	$sth->execute();
1898
	                } catch(PDOException $e) {
1899
    	                	echo "error : ".$e->getMessage();
1900
	                }
1901
		}
1902
		if ($globalDBdriver == 'mysql') {
1903
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1904
		} else {
1905
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1906
		}
1907
		$error = create_db::import_file($tmp_dir.'countries.sql');
1908
		return $error;
1909
	}
1910
1911
	
1912
	public static function update_waypoints() {
1913
		global $tmp_dir;
1914
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1915
//		update_db::unzip($tmp_dir.'AptNav.zip');
1916
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1917
//		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');
1918
		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');
1919
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1920
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1921
		return $error;
1922
	}
1923
1924
	public static function update_ivao() {
1925
		global $tmp_dir, $globalDebug;
1926
		$Common = new Common();
1927
		$error = '';
1928
		//Direct download forbidden
1929
		//if ($globalDebug) echo "IVAO : Download...";
1930
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1931
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1932
			if ($globalDebug) echo "Unzip...";
1933
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1934
			if ($globalDebug) echo "Add to DB...";
1935
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1936
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1937
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1938
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1939
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1940
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1941
		if ($error != '') {
1942
			return $error;
1943
		} elseif ($globalDebug) echo "Done\n";
1944
		return '';
1945
	}
1946
1947
	public static function update_routes() {
1948
		global $tmp_dir, $globalDebug;
1949
		$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...
1950
		if ($globalDebug) echo "Routes : Download...";
1951
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1952
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1953
			if ($globalDebug) echo "Gunzip...";
1954
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1955
			if ($globalDebug) echo "Add to DB...";
1956
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1957
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1958
		if ($error != '') {
1959
			return $error;
1960
		} elseif ($globalDebug) echo "Done\n";
1961
		return '';
1962
	}
1963
	public static function update_oneworld() {
1964
		global $tmp_dir, $globalDebug;
1965
		$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...
1966
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1967
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1968
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1969
			if ($globalDebug) echo "Gunzip...";
1970
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1971
			if ($globalDebug) echo "Add to DB...";
1972
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1973
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1974
		if ($error != '') {
1975
			return $error;
1976
		} elseif ($globalDebug) echo "Done\n";
1977
		return '';
1978
	}
1979
	public static function update_skyteam() {
1980
		global $tmp_dir, $globalDebug;
1981
		$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...
1982
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1983
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1984
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1985
			if ($globalDebug) echo "Gunzip...";
1986
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1987
			if ($globalDebug) echo "Add to DB...";
1988
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1989
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1990
		if ($error != '') {
1991
			return $error;
1992
		} elseif ($globalDebug) echo "Done\n";
1993
		return '';
1994
	}
1995
	public static function update_ModeS() {
1996
		global $tmp_dir, $globalDebug;
1997
/*
1998
		if ($globalDebug) echo "Modes : Download...";
1999
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
2000
		if ($globalDebug) echo "Unzip...";
2001
		update_db::unzip($tmp_dir.'basestation_latest.zip');
2002
		if ($globalDebug) echo "Add to DB...";
2003
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
2004
		if ($error != true) {
2005
			echo $error;
2006
			exit;
2007
		} elseif ($globalDebug) echo "Done\n";
2008
*/
2009
		if ($globalDebug) echo "Modes : Download...";
2010
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
2011
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
2012
2013
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
2014
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
2015
			if ($globalDebug) echo "Unzip...";
2016
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
2017
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
2018
			if ($globalDebug) echo "Add to DB...";
2019
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
2020
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
2021
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
2022
		if ($error != '') {
2023
			return $error;
2024
		} elseif ($globalDebug) echo "Done\n";
2025
		return '';
2026
	}
2027
2028
	public static function update_ModeS_faa() {
2029
		global $tmp_dir, $globalDebug;
2030
		if ($globalDebug) echo "Modes FAA: Download...";
2031
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
2032
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
2033
			if ($globalDebug) echo "Unzip...";
2034
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
2035
			if ($globalDebug) echo "Add to DB...";
2036
			$error = update_db::modes_faa();
2037
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
2038
		if ($error != '') {
2039
			return $error;
2040
		} elseif ($globalDebug) echo "Done\n";
2041
		return '';
2042
	}
2043
2044
	public static function update_ModeS_flarm() {
2045
		global $tmp_dir, $globalDebug;
2046
		if ($globalDebug) echo "Modes Flarmnet: Download...";
2047
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
2048
		if (file_exists($tmp_dir.'data.fln')) {
2049
			if ($globalDebug) echo "Add to DB...";
2050
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
2051
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
2052
		if ($error != '') {
2053
			return $error;
2054
		} elseif ($globalDebug) echo "Done\n";
2055
		return '';
2056
	}
2057
2058
	public static function update_ModeS_ogn() {
2059
		global $tmp_dir, $globalDebug;
2060
		if ($globalDebug) echo "Modes OGN: Download...";
2061
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
2062
		if (file_exists($tmp_dir.'ogn.csv')) {
2063
			if ($globalDebug) echo "Add to DB...";
2064
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
2065
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
2066
		if ($error != '') {
2067
			return $error;
2068
		} elseif ($globalDebug) echo "Done\n";
2069
		return '';
2070
	}
2071
2072
	public static function update_owner() {
2073
		global $tmp_dir, $globalDebug, $globalMasterSource;
2074
		
2075
		if ($globalDebug) echo "Owner France: Download...";
2076
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
2077
		if (file_exists($tmp_dir.'owner_f.csv')) {
2078
			if ($globalDebug) echo "Add to DB...";
2079
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
2080
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
2081
		if ($error != '') {
2082
			return $error;
2083
		} elseif ($globalDebug) echo "Done\n";
2084
		
2085
		if ($globalDebug) echo "Owner Ireland: Download...";
2086
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
2087
		if (file_exists($tmp_dir.'owner_ei.csv')) {
2088
			if ($globalDebug) echo "Add to DB...";
2089
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
2090
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
2091
		if ($error != '') {
2092
			return $error;
2093
		} elseif ($globalDebug) echo "Done\n";
2094
		if ($globalDebug) echo "Owner Switzerland: Download...";
2095
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
2096
		if (file_exists($tmp_dir.'owner_hb.csv')) {
2097
			if ($globalDebug) echo "Add to DB...";
2098
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
2099
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
2100
		if ($error != '') {
2101
			return $error;
2102
		} elseif ($globalDebug) echo "Done\n";
2103
		if ($globalDebug) echo "Owner Czech Republic: Download...";
2104
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
2105
		if (file_exists($tmp_dir.'owner_ok.csv')) {
2106
			if ($globalDebug) echo "Add to DB...";
2107
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
2108
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
2109
		if ($error != '') {
2110
			return $error;
2111
		} elseif ($globalDebug) echo "Done\n";
2112
		if ($globalDebug) echo "Owner Australia: Download...";
2113
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
2114
		if (file_exists($tmp_dir.'owner_vh.csv')) {
2115
			if ($globalDebug) echo "Add to DB...";
2116
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
2117
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
2118
		if ($error != '') {
2119
			return $error;
2120
		} elseif ($globalDebug) echo "Done\n";
2121
		if ($globalDebug) echo "Owner Austria: Download...";
2122
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
2123
		if (file_exists($tmp_dir.'owner_oe.csv')) {
2124
			if ($globalDebug) echo "Add to DB...";
2125
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
2126
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
2127
		if ($error != '') {
2128
			return $error;
2129
		} elseif ($globalDebug) echo "Done\n";
2130
		if ($globalDebug) echo "Owner Chile: Download...";
2131
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
2132
		if (file_exists($tmp_dir.'owner_cc.csv')) {
2133
			if ($globalDebug) echo "Add to DB...";
2134
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
2135
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
2136
		if ($error != '') {
2137
			return $error;
2138
		} elseif ($globalDebug) echo "Done\n";
2139
		if ($globalDebug) echo "Owner Colombia: Download...";
2140
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
2141
		if (file_exists($tmp_dir.'owner_hj.csv')) {
2142
			if ($globalDebug) echo "Add to DB...";
2143
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
2144
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
2145
		if ($error != '') {
2146
			return $error;
2147
		} elseif ($globalDebug) echo "Done\n";
2148
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
2149
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
2150
		if (file_exists($tmp_dir.'owner_e7.csv')) {
2151
			if ($globalDebug) echo "Add to DB...";
2152
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
2153
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
2154
		if ($error != '') {
2155
			return $error;
2156
		} elseif ($globalDebug) echo "Done\n";
2157
		if ($globalDebug) echo "Owner Brazil: Download...";
2158
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
2159
		if (file_exists($tmp_dir.'owner_pp.csv')) {
2160
			if ($globalDebug) echo "Add to DB...";
2161
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
2162
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
2163
		if ($error != '') {
2164
			return $error;
2165
		} elseif ($globalDebug) echo "Done\n";
2166
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
2167
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
2168
		if (file_exists($tmp_dir.'owner_vp.csv')) {
2169
			if ($globalDebug) echo "Add to DB...";
2170
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
2171
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
2172
		if ($error != '') {
2173
			return $error;
2174
		} elseif ($globalDebug) echo "Done\n";
2175
		if ($globalDebug) echo "Owner Croatia: Download...";
2176
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
2177
		if (file_exists($tmp_dir.'owner_9a.csv')) {
2178
			if ($globalDebug) echo "Add to DB...";
2179
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
2180
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
2181
		if ($error != '') {
2182
			return $error;
2183
		} elseif ($globalDebug) echo "Done\n";
2184
		if ($globalDebug) echo "Owner Luxembourg: Download...";
2185
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
2186
		if (file_exists($tmp_dir.'owner_lx.csv')) {
2187
			if ($globalDebug) echo "Add to DB...";
2188
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
2189
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
2190
		if ($error != '') {
2191
			return $error;
2192
		} elseif ($globalDebug) echo "Done\n";
2193
		if ($globalDebug) echo "Owner Maldives: Download...";
2194
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
2195
		if (file_exists($tmp_dir.'owner_8q.csv')) {
2196
			if ($globalDebug) echo "Add to DB...";
2197
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
2198
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
2199
		if ($error != '') {
2200
			return $error;
2201
		} elseif ($globalDebug) echo "Done\n";
2202
		if ($globalDebug) echo "Owner New Zealand: Download...";
2203
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
2204
		if (file_exists($tmp_dir.'owner_zk.csv')) {
2205
			if ($globalDebug) echo "Add to DB...";
2206
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
2207
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
2208
		if ($error != '') {
2209
			return $error;
2210
		} elseif ($globalDebug) echo "Done\n";
2211
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
2212
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
2213
		if (file_exists($tmp_dir.'owner_p2.csv')) {
2214
			if ($globalDebug) echo "Add to DB...";
2215
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
2216
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
2217
		if ($error != '') {
2218
			return $error;
2219
		} elseif ($globalDebug) echo "Done\n";
2220
		if ($globalDebug) echo "Owner Slovakia: Download...";
2221
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
2222
		if (file_exists($tmp_dir.'owner_om.csv')) {
2223
			if ($globalDebug) echo "Add to DB...";
2224
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
2225
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
2226
		if ($error != '') {
2227
			return $error;
2228
		} elseif ($globalDebug) echo "Done\n";
2229
		if ($globalDebug) echo "Owner Ecuador: Download...";
2230
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
2231
		if (file_exists($tmp_dir.'owner_hc.csv')) {
2232
			if ($globalDebug) echo "Add to DB...";
2233
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
2234
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
2235
		if ($error != '') {
2236
			return $error;
2237
		} elseif ($globalDebug) echo "Done\n";
2238
		if ($globalDebug) echo "Owner Iceland: Download...";
2239
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
2240
		if (file_exists($tmp_dir.'owner_tf.csv')) {
2241
			if ($globalDebug) echo "Add to DB...";
2242
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
2243
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
2244
		if ($error != '') {
2245
			return $error;
2246
		} elseif ($globalDebug) echo "Done\n";
2247
		if ($globalDebug) echo "Owner Isle of Man: Download...";
2248
		update_db::download('http://antonakis.co.uk/registers/IsleOfMan.txt',$tmp_dir.'owner_m.csv');
2249
		if (file_exists($tmp_dir.'owner_m.csv')) {
2250
			if ($globalDebug) echo "Add to DB...";
2251
			$error = update_db::retrieve_owner($tmp_dir.'owner_m.csv','M');
2252
		} else $error = "File ".$tmp_dir.'owner_m.csv'." doesn't exist. Download failed.";
2253
		if ($error != '') {
2254
			return $error;
2255
		} elseif ($globalDebug) echo "Done\n";
2256
		if ($globalMasterSource) {
2257
			if ($globalDebug) echo "ModeS Netherlands: Download...";
2258
			update_db::download('http://antonakis.co.uk/registers/Netherlands.txt',$tmp_dir.'owner_ph.csv');
2259
			if (file_exists($tmp_dir.'owner_ph.csv')) {
2260
				if ($globalDebug) echo "Add to DB...";
2261
				$error = update_db::retrieve_owner($tmp_dir.'owner_ph.csv','PH');
2262
			} else $error = "File ".$tmp_dir.'owner_ph.csv'." doesn't exist. Download failed.";
2263
			if ($error != '') {
2264
				return $error;
2265
			} elseif ($globalDebug) echo "Done\n";
2266
			if ($globalDebug) echo "ModeS Denmark: Download...";
2267
			update_db::download('http://antonakis.co.uk/registers/Denmark.txt',$tmp_dir.'owner_oy.csv');
2268
			if (file_exists($tmp_dir.'owner_oy.csv')) {
2269
				if ($globalDebug) echo "Add to DB...";
2270
				$error = update_db::retrieve_owner($tmp_dir.'owner_oy.csv','OY');
2271
			} else $error = "File ".$tmp_dir.'owner_oy.csv'." doesn't exist. Download failed.";
2272
			if ($error != '') {
2273
				return $error;
2274
			} elseif ($globalDebug) echo "Done\n";
2275
		} elseif ($globalDebug) echo "Done\n";
2276
		return '';
2277
	}
2278
2279
	public static function update_translation() {
2280
		global $tmp_dir, $globalDebug;
2281
		$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...
2282
		if ($globalDebug) echo "Translation : Download...";
2283
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
2284
		if (file_exists($tmp_dir.'translation.zip')) {
2285
			if ($globalDebug) echo "Unzip...";
2286
			update_db::unzip($tmp_dir.'translation.zip');
2287
			if ($globalDebug) echo "Add to DB...";
2288
			$error = update_db::translation();
2289
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
2290
		if ($error != '') {
2291
			return $error;
2292
		} elseif ($globalDebug) echo "Done\n";
2293
		return '';
2294
	}
2295
2296
	public static function update_translation_fam() {
2297
		global $tmp_dir, $globalDebug;
2298
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
2299
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
2300
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
2301
			if ($globalDebug) echo "Gunzip...";
2302
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
2303
			if ($globalDebug) echo "Add to DB...";
2304
			$error = update_db::translation_fam();
2305
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
2306
		if ($error != '') {
2307
			return $error;
2308
		} elseif ($globalDebug) echo "Done\n";
2309
		return '';
2310
	}
2311
	public static function update_ModeS_fam() {
2312
		global $tmp_dir, $globalDebug;
2313
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
2314
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
2315
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
2316
			if ($globalDebug) echo "Gunzip...";
2317
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
2318
			if ($globalDebug) echo "Add to DB...";
2319
			$error = update_db::modes_fam();
2320
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
2321
		if ($error != '') {
2322
			return $error;
2323
		} elseif ($globalDebug) echo "Done\n";
2324
		return '';
2325
	}
2326
	public static function update_owner_fam() {
2327
		global $tmp_dir, $globalDebug, $globalOwner;
2328
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
2329
		if ($globalOwner === TRUE) {
2330
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
2331
		} else {
2332
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
2333
		}
2334
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
2335
			if ($globalDebug) echo "Gunzip...";
2336
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
2337
			if ($globalDebug) echo "Add to DB...";
2338
			$error = update_db::owner_fam();
2339
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
2340
		if ($error != '') {
2341
			return $error;
2342
		} elseif ($globalDebug) echo "Done\n";
2343
		return '';
2344
	}
2345
	public static function update_routes_fam() {
2346
		global $tmp_dir, $globalDebug;
2347
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
2348
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
2349
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
2350
			if ($globalDebug) echo "Gunzip...";
2351
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
2352
			if ($globalDebug) echo "Add to DB...";
2353
			$error = update_db::routes_fam();
2354
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
2355
		if ($error != '') {
2356
			return $error;
2357
		} elseif ($globalDebug) echo "Done\n";
2358
		return '';
2359
	}
2360
	public static function update_marine_identity_fam() {
2361
		global $tmp_dir, $globalDebug;
2362
		update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz.md5',$tmp_dir.'marine_identity.tsv.gz.md5');
2363
		if (file_exists($tmp_dir.'marine_identity.tsv.gz.md5')) {
2364
			$marine_identity_md5_file = explode(' ',file_get_contents($tmp_dir.'marine_identity.tsv.gz.md5'));
2365
			$marine_identity_md5 = $marine_identity_md5_file[0];
2366
			if (!update_db::check_marine_identity_version($marine_identity_md5)) {
2367
				if ($globalDebug) echo "Marine identity from FlightAirMap website : Download...";
2368
				update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz',$tmp_dir.'marine_identity.tsv.gz');
2369
				if (file_exists($tmp_dir.'marine_identity.tsv.gz')) {
2370
					if ($globalDebug) echo "Gunzip...";
2371
					update_db::gunzip($tmp_dir.'marine_identity.tsv.gz');
2372
					if ($globalDebug) echo "Add to DB...";
2373
					$error = update_db::marine_identity_fam();
2374
				} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." doesn't exist. Download failed.";
2375
				if ($error != '') {
2376
					return $error;
2377
				} elseif ($globalDebug) {
2378
					update_db::insert_marine_identity_version($marine_identity_md5);
2379
					echo "Done\n";
2380
				}
2381
			}
2382
		}
2383
		return '';
2384
	}
2385
2386
	public static function update_satellite_fam() {
2387
		global $tmp_dir, $globalDebug;
2388
		update_db::download('http://data.flightairmap.fr/data/satellite.tsv.gz.md5',$tmp_dir.'satellite.tsv.gz.md5');
2389
		if (file_exists($tmp_dir.'satellite.tsv.gz.md5')) {
2390
			$satellite_md5_file = explode(' ',file_get_contents($tmp_dir.'satellite.tsv.gz.md5'));
2391
			$satellite_md5 = $satellite_md5_file[0];
2392
			if (!update_db::check_satellite_version($marine_identity_md5)) {
0 ignored issues
show
Bug introduced by
The variable $marine_identity_md5 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...
2393
				if ($globalDebug) echo "Satellite from FlightAirMap website : Download...";
2394
				update_db::download('http://data.flightairmap.fr/data/satellite.tsv.gz',$tmp_dir.'satellite.tsv.gz');
2395
				if (file_exists($tmp_dir.'satellite.tsv.gz')) {
2396
					if ($globalDebug) echo "Gunzip...";
2397
					update_db::gunzip($tmp_dir.'satellite.tsv.gz');
2398
					if ($globalDebug) echo "Add to DB...";
2399
					$error = update_db::satellite_fam();
2400
				} else $error = "File ".$tmp_dir.'satellite.tsv.gz'." doesn't exist. Download failed.";
2401
				if ($error != '') {
2402
					return $error;
2403
				} elseif ($globalDebug) {
2404
					update_db::insert_satellite_version($satellite_md5);
2405
					echo "Done\n";
2406
				}
2407
			}
2408
		}
2409
		return '';
2410
	}
2411
	public static function update_banned_fam() {
2412
		global $tmp_dir, $globalDebug;
2413
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
2414
		update_db::download('http://data.flightairmap.fr/data/ban-eu.csv',$tmp_dir.'ban_eu.csv');
2415
		if (file_exists($tmp_dir.'ban_eu.csv')) {
2416
			//if ($globalDebug) echo "Gunzip...";
2417
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
2418
			if ($globalDebug) echo "Add to DB...";
2419
			$error = update_db::banned_fam();
2420
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
2421
		if ($error != '') {
2422
			return $error;
2423
		} elseif ($globalDebug) echo "Done\n";
2424
		return '';
2425
	}
2426
2427
	public static function update_airspace_fam() {
2428
		global $tmp_dir, $globalDebug, $globalDBdriver;
2429
		include_once('class.create_db.php');
2430
		$error = '';
2431
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
2432
		if ($globalDBdriver == 'mysql') {
2433
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2434
		} else {
2435
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2436
		}
2437
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
2438
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
2439
			$airspace_md5 = $airspace_md5_file[0];
2440
			if (!update_db::check_airspace_version($airspace_md5)) {
2441
				if ($globalDBdriver == 'mysql') {
2442
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
2443
				} else {
2444
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
2445
				}
2446
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
2447
					if ($globalDebug) echo "Gunzip...";
2448
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
2449
					if ($globalDebug) echo "Add to DB...";
2450
					$Connection = new Connection();
2451
					if ($Connection->tableExists('airspace')) {
2452
						$query = 'DROP TABLE airspace';
2453
						try {
2454
							$sth = $Connection->db->prepare($query);
2455
    	    	    					$sth->execute();
2456
			            		} catch(PDOException $e) {
2457
							return "error : ".$e->getMessage();
2458
		            			}
2459
		    			}
2460
					$error = create_db::import_file($tmp_dir.'airspace.sql');
2461
					update_db::insert_airspace_version($airspace_md5);
2462
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
2463
			}
2464
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
2465
		if ($error != '') {
2466
			return $error;
2467
		} elseif ($globalDebug) echo "Done\n";
2468
		return '';
2469
	}
2470
2471
	public static function update_geoid_fam() {
2472
		global $tmp_dir, $globalDebug, $globalGeoidSource;
2473
		$error = '';
2474
		if ($globalDebug) echo "Geoid from FlightAirMap website : Download...";
2475
		update_db::download('http://data.flightairmap.fr/data/geoid/'.$globalGeoidSource.'.pgm.gz.md5',$tmp_dir.$globalGeoidSource.'.pgm.gz.md5');
2476
		if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz.md5')) {
2477
			$geoid_md5_file = explode(' ',file_get_contents($tmp_dir.$globalGeoidSource.'.pgm.gz.md5'));
2478
			$geoid_md5 = $geoid_md5_file[0];
2479
			if (!update_db::check_geoid_version($geoid_md5)) {
2480
				update_db::download('http://data.flightairmap.fr/data/geoid/'.$globalGeoidSource.'.pgm.gz',$tmp_dir.$globalGeoidSource.'.pgm.gz');
2481
				if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz')) {
2482
					if ($globalDebug) echo "Gunzip...";
2483
					update_db::gunzip($tmp_dir.$globalGeoidSource.'.pgm.gz',dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm');
2484
					if (file_exists(dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm')) {
2485
						update_db::insert_geoid_version($geoid_md5);
2486
					}
2487
				} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." doesn't exist. Download failed.";
2488
			}
2489
		} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz.md5'." doesn't exist. Download failed.";
2490
		if ($error != '') {
2491
			return $error;
2492
		} elseif ($globalDebug) echo "Done\n";
2493
		return '';
2494
	}
2495
2496
	public static function update_tle() {
2497
		global $tmp_dir, $globalDebug;
2498
		if ($globalDebug) echo "Download TLE : Download...";
2499
		$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',
2500
		'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',
2501
		'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');
2502
		foreach ($alltle as $filename) {
2503
			if ($globalDebug) echo "downloading ".$filename.'...';
2504
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
2505
			if (file_exists($tmp_dir.$filename)) {
2506
				if ($globalDebug) echo "Add to DB ".$filename."...";
2507
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
2508
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
2509
			if ($error != '') {
2510
				echo $error."\n";
2511
			} elseif ($globalDebug) echo "Done\n";
2512
		}
2513
		return '';
2514
	}
2515
2516
	public static function update_ucsdb() {
2517
		global $tmp_dir, $globalDebug;
2518
		if ($globalDebug) echo "Download UCS DB : Download...";
2519
		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');
2520
		if (file_exists($tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt')) {
2521
			if ($globalDebug) echo "Add to DB...";
2522
			$error = update_db::satellite_ucsdb($tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt');
2523
		} else $error = "File ".$tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt'." doesn't exist. Download failed.";
2524
		if ($error != '') {
2525
			echo $error."\n";
2526
		} elseif ($globalDebug) echo "Done\n";
2527
		return '';
2528
	}
2529
2530
	public static function update_celestrak() {
2531
		global $tmp_dir, $globalDebug;
2532
		if ($globalDebug) echo "Download Celestrak DB : Download...";
2533
		update_db::download('https://celestrak.com/pub/satcat.txt',$tmp_dir.'satcat.txt');
2534
		if (file_exists($tmp_dir.'satcat.txt')) {
2535
			if ($globalDebug) echo "Add to DB...";
2536
			$error = update_db::satellite_celestrak($tmp_dir.'satcat.txt');
2537
		} else $error = "File ".$tmp_dir.'satcat.txt'." doesn't exist. Download failed.";
2538
		if ($error != '') {
2539
			echo $error."\n";
2540
		} elseif ($globalDebug) echo "Done\n";
2541
		return '';
2542
	}
2543
2544
	public static function update_models() {
2545
		global $tmp_dir, $globalDebug;
2546
		$error = '';
2547
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2548
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2549
		if (file_exists($tmp_dir.'models.md5sum')) {
2550
			if ($globalDebug) echo "Check files...\n";
2551
			$newmodelsdb = array();
2552
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2553
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2554
					$model = trim($row[2]);
2555
					$newmodelsdb[$model] = trim($row[0]);
2556
				}
2557
			}
2558
			$modelsdb = array();
2559
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2560
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2561
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2562
						$model = trim($row[2]);
2563
						$modelsdb[$model] = trim($row[0]);
2564
					}
2565
				}
2566
			}
2567
			$diff = array_diff($newmodelsdb,$modelsdb);
2568
			foreach ($diff as $key => $value) {
2569
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2570
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2571
				
2572
			}
2573
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2574
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2575
		if ($error != '') {
2576
			return $error;
2577
		} elseif ($globalDebug) echo "Done\n";
2578
		return '';
2579
	}
2580
2581
	public static function update_space_models() {
2582
		global $tmp_dir, $globalDebug;
2583
		$error = '';
2584
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2585
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2586
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2587
			if ($globalDebug) echo "Check files...\n";
2588
			$newmodelsdb = array();
2589
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2590
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2591
					$model = trim($row[2]);
2592
					$newmodelsdb[$model] = trim($row[0]);
2593
				}
2594
			}
2595
			$modelsdb = array();
2596
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2597
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2598
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2599
						$model = trim($row[2]);
2600
						$modelsdb[$model] = trim($row[0]);
2601
					}
2602
				}
2603
			}
2604
			$diff = array_diff($newmodelsdb,$modelsdb);
2605
			foreach ($diff as $key => $value) {
2606
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2607
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2608
				
2609
			}
2610
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2611
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2612
		if ($error != '') {
2613
			return $error;
2614
		} elseif ($globalDebug) echo "Done\n";
2615
		return '';
2616
	}
2617
2618
	public static function update_vehicules_models() {
2619
		global $tmp_dir, $globalDebug;
2620
		$error = '';
2621
		if ($globalDebug) echo "Vehicules models from FlightAirMap website : Download...";
2622
		update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',$tmp_dir.'vehicules_models.md5sum');
2623
		if (file_exists($tmp_dir.'vehicules_models.md5sum')) {
2624
			if ($globalDebug) echo "Check files...\n";
2625
			$newmodelsdb = array();
2626
			if (($handle = fopen($tmp_dir.'vehicules_models.md5sum','r')) !== FALSE) {
2627
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2628
					$model = trim($row[2]);
2629
					$newmodelsdb[$model] = trim($row[0]);
2630
				}
2631
			}
2632
			$modelsdb = array();
2633
			if (file_exists(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum')) {
2634
				if (($handle = fopen(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum','r')) !== FALSE) {
2635
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2636
						$model = trim($row[2]);
2637
						$modelsdb[$model] = trim($row[0]);
2638
					}
2639
				}
2640
			}
2641
			$diff = array_diff($newmodelsdb,$modelsdb);
2642
			foreach ($diff as $key => $value) {
2643
				if ($globalDebug) echo 'Downloading vehicules model '.$key.' ...'."\n";
2644
				update_db::download('http://data.flightairmap.fr/data/models/vehicules/'.$key,dirname(__FILE__).'/../models/vehicules/'.$key);
2645
				
2646
			}
2647
			update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum');
2648
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2649
		if ($error != '') {
2650
			return $error;
2651
		} elseif ($globalDebug) echo "Done\n";
2652
		return '';
2653
	}
2654
2655
	public static function update_aircraft() {
2656
		global $tmp_dir, $globalDebug;
2657
		date_default_timezone_set('UTC');
2658
		//$error = '';
2659
		/*
2660
		if ($globalDebug) echo "Aircrafts : Download...";
2661
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2662
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2663
		//$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);
2664
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2665
//		echo strlen($data_req);
2666
		echo $data;
2667
		*/
2668
		if (file_exists($tmp_dir.'aircrafts.html')) {
2669
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2670
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2671
		    $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...
2672
		    //echo $result;
2673
		    //var_dump(str_get_html($result));
2674
		    //print_r(self::table2array($result));
2675
		}
2676
2677
	}
2678
	
2679
	public static function update_notam() {
2680
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2681
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2682
		$Common = new Common();
2683
		date_default_timezone_set('UTC');
2684
		$query = 'TRUNCATE TABLE notam';
2685
		try {
2686
			$Connection = new Connection();
2687
			$sth = $Connection->db->prepare($query);
2688
                        $sth->execute();
2689
                } catch(PDOException $e) {
2690
                        return "error : ".$e->getMessage();
2691
                }
2692
2693
		$error = '';
2694
		if ($globalDebug) echo "Notam : Download...";
2695
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2696
		if (file_exists($tmp_dir.'notam.rss')) {
2697
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2698
			foreach ($notams['channel']['item'] as $notam) {
2699
				$title = explode(':',$notam['title']);
2700
				$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...
2701
				unset($title[0]);
2702
				$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...
2703
				$description = strip_tags($notam['description'],'<pre>');
2704
				preg_match(':^(.*?)<pre>:',$description,$match);
2705
				$q = explode('/',$match[1]);
2706
				$data['fir'] = $q[0];
2707
				$data['code'] = $q[1];
2708
				$ifrvfr = $q[2];
2709
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2710
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2711
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2712
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2713
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2714
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2715
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2716
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2717
				//$data['scope'] = $q[4];
2718
				$data['lower_limit'] = $q[5];
2719
				$data['upper_limit'] = $q[6];
2720
				$latlonrad = $q[7];
2721
				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...
2722
				$latitude = $Common->convertDec($las,'latitude');
2723
				$longitude = $Common->convertDec($lns,'longitude');
2724
				if ($lac == 'S') $latitude = '-'.$latitude;
2725
				if ($lnc == 'W') $longitude = '-'.$longitude;
2726
				$data['center_latitude'] = $latitude;
2727
				$data['center_longitude'] = $longitude;
2728
				$data['radius'] = intval($radius);
2729
				
2730
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2731
				$data['text'] = $match[1];
2732
				preg_match(':</pre>(.*?)$:',$description,$match);
2733
				$fromto = $match[1];
2734
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2735
				$fromall = trim($match[1]);
2736
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2737
				$from = trim($match[1]);
2738
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2739
				preg_match('#TO:(.*?)$#',$fromto,$match);
2740
				$toall = trim($match[1]);
2741
				if (!preg_match(':Permanent:',$toall)) {
2742
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2743
					$to = trim($match[1]);
2744
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2745
					$data['permanent'] = 0;
2746
				} else {
2747
				    $data['date_end'] = NULL;
2748
				    $data['permanent'] = 1;
2749
				}
2750
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2751
				$NOTAM = new NOTAM();
2752
				$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']);
2753
				unset($data);
2754
			} 
2755
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2756
		if ($error != '') {
2757
			return $error;
2758
		} elseif ($globalDebug) echo "Done\n";
2759
		return '';
2760
	}
2761
	
2762
	public static function create_airspace() {
2763
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2764
		$Connection = new Connection();
2765
		if ($Connection->tableExists('airspace')) {
2766
			if ($globalDBdriver == 'mysql') {
2767
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2768
			} else {
2769
				$query = 'DROP TABLE airspace';
2770
			}
2771
			try {
2772
				$Connection = new Connection();
2773
				$sth = $Connection->db->prepare($query);
2774
				$sth->execute();
2775
			} catch(PDOException $e) {
2776
				return "error : ".$e->getMessage();
2777
			}
2778
		}
2779
		$Common = new Common();
2780
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2781
		$airspace_json = json_decode($airspace_lst,true);
2782
		foreach ($airspace_json['records'] as $airspace) {
2783
			if ($globalDebug) echo $airspace['name']."...\n";
2784
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2785
			if (file_exists($tmp_dir.$airspace['name'])) {
2786
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2787
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2788
				if ($globalDBdriver == 'mysql') {
2789
					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'].'"');
2790
				} else {
2791
					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'].'"');
2792
				}
2793
			}
2794
		}
2795
	}
2796
	
2797
	public static function fix_icaotype() {
2798
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
2799
		$Spotter = new Spotter();
2800
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
2801
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
2802
			try {
2803
				$Connection = new Connection();
2804
				$sth = $Connection->db->prepare($query);
2805
				$sth->execute(array(':new' => $new, ':old' => $old));
2806
			} catch(PDOException $e) {
2807
				return "error : ".$e->getMessage();
2808
			}
2809
		}
2810
	}
2811
2812
	public static function check_last_update() {
2813
		global $globalDBdriver;
2814
		if ($globalDBdriver == 'mysql') {
2815
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2816
		} else {
2817
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2818
		}
2819
		try {
2820
			$Connection = new Connection();
2821
			$sth = $Connection->db->prepare($query);
2822
                        $sth->execute();
2823
                } catch(PDOException $e) {
2824
                        return "error : ".$e->getMessage();
2825
                }
2826
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2827
                if ($row['nb'] > 0) return false;
2828
                else return true;
2829
	}
2830
2831
	public static function insert_last_update() {
2832
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2833
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2834
		try {
2835
			$Connection = new Connection();
2836
			$sth = $Connection->db->prepare($query);
2837
                        $sth->execute();
2838
                } catch(PDOException $e) {
2839
                        return "error : ".$e->getMessage();
2840
                }
2841
	}
2842
2843
	public static function check_airspace_version($version) {
2844
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2845
		try {
2846
			$Connection = new Connection();
2847
			$sth = $Connection->db->prepare($query);
2848
                        $sth->execute(array(':version' => $version));
2849
                } catch(PDOException $e) {
2850
                        return "error : ".$e->getMessage();
2851
                }
2852
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2853
                if ($row['nb'] > 0) return true;
2854
                else return false;
2855
	}
2856
2857
	public static function check_geoid_version($version) {
2858
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'geoid_version' AND value = :version";
2859
		try {
2860
			$Connection = new Connection();
2861
			$sth = $Connection->db->prepare($query);
2862
                        $sth->execute(array(':version' => $version));
2863
                } catch(PDOException $e) {
2864
                        return "error : ".$e->getMessage();
2865
                }
2866
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2867
                if ($row['nb'] > 0) return true;
2868
                else return false;
2869
	}
2870
2871
	public static function check_marine_identity_version($version) {
2872
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'marine_identity_version' AND value = :version";
2873
		try {
2874
			$Connection = new Connection();
2875
			$sth = $Connection->db->prepare($query);
2876
			$sth->execute(array(':version' => $version));
2877
		} catch(PDOException $e) {
2878
			return "error : ".$e->getMessage();
2879
		}
2880
		$row = $sth->fetch(PDO::FETCH_ASSOC);
2881
		if ($row['nb'] > 0) return true;
2882
		else return false;
2883
	}
2884
2885
	public static function check_satellite_version($version) {
2886
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'satellite_version' AND value = :version";
2887
		try {
2888
			$Connection = new Connection();
2889
			$sth = $Connection->db->prepare($query);
2890
			$sth->execute(array(':version' => $version));
2891
		} catch(PDOException $e) {
2892
			return "error : ".$e->getMessage();
2893
		}
2894
		$row = $sth->fetch(PDO::FETCH_ASSOC);
2895
		if ($row['nb'] > 0) return true;
2896
		else return false;
2897
	}
2898
2899
2900
	public static function insert_airspace_version($version) {
2901
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2902
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2903
		try {
2904
			$Connection = new Connection();
2905
			$sth = $Connection->db->prepare($query);
2906
			$sth->execute(array(':version' => $version));
2907
		} catch(PDOException $e) {
2908
			return "error : ".$e->getMessage();
2909
		}
2910
	}
2911
	
2912
	public static function insert_geoid_version($version) {
2913
		$query = "DELETE FROM config WHERE name = 'geoid_version';
2914
			INSERT INTO config (name,value) VALUES ('geoid_version',:version);";
2915
		try {
2916
			$Connection = new Connection();
2917
			$sth = $Connection->db->prepare($query);
2918
                        $sth->execute(array(':version' => $version));
2919
                } catch(PDOException $e) {
2920
                        return "error : ".$e->getMessage();
2921
                }
2922
	}
2923
2924
	public static function insert_marine_identity_version($version) {
2925
		$query = "DELETE FROM config WHERE name = 'marine_identity_version';
2926
			INSERT INTO config (name,value) VALUES ('marine_identity_version',:version);";
2927
		try {
2928
			$Connection = new Connection();
2929
			$sth = $Connection->db->prepare($query);
2930
			$sth->execute(array(':version' => $version));
2931
		} catch(PDOException $e) {
2932
			return "error : ".$e->getMessage();
2933
		}
2934
	}
2935
2936
	public static function insert_satellite_version($version) {
2937
		$query = "DELETE FROM config WHERE name = 'satellite_version';
2938
			INSERT INTO config (name,value) VALUES ('satellite_version',:version);";
2939
		try {
2940
			$Connection = new Connection();
2941
			$sth = $Connection->db->prepare($query);
2942
			$sth->execute(array(':version' => $version));
2943
		} catch(PDOException $e) {
2944
			return "error : ".$e->getMessage();
2945
		}
2946
	}
2947
2948
	public static function check_last_notam_update() {
2949
		global $globalDBdriver;
2950
		if ($globalDBdriver == 'mysql') {
2951
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2952
		} else {
2953
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2954
		}
2955
		try {
2956
			$Connection = new Connection();
2957
			$sth = $Connection->db->prepare($query);
2958
                        $sth->execute();
2959
                } catch(PDOException $e) {
2960
                        return "error : ".$e->getMessage();
2961
                }
2962
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2963
                if ($row['nb'] > 0) return false;
2964
                else return true;
2965
	}
2966
2967
	public static function insert_last_notam_update() {
2968
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2969
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2970
		try {
2971
			$Connection = new Connection();
2972
			$sth = $Connection->db->prepare($query);
2973
                        $sth->execute();
2974
                } catch(PDOException $e) {
2975
                        return "error : ".$e->getMessage();
2976
                }
2977
	}
2978
2979
	public static function check_last_airspace_update() {
2980
		global $globalDBdriver;
2981
		if ($globalDBdriver == 'mysql') {
2982
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2983
		} else {
2984
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2985
		}
2986
		try {
2987
			$Connection = new Connection();
2988
			$sth = $Connection->db->prepare($query);
2989
                        $sth->execute();
2990
                } catch(PDOException $e) {
2991
                        return "error : ".$e->getMessage();
2992
                }
2993
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2994
                if ($row['nb'] > 0) return false;
2995
                else return true;
2996
	}
2997
2998
	public static function insert_last_airspace_update() {
2999
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
3000
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
3001
		try {
3002
			$Connection = new Connection();
3003
			$sth = $Connection->db->prepare($query);
3004
                        $sth->execute();
3005
                } catch(PDOException $e) {
3006
                        return "error : ".$e->getMessage();
3007
                }
3008
	}
3009
3010
	public static function check_last_geoid_update() {
3011
		global $globalDBdriver;
3012
		if ($globalDBdriver == 'mysql') {
3013
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3014
		} else {
3015
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3016
		}
3017
		try {
3018
			$Connection = new Connection();
3019
			$sth = $Connection->db->prepare($query);
3020
                        $sth->execute();
3021
                } catch(PDOException $e) {
3022
                        return "error : ".$e->getMessage();
3023
                }
3024
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3025
                if ($row['nb'] > 0) return false;
3026
                else return true;
3027
	}
3028
3029
	public static function insert_last_geoid_update() {
3030
		$query = "DELETE FROM config WHERE name = 'last_update_geoid';
3031
			INSERT INTO config (name,value) VALUES ('last_update_geoid',NOW());";
3032
		try {
3033
			$Connection = new Connection();
3034
			$sth = $Connection->db->prepare($query);
3035
                        $sth->execute();
3036
                } catch(PDOException $e) {
3037
                        return "error : ".$e->getMessage();
3038
                }
3039
	}
3040
3041
	public static function check_last_owner_update() {
3042
		global $globalDBdriver;
3043
		if ($globalDBdriver == 'mysql') {
3044
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3045
		} else {
3046
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3047
		}
3048
		try {
3049
			$Connection = new Connection();
3050
			$sth = $Connection->db->prepare($query);
3051
                        $sth->execute();
3052
                } catch(PDOException $e) {
3053
                        return "error : ".$e->getMessage();
3054
                }
3055
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3056
                if ($row['nb'] > 0) return false;
3057
                else return true;
3058
	}
3059
3060
	public static function insert_last_owner_update() {
3061
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
3062
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
3063
		try {
3064
			$Connection = new Connection();
3065
			$sth = $Connection->db->prepare($query);
3066
                        $sth->execute();
3067
                } catch(PDOException $e) {
3068
                        return "error : ".$e->getMessage();
3069
                }
3070
	}
3071
	public static function check_last_schedules_update() {
3072
		global $globalDBdriver;
3073
		if ($globalDBdriver == 'mysql') {
3074
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3075
		} else {
3076
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3077
		}
3078
		try {
3079
			$Connection = new Connection();
3080
			$sth = $Connection->db->prepare($query);
3081
                        $sth->execute();
3082
                } catch(PDOException $e) {
3083
                        return "error : ".$e->getMessage();
3084
                }
3085
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3086
                if ($row['nb'] > 0) return false;
3087
                else return true;
3088
	}
3089
3090
	public static function insert_last_schedules_update() {
3091
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
3092
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
3093
		try {
3094
			$Connection = new Connection();
3095
			$sth = $Connection->db->prepare($query);
3096
			$sth->execute();
3097
		} catch(PDOException $e) {
3098
			return "error : ".$e->getMessage();
3099
		}
3100
	}
3101
3102
	public static function check_last_tle_update() {
3103
		global $globalDBdriver;
3104
		if ($globalDBdriver == 'mysql') {
3105
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3106
		} else {
3107
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3108
		}
3109
		try {
3110
			$Connection = new Connection();
3111
			$sth = $Connection->db->prepare($query);
3112
			$sth->execute();
3113
		} catch(PDOException $e) {
3114
			return "error : ".$e->getMessage();
3115
		}
3116
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3117
		if ($row['nb'] > 0) return false;
3118
		else return true;
3119
	}
3120
3121
	public static function insert_last_tle_update() {
3122
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
3123
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
3124
		try {
3125
			$Connection = new Connection();
3126
			$sth = $Connection->db->prepare($query);
3127
			$sth->execute();
3128
		} catch(PDOException $e) {
3129
			return "error : ".$e->getMessage();
3130
		}
3131
	}
3132
3133
	public static function check_last_ucsdb_update() {
3134
		global $globalDBdriver;
3135
		if ($globalDBdriver == 'mysql') {
3136
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
3137
		} else {
3138
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 MONTH'";
3139
		}
3140
		try {
3141
			$Connection = new Connection();
3142
			$sth = $Connection->db->prepare($query);
3143
			$sth->execute();
3144
		} catch(PDOException $e) {
3145
			return "error : ".$e->getMessage();
3146
		}
3147
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3148
		if ($row['nb'] > 0) return false;
3149
		else return true;
3150
	}
3151
3152
	public static function insert_last_ucsdb_update() {
3153
		$query = "DELETE FROM config WHERE name = 'last_update_ucsdb';
3154
			INSERT INTO config (name,value) VALUES ('last_update_ucsdb',NOW());";
3155
		try {
3156
			$Connection = new Connection();
3157
			$sth = $Connection->db->prepare($query);
3158
			$sth->execute();
3159
		} catch(PDOException $e) {
3160
			return "error : ".$e->getMessage();
3161
		}
3162
	}
3163
3164
	public static function check_last_celestrak_update() {
3165
		global $globalDBdriver;
3166
		if ($globalDBdriver == 'mysql') {
3167
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3168
		} else {
3169
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3170
		}
3171
		try {
3172
			$Connection = new Connection();
3173
			$sth = $Connection->db->prepare($query);
3174
			$sth->execute();
3175
		} catch(PDOException $e) {
3176
			return "error : ".$e->getMessage();
3177
		}
3178
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3179
		if ($row['nb'] > 0) return false;
3180
		else return true;
3181
	}
3182
3183
	public static function insert_last_celestrak_update() {
3184
		$query = "DELETE FROM config WHERE name = 'last_update_celestrak';
3185
			INSERT INTO config (name,value) VALUES ('last_update_celestrak',NOW());";
3186
		try {
3187
			$Connection = new Connection();
3188
			$sth = $Connection->db->prepare($query);
3189
			$sth->execute();
3190
		} catch(PDOException $e) {
3191
			return "error : ".$e->getMessage();
3192
		}
3193
	}
3194
3195
	public static function check_last_marine_identity_update() {
3196
		global $globalDBdriver;
3197
		if ($globalDBdriver == 'mysql') {
3198
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3199
		} else {
3200
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3201
		}
3202
		try {
3203
			$Connection = new Connection();
3204
			$sth = $Connection->db->prepare($query);
3205
			$sth->execute();
3206
		} catch(PDOException $e) {
3207
			return "error : ".$e->getMessage();
3208
		}
3209
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3210
		if ($row['nb'] > 0) return false;
3211
		else return true;
3212
	}
3213
3214
	public static function check_last_satellite_update() {
3215
		global $globalDBdriver;
3216
		if ($globalDBdriver == 'mysql') {
3217
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
3218
		} else {
3219
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
3220
		}
3221
		try {
3222
			$Connection = new Connection();
3223
			$sth = $Connection->db->prepare($query);
3224
			$sth->execute();
3225
		} catch(PDOException $e) {
3226
			return "error : ".$e->getMessage();
3227
		}
3228
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3229
		if ($row['nb'] > 0) return false;
3230
		else return true;
3231
	}
3232
3233
	public static function insert_last_marine_identity_update() {
3234
		$query = "DELETE FROM config WHERE name = 'last_update_marine_identity';
3235
			INSERT INTO config (name,value) VALUES ('last_update_marine_identity',NOW());";
3236
		try {
3237
			$Connection = new Connection();
3238
			$sth = $Connection->db->prepare($query);
3239
			$sth->execute();
3240
		} catch(PDOException $e) {
3241
			return "error : ".$e->getMessage();
3242
		}
3243
	}
3244
3245
	public static function insert_last_satellite_update() {
3246
		$query = "DELETE FROM config WHERE name = 'last_update_satellite';
3247
			INSERT INTO config (name,value) VALUES ('last_update_satellite',NOW());";
3248
		try {
3249
			$Connection = new Connection();
3250
			$sth = $Connection->db->prepare($query);
3251
			$sth->execute();
3252
		} catch(PDOException $e) {
3253
			return "error : ".$e->getMessage();
3254
		}
3255
	}
3256
3257
	public static function delete_duplicatemodes() {
3258
		global $globalDBdriver;
3259
		if ($globalDBdriver == 'mysql') {
3260
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
3261
		} else {
3262
			$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'";
3263
		}
3264
		try {
3265
			$Connection = new Connection();
3266
			$sth = $Connection->db->prepare($query);
3267
                        $sth->execute();
3268
                } catch(PDOException $e) {
3269
                        return "error : ".$e->getMessage();
3270
                }
3271
	}
3272
	public static function delete_duplicateowner() {
3273
		global $globalDBdriver;
3274
		if ($globalDBdriver == 'mysql') {
3275
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
3276
		} else {
3277
			$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)";
3278
		}
3279
		try {
3280
			$Connection = new Connection();
3281
			$sth = $Connection->db->prepare($query);
3282
                        $sth->execute();
3283
                } catch(PDOException $e) {
3284
                        return "error : ".$e->getMessage();
3285
                }
3286
	}
3287
	
3288
	public static function update_all() {
3289
		global $globalMasterServer, $globalMasterSource;
3290
		if (!isset($globalMasterServer) || !$globalMasterServer) {
3291
			if (isset($globalMasterSource) && $globalMasterSource) {
3292
				echo update_db::update_routes();
3293
				echo update_db::update_translation();
3294
				//echo update_db::update_notam_fam();
3295
				echo update_db::update_ModeS();
3296
				//echo update_db::update_ModeS_flarm();
3297
				echo update_db::update_ModeS_ogn();
3298
				echo update_db::update_ModeS_faa();
3299
				echo update_db::fix_icaotype();
3300
				echo update_db::update_banned_fam();
3301
				echo update_db::update_celestrak();
3302
				//echo update_db::delete_duplicatemodes();
3303
			} else {
3304
				//echo update_db::update_routes();
3305
				echo update_db::update_routes_fam();
3306
				echo update_db::update_translation();
3307
				echo update_db::update_translation_fam();
3308
				//echo update_db::update_notam_fam();
3309
				//echo update_db::update_ModeS();
3310
				echo update_db::update_ModeS_fam();
3311
				//echo update_db::update_ModeS_flarm();
3312
				echo update_db::update_ModeS_ogn();
3313
				//echo update_db::delete_duplicatemodes();
3314
				echo update_db::update_banned_fam();
3315
			}
3316
		}
3317
	}
3318
}
3319
3320
//echo update_db::update_airports();
3321
//echo update_db::translation();
3322
//echo update_db::update_waypoints();
3323
//echo update_db::update_airspace();
3324
//echo update_db::update_notam();
3325
//echo update_db::update_ivao();
3326
//echo update_db::update_ModeS_flarm();
3327
//echo update_db::update_ModeS_ogn();
3328
//echo update_db::update_aircraft();
3329
//$update_db = new update_db();
3330
//echo update_db::update_owner();
3331
//update_db::update_translation_fam();
3332
//echo update_db::update_routes();
3333
//update_db::update_models();
3334
//echo $update_db::update_skyteam();
3335
//echo $update_db::update_tle();
3336
//echo update_db::update_notam_fam();
3337
//echo update_db::create_airspace();
3338
//echo update_db::update_ModeS();
3339
//echo update_db::update_ModeS_fam();
3340
//echo update_db::update_routes_fam();
3341
//echo update_db::update_ModeS_faa();
3342
//echo update_db::update_banned_fam();
3343
//echo update_db::modes_faa();
3344
//echo update_db::update_owner_fam();
3345
//echo update_db::delete_duplicateowner();
3346
//echo update_db::fix_icaotype();
3347
//echo update_db::satellite_ucsdb('tmp/UCS_Satellite_Database_officialname_1-1-17.txt');
3348
//echo update_db::satellite_celestrak('tmp/satcat.txt');
3349
?>
3350