Completed
Push — master ( 5e2e76...e76a64 )
by Yannick
32:07
created

update_db::check()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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