Completed
Push — master ( eac4f3...3eb940 )
by Yannick
33:30
created

update_db::diagrams_fam()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 4
nop 0
dl 0
loc 25
rs 8.5806
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
		global $globalDebug;
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
	public static function diagrams_fam() {
1031
		global $tmp_dir, $globalTransaction;
1032
		$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...
1033
		$delimiter = " ";
1034
		$Connection = new Connection();
1035
		if (($handle = fopen($tmp_dir.'diagramspdf', 'r')) !== FALSE)
1036
		{
1037
			$Connection->db->beginTransaction();
1038
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1039
			{
1040
				$query = 'UPDATE airport SET diagram_pdf = :diagrampdf, diagram_png = :diagrampng WHERE icao = :icao';
1041
				$icao = str_replace('.pdf','',$data[2]);
1042
				try {
1043
					$sth = $Connection->db->prepare($query);
1044
					$sth->execute(array(':icao' => $icao,':diagrampdf' => 'https://data.flightairmap.com/data/diagrams/'.$icao.'.pdf',':diagrampng' => 'https://data.flightairmap.com/data/diagrams/'.$icao.'.png'));
1045
				} catch(PDOException $e) {
1046
					echo "error : ".$e->getMessage();
1047
					return "error : ".$e->getMessage();
1048
				}
1049
			}
1050
			fclose($handle);
1051
			$Connection->db->commit();
1052
		}
1053
		return '';
1054
        }
1055
1056
	/*
1057
	* This function use FAA public data.
1058
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
1059
	*/
1060
	public static function modes_faa() {
1061
		global $tmp_dir, $globalTransaction, $globalDebug;
1062
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1063
		try {
1064
			$Connection = new Connection();
1065
			$sth = $Connection->db->prepare($query);
1066
                        $sth->execute(array(':source' => 'website_faa'));
1067
                } catch(PDOException $e) {
1068
                        return "error : ".$e->getMessage();
1069
                }
1070
1071
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1072
		try {
1073
			$Connection = new Connection();
1074
			$sth = $Connection->db->prepare($query);
1075
                        $sth->execute(array(':source' => 'website_faa'));
1076
                } catch(PDOException $e) {
1077
                        return "error : ".$e->getMessage();
1078
                }
1079
1080
		$delimiter = ",";
1081
		$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...
1082
		$Connection = new Connection();
1083
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1084
		{
1085
			$i = 0;
1086
			if ($globalTransaction) $Connection->db->beginTransaction();
1087
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1088
			{
1089
				if ($i > 0) {
1090
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1091
					try {
1092
						$sths = $Connection->db->prepare($query_search);
1093
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1094
					} catch(PDOException $e) {
1095
						return "error s : ".$e->getMessage();
1096
					}
1097
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1098
					if (!empty($result_search)) {
1099
						if ($globalDebug) echo '.';
1100
							//if ($globalDBdriver == 'mysql') {
1101
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1102
							//} else {
1103
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1104
							//}
1105
						try {
1106
							$sthi = $Connection->db->prepare($queryi);
1107
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1108
						} catch(PDOException $e) {
1109
							return "error u : ".$e->getMessage();
1110
						}
1111
					} else {
1112
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1113
						try {
1114
							$sthsm = $Connection->db->prepare($query_search_mfr);
1115
							$sthsm->execute(array(':mfr' => $data[2]));
1116
						} catch(PDOException $e) {
1117
							return "error mfr : ".$e->getMessage();
1118
						}
1119
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1120
						if (!empty($result_search_mfr)) {
1121
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1122
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1123
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1124
							try {
1125
								$sthf = $Connection->db->prepare($queryf);
1126
								$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'));
1127
							} catch(PDOException $e) {
1128
								return "error f : ".$e->getMessage();
1129
							}
1130
						}
1131
					}
1132
					if (strtotime($data[29]) > time()) {
1133
						if ($globalDebug) echo 'i';
1134
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1135
						try {
1136
							$sth = $Connection->db->prepare($query);
1137
							$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'));
1138
						} catch(PDOException $e) {
1139
							return "error i : ".$e->getMessage();
1140
						}
1141
					}
1142
				}
1143
				if ($i % 90 == 0) {
1144
					if ($globalTransaction) $Connection->db->commit();
1145
					if ($globalTransaction) $Connection->db->beginTransaction();
1146
				}
1147
				$i++;
1148
			}
1149
			fclose($handle);
1150
			if ($globalTransaction) $Connection->db->commit();
1151
		}
1152
		return '';
1153
	}
1154
1155
	public static function modes_fam() {
1156
		global $tmp_dir, $globalTransaction;
1157
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1158
		try {
1159
			$Connection = new Connection();
1160
			$sth = $Connection->db->prepare($query);
1161
			$sth->execute(array(':source' => 'website_fam'));
1162
		} catch(PDOException $e) {
1163
			return "error : ".$e->getMessage();
1164
		}
1165
		$delimiter = "\t";
1166
		$Connection = new Connection();
1167
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1168
		{
1169
			$i = 0;
1170
			if ($globalTransaction) $Connection->db->beginTransaction();
1171
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1172
			{
1173
				if ($i > 0) {
1174
					if ($data[1] == 'NULL') $data[1] = $data[0];
1175
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1176
					try {
1177
						$sth = $Connection->db->prepare($query);
1178
						$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'));
1179
					} catch(PDOException $e) {
1180
						return "error : ".$e->getMessage();
1181
					}
1182
				}
1183
				$i++;
1184
			}
1185
			fclose($handle);
1186
			if ($globalTransaction) $Connection->db->commit();
1187
		}
1188
		return '';
1189
	}
1190
1191
	public static function airlines_fam() {
1192
		global $tmp_dir, $globalTransaction, $globalDBdriver;
1193
		$Connection = new Connection();
1194
		/*
1195
		if ($globalDBdriver == 'mysql') {
1196
			$query = "LOCK TABLE airlines WRITE";
1197
		} else {
1198
			$query = "LOCK TABLE airlines IN ACCESS EXCLUSIVE WORK";
1199
		}
1200
		try {
1201
			$sth = $Connection->db->prepare($query);
1202
			$sth->execute();
1203
		} catch(PDOException $e) {
1204
			return "error : ".$e->getMessage();
1205
		}
1206
		*/
1207
		$query = "DELETE FROM airlines WHERE forsource IS NULL";
1208
		try {
1209
			$sth = $Connection->db->prepare($query);
1210
			$sth->execute();
1211
		} catch(PDOException $e) {
1212
			return "error : ".$e->getMessage();
1213
		}
1214
		$delimiter = "\t";
1215
		if (($handle = fopen($tmp_dir.'airlines.tsv', 'r')) !== FALSE)
1216
		{
1217
			$i = 0;
1218
			if ($globalTransaction) $Connection->db->beginTransaction();
1219
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1220
			{
1221
				if ($i > 0) {
1222
					if ($data[1] == 'NULL') $data[1] = $data[0];
1223
					$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)';
1224
					try {
1225
						$sth = $Connection->db->prepare($query);
1226
						$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]));
1227
					} catch(PDOException $e) {
1228
						return "error : ".$e->getMessage();
1229
					}
1230
				}
1231
				$i++;
1232
			}
1233
			fclose($handle);
1234
			if ($globalTransaction) $Connection->db->commit();
1235
		}
1236
		/*
1237
		$query = "UNLOCK TABLES";
1238
		try {
1239
			$sth = $Connection->db->prepare($query);
1240
			$sth->execute();
1241
		} catch(PDOException $e) {
1242
			return "error : ".$e->getMessage();
1243
		}
1244
		*/
1245
		return '';
1246
        }
1247
        
1248
	public static function owner_fam() {
1249
		global $tmp_dir, $globalTransaction;
1250
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1251
		try {
1252
			$Connection = new Connection();
1253
			$sth = $Connection->db->prepare($query);
1254
                        $sth->execute(array(':source' => 'website_fam'));
1255
                } catch(PDOException $e) {
1256
                        return "error : ".$e->getMessage();
1257
                }
1258
1259
		$delimiter = "\t";
1260
		$Connection = new Connection();
1261
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1262
		{
1263
			$i = 0;
1264
			if ($globalTransaction) $Connection->db->beginTransaction();
1265
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1266
			{
1267
				if ($i > 0) {
1268
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1269
					try {
1270
						$sth = $Connection->db->prepare($query);
1271
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1272
					} catch(PDOException $e) {
1273
						//print_r($data);
1274
						return "error : ".$e->getMessage();
1275
					}
1276
				}
1277
				$i++;
1278
			}
1279
			fclose($handle);
1280
			if ($globalTransaction) $Connection->db->commit();
1281
		}
1282
		return '';
1283
        }
1284
1285
	public static function routes_fam() {
1286
		global $tmp_dir, $globalTransaction, $globalDebug;
1287
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1288
		try {
1289
			$Connection = new Connection();
1290
			$sth = $Connection->db->prepare($query);
1291
			$sth->execute(array(':source' => 'website_fam'));
1292
		} catch(PDOException $e) {
1293
			return "error : ".$e->getMessage();
1294
		}
1295
		$delimiter = "\t";
1296
		$Connection = new Connection();
1297
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1298
		{
1299
			$i = 0;
1300
			if ($globalTransaction) $Connection->db->beginTransaction();
1301
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1302
			{
1303
				if ($i > 0) {
1304
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1305
					$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)';
1306
					try {
1307
						$sth = $Connection->db->prepare($query);
1308
						$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'));
1309
					} catch(PDOException $e) {
1310
						if ($globalDebug) echo "error: ".$e->getMessage()." - data: ".implode(',',$data);
1311
						die();
1312
					}
1313
				}
1314
				if ($globalTransaction && $i % 2000 == 0) {
1315
					$Connection->db->commit();
1316
					if ($globalDebug) echo '.';
1317
					$Connection->db->beginTransaction();
1318
				}
1319
				$i++;
1320
			}
1321
			fclose($handle);
1322
			if ($globalTransaction) $Connection->db->commit();
1323
		}
1324
		return '';
1325
	}
1326
1327
	public static function block_fam() {
1328
		global $tmp_dir, $globalTransaction, $globalDebug;
1329
		$query = "DELETE FROM aircraft_block WHERE Source = '' OR Source = :source";
1330
		try {
1331
			$Connection = new Connection();
1332
			$sth = $Connection->db->prepare($query);
1333
			$sth->execute(array(':source' => 'website_fam'));
1334
		} catch(PDOException $e) {
1335
			return "error : ".$e->getMessage();
1336
		}
1337
		$Connection = new Connection();
1338
		if (($handle = fopen($tmp_dir.'block.tsv', 'r')) !== FALSE)
1339
		{
1340
			$i = 0;
1341
			if ($globalTransaction) $Connection->db->beginTransaction();
1342
			while (($data = fgets($handle, 1000)) !== FALSE)
1343
			{
1344
				$query = 'INSERT INTO aircraft_block (callSign,Source) VALUES (:callSign,:source)';
1345
				try {
1346
					$sth = $Connection->db->prepare($query);
1347
					$sth->execute(array(':callSign' => trim($data),':source' => 'website_fam'));
1348
				} catch(PDOException $e) {
1349
					if ($globalDebug) echo "error: ".$e->getMessage()." - data: ".$data;
1350
					die();
1351
				}
1352
				if ($globalTransaction && $i % 2000 == 0) {
1353
					$Connection->db->commit();
1354
					if ($globalDebug) echo '.';
1355
					$Connection->db->beginTransaction();
1356
				}
1357
				$i++;
1358
			}
1359
			fclose($handle);
1360
			if ($globalTransaction) $Connection->db->commit();
1361
		}
1362
		return '';
1363
        }
1364
1365
	public static function marine_identity_fam() {
1366
		global $tmp_dir, $globalTransaction;
1367
		$query = "TRUNCATE TABLE marine_identity";
1368
		try {
1369
			$Connection = new Connection();
1370
			$sth = $Connection->db->prepare($query);
1371
                        $sth->execute();
1372
                } catch(PDOException $e) {
1373
                        return "error : ".$e->getMessage();
1374
                }
1375
1376
		
1377
		//update_db::unzip($out_file);
1378
		$delimiter = "\t";
1379
		$Connection = new Connection();
1380
		if (($handle = fopen($tmp_dir.'marine_identity.tsv', 'r')) !== FALSE)
1381
		{
1382
			$i = 0;
1383
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1384
			//$Connection->db->beginTransaction();
1385
			if ($globalTransaction) $Connection->db->beginTransaction();
1386
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1387
			{
1388
				if ($i > 0) {
1389
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1390
					$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)';
1391
					try {
1392
						$sth = $Connection->db->prepare($query);
1393
						$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]));
1394
					} catch(PDOException $e) {
1395
						return "error : ".$e->getMessage();
1396
					}
1397
				}
1398
				$i++;
1399
			}
1400
			fclose($handle);
1401
			if ($globalTransaction) $Connection->db->commit();
1402
		}
1403
		return '';
1404
        }
1405
1406
	public static function satellite_fam() {
1407
		global $tmp_dir, $globalTransaction;
1408
		$query = "TRUNCATE TABLE satellite";
1409
		try {
1410
			$Connection = new Connection();
1411
			$sth = $Connection->db->prepare($query);
1412
			$sth->execute();
1413
		} catch(PDOException $e) {
1414
			return "error : ".$e->getMessage();
1415
		}
1416
		$delimiter = "\t";
1417
		$Connection = new Connection();
1418
		if (($handle = fopen($tmp_dir.'satellite.tsv', 'r')) !== FALSE)
1419
		{
1420
			$i = 0;
1421
			if ($globalTransaction) $Connection->db->beginTransaction();
1422
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1423
			{
1424
				if ($i > 0) {
1425
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1426
					$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) 
1427
					    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)';
1428
					try {
1429
						$sth = $Connection->db->prepare($query);
1430
						$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]));
1431
					} catch(PDOException $e) {
1432
						return "error : ".$e->getMessage();
1433
					}
1434
				}
1435
				$i++;
1436
			}
1437
			fclose($handle);
1438
			if ($globalTransaction) $Connection->db->commit();
1439
		}
1440
		return '';
1441
	}
1442
1443
	public static function banned_fam() {
1444
		global $tmp_dir, $globalTransaction;
1445
		$query = "UPDATE airlines SET ban_eu = 0";
1446
		try {
1447
			$Connection = new Connection();
1448
			$sth = $Connection->db->prepare($query);
1449
			$sth->execute();
1450
		} catch(PDOException $e) {
1451
			return "error : ".$e->getMessage();
1452
		}
1453
1454
		$Connection = new Connection();
1455
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1456
		{
1457
			if ($globalTransaction) $Connection->db->beginTransaction();
1458
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1459
			{
1460
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1461
				if ($data[0] != '') {
1462
					$icao = $data[0];
1463
					try {
1464
						$sth = $Connection->db->prepare($query);
1465
						$sth->execute(array(':icao' => $icao));
1466
					} catch(PDOException $e) {
1467
						return "error : ".$e->getMessage();
1468
					}
1469
				}
1470
			}
1471
			fclose($handle);
1472
			if ($globalTransaction) $Connection->db->commit();
1473
		}
1474
		return '';
1475
        }
1476
1477
	public static function tle($filename,$tletype) {
1478
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1479
		global $tmp_dir, $globalTransaction;
1480
		//$Spotter = new Spotter();
1481
		
1482
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1483
		try {
1484
			$Connection = new Connection();
1485
			$sth = $Connection->db->prepare($query);
1486
                        $sth->execute(array(':source' => $filename));
1487
                } catch(PDOException $e) {
1488
                        return "error : ".$e->getMessage();
1489
                }
1490
		
1491
		$Connection = new Connection();
1492
		if (($handle = fopen($filename, 'r')) !== FALSE)
1493
		{
1494
			$i = 0;
1495
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1496
			//$Connection->db->beginTransaction();
1497
			$dbdata = array();
1498
			while (($data = fgets($handle, 1000)) !== FALSE)
1499
			{
1500
				if ($i == 0) {
1501
					$dbdata['name'] = trim($data);
1502
					$i++;
1503
				} elseif ($i == 1) {
1504
					$dbdata['tle1'] = trim($data);
1505
					$i++;
1506
				} elseif ($i == 2) {
1507
					$dbdata['tle2'] = trim($data);
1508
					//print_r($dbdata);
1509
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1510
					try {
1511
						$sth = $Connection->db->prepare($query);
1512
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1513
					} catch(PDOException $e) {
1514
						return "error : ".$e->getMessage();
1515
					}
1516
1517
					$i = 0;
1518
				}
1519
			}
1520
			fclose($handle);
1521
			//$Connection->db->commit();
1522
		}
1523
		return '';
1524
        }
1525
1526
	public static function satellite_ucsdb($filename) {
1527
		global $tmp_dir, $globalTransaction;
1528
		
1529
		$query = "DELETE FROM satellite";
1530
		try {
1531
			$Connection = new Connection();
1532
			$sth = $Connection->db->prepare($query);
1533
			$sth->execute(array(':source' => $filename));
1534
		} catch(PDOException $e) {
1535
			return "error : ".$e->getMessage();
1536
		}
1537
		
1538
		
1539
		$Connection = new Connection();
1540
		if (($handle = fopen($filename, 'r')) !== FALSE)
1541
		{
1542
			$i = 0;
1543
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1544
			//$Connection->db->beginTransaction();
1545
			while (($data = fgetcsv($handle, 1000,"\t")) !== FALSE)
1546
			{
1547
				if ($i > 0 && $data[0] != '') {
1548
					$sources = trim($data[28].' '.$data[29].' '.$data[30].' '.$data[31].' '.$data[32].' '.$data[33]);
1549
					$period = str_replace(',','',$data[14]);
1550
					if (!empty($period) && strpos($period,'days')) $period = str_replace(' days','',$period)*24*60;
1551
					if ($data[18] != '') $launch_date = date('Y-m-d',strtotime($data[18]));
1552
					else $launch_date = NULL;
1553
					$data = array_map(function($value) {
1554
						return trim($value) === '' ? null : $value;
1555
					}, $data);
1556
					//print_r($data);
1557
					$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) 
1558
					    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)';
1559
					try {
1560
						$sth = $Connection->db->prepare($query);
1561
						$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));
1562
					} catch(PDOException $e) {
1563
						return "error : ".$e->getMessage();
1564
					}
1565
				}
1566
				$i++;
1567
			}
1568
			fclose($handle);
1569
			//$Connection->db->commit();
1570
		}
1571
		return '';
1572
	}
1573
1574
	public static function satellite_celestrak($filename) {
1575
		global $tmp_dir, $globalTransaction, $globalDebug;
1576
		$satcat_sources = array(
1577
			'AB' => array('country' => 'Multinational', 'owner' => 'Arab Satellite Communications Org. (ASCO)'),
1578
			'ABS' => array('country' => 'Multinational', 'owner' => 'Asia Broadcast Satellite Ltd.'),
1579
			'AC' => array('country' => 'China', 'owner' => 'Asia Satellite Telecommunications Co. Ltd.'),
1580
			'ALG' => array('country' => 'Algeria', 'owner' => ''),
1581
			'ARGN' => array('country' => 'Argentina', 'owner' => ''),
1582
			'ASRA' => array('country' => 'Austria', 'owner' => ''),
1583
			'AUS' => array('country' => 'Australia', 'owner' => ''),
1584
			'AZER' => array('country' => 'Azerbaijan', 'owner' => ''),
1585
			'BEL' => array('country' => 'Belgium', 'owner' => ''),
1586
			'BELA' => array('country' => 'Belarus', 'owner' => ''),
1587
			'BERM' => array('country' => 'Bermuda', 'owner' => ''),
1588
			'BOL' => array('country' => 'Bolivia', 'owner' => ''),
1589
			'BUL' => array('country' => 'Bulgaria', 'owner' => ''),
1590
			'BRAZ' => array('country' => 'Brazil', 'owner' => ''),
1591
			'CA' => array('country' => 'Canada', 'owner' => ''),
1592
			'CHBZ' => array('country' => 'China/Brazil', 'owner' => ''),
1593
			'CHLE' => array('country' => 'Chile', 'owner' => ''),
1594
			'CIS' => array('country' => 'Russia', 'owner' => ''),
1595
			'COL' => array('country' => 'Colombia', 'owner' => ''),
1596
			'CZCH' => array('country' => 'Czech Republic (former Czechoslovakia)', 'owner' => ''),
1597
			'DEN' => array('country' => 'Denmark', 'owner' => ''),
1598
			'ECU' => array('country' => 'Ecuador', 'owner' => ''),
1599
			'EGYP' => array('country' => 'Egypt', 'owner' => ''),
1600
			'ESA' => array('country' => 'Multinational', 'owner' => 'European Space Agency'),
1601
			'ESRO' => array('country' => 'Multinational', 'owner' => 'European Space Research Organization'),
1602
			'EST' => array('country' => 'Estonia','owner' => ''),
1603
			'EUME' => array('country' => 'Multinational', 'owner' => 'EUMETSAT (European Organization for the Exploitation of Meteorological Satellites)'),
1604
			'EUTE' => array('country' => 'Multinational', 'owner' => 'European Telecommunications Satellite Consortium (EUTELSAT)'),
1605
			'FGER' => array('country' => 'France/Germany', 'owner' => ''),
1606
			'FIN' => array('country' => 'Finland', 'owner' => ''),
1607
			'FR' => array('country' => 'France', 'owner' => ''),
1608
			'FRIT' => array('country' => 'France/Italy', 'owner' => ''),
1609
			'GER' => array('country' => 'Germany', 'owner' => ''),
1610
			'GLOB' => array('country' => 'USA', 'owner' => 'Globalstar'),
1611
			'GREC' => array('country' => 'Greece', 'owner' => ''),
1612
			'HUN' => array('country' => 'Hungary', 'owner' => ''),
1613
			'IM' => array('country' => 'United Kingdom', 'owner' => 'INMARSAT, Ltd.'),
1614
			'IND' => array('country' => 'India', 'owner' => ''),
1615
			'INDO' => array('country' => 'Indonesia', 'owner' => ''),
1616
			'IRAN' => array('country' => 'Iran', 'owner' => ''),
1617
			'IRAQ' => array('country' => 'Iraq', 'owner' => ''),
1618
			'IRID' => array('country' => 'USA', 'owner' => 'Iridium Satellite LLC'),
1619
			'ISRA' => array('country' => 'Israel', 'owner' => ''),
1620
			'ISRO' => array('country' => 'India', 'owner' => 'Indian Space Research Organisation (ISRO)'),
1621
			'ISS' => array('country' => 'Multinational', 'owner' => 'NASA/Multinational'),
1622
			'IT' => array('country' => 'Italy', 'owner' => ''),
1623
			'ITSO' => array('country' => 'USA', 'owner' => 'Intelsat, S.A.'),
1624
			'JPN' => array('country' => 'Japan', 'owner' => ''),
1625
			'KAZ' => array('country' => 'Kazakhstan', 'owner' => ''),
1626
			'LAOS' => array('country' => 'Laos', 'owner' => ''),
1627
			'LTU' => array('country' => 'Lithuania', 'owner' => ''),
1628
			'LUXE' => array('country' => 'Luxembourg', 'owner' => ''),
1629
			'MALA' => array('country' => 'Malaysia', 'owner' => ''),
1630
			'MEX' => array('country' => 'Mexico', 'owner' => ''),
1631
			'NATO' => array('country' => 'Multinational', 'owner' => 'North Atlantic Treaty Organization'),
1632
			'NETH' => array('country' => 'Netherlands', 'owner' => ''),
1633
			'NICO' => array('country' => 'USA', 'owner' => 'New ICO'),
1634
			'NIG' => array('country' => 'Nigeria', 'owner' => ''),
1635
			'NKOR' => array('country' => 'North Korea', 'owner' => ''),
1636
			'NOR' => array('country' => 'Norway', 'owner' => ''),
1637
			'O3B' => array('country' => 'United Kingdom', 'owner' => 'O3b Networks Ltd.'),
1638
			'ORB' => array('country' => 'USA', 'owner' => 'ORBCOMM Inc.'),
1639
			'PAKI' => array('country' => 'Pakistan', 'owner' => ''),
1640
			'PERU' => array('country' => 'Peru', 'owner' => ''),
1641
			'POL' => array('country' => 'Poland', 'owner' => ''),
1642
			'POR' => array('country' => 'Portugal', 'owner' => ''),
1643
			'PRC' => array('country' => 'China', 'owner' => ''),
1644
			'PRES' => array('country' => 'Multinational', 'owner' => 'China/ESA'),
1645
			'RASC' => array('country' => 'Multinational', 'owner' => 'Regional African Satellite Communications Organisation (RASCOM)'),
1646
			'ROC' => array('country' => 'Taiwan', 'owner' => ''),
1647
			'ROM' => array('country' => 'Romania', 'owner' => ''),
1648
			'RP' => array('country' => 'Philippines', 'owner' => ''),
1649
			'SAFR' => array('country' => 'South Africa', 'owner' => ''),
1650
			'SAUD' => array('country' => 'Saudi Arabia', 'owner' => ''),
1651
			'SEAL' => array('country' => 'USA', 'owner' => ''),
1652
			'SES' => array('country' => 'Multinational', 'owner' => 'SES World Skies'),
1653
			'SING' => array('country' => 'Singapore', 'owner' => ''),
1654
			'SKOR' => array('country' => 'South Korea', 'owner' => ''),
1655
			'SPN' => array('country' => 'Spain', 'owner' => ''),
1656
			'STCT' => array('country' => 'Singapore/Taiwan', 'owner' => ''),
1657
			'SWED' => array('country' => 'Sweden', 'owner' => ''),
1658
			'SWTZ' => array('country' => 'Switzerland', 'owner' => ''),
1659
			'THAI' => array('country' => 'Thailand', 'owner' => ''),
1660
			'TMMC' => array('country' => 'Turkmenistan/Monaco', 'owner' => ''),
1661
			'TURK' => array('country' => 'Turkey', 'owner' => ''),
1662
			'UAE' => array('country' => 'United Arab Emirates', 'owner' => ''),
1663
			'UK' => array('country' => 'United Kingdom', 'owner' => ''),
1664
			'UKR' => array('country' => 'Ukraine', 'owner' => ''),
1665
			'URY' => array('country' => 'Uruguay', 'owner' => ''),
1666
			'US' => array('country' => 'USA', 'owner' => ''),
1667
			'USBZ' => array('country' => 'USA/Brazil', 'owner' => ''),
1668
			'VENZ' => array('country' => 'Venezuela', 'owner' => ''),
1669
			'VTNM' => array('country' => 'Vietnam', 'owner' => '')
1670
		);
1671
		$satcat_launch_site = array(
1672
			'AFETR' => 'Cape Canaveral',
1673
			'AFWTR' => 'Vandenberg AFB',
1674
			'CAS' => 'Canaries Airspace',
1675
			'DLS' => 'Dombarovsky Air Base',
1676
			'ERAS' => 'Eastern Range Airspace',
1677
			'FRGUI' => 'Guiana Space Center',
1678
			'HGSTR' => 'Hammaguira Space Track Range, Algeria',
1679
			'JSC' => 'Jiuquan Satellite Launch Center',
1680
			'KODAK' => 'Kodiak Launch Complex',
1681
			'KSCUT' => 'Uchinoura Space Center',
1682
			'KWAJ' => 'Kwajalein Island',
1683
			'KYMSC' => 'Kapustin Yar Missile and Space Complex, Russia',
1684
			'NSC' => 'Naro Space Center',
1685
			'PLMSC' => 'Plesetsk Cosmodrome',
1686
			'SEAL' => 'Sea Launch',
1687
			'SEMLS' => 'Semnan Satellite Launch Site, Iran',
1688
			'SNMLP' => 'San Marco Launch Platform, Indian Ocean (Kenya)',
1689
			'SRILR' => 'Satish Dhawan Space Center',
1690
			'SUBL' => 'Submarine Launch Platform (mobile), Russia',
1691
			'SVOBO' => 'Svobodny Cosmodrome',
1692
			'TAISC' => 'Taiyuan Launch Center',
1693
			'TANSC' => 'Tanegashima Space Center',
1694
			'TYMSC' => 'Baikonur Cosmodrome',
1695
			'VOSTO' => 'Vostochny Cosmodrome',
1696
			'WLPIS' => 'Wallops Island Flight Facility',
1697
			'WOMRA' => 'Woomera, Australia',
1698
			'WRAS' => 'Western Range Airspace',
1699
			'WSC' => 'Wenchang Satellite Launch Center',
1700
			'XICLF' => 'Xichang Satellite Launch Center',
1701
			'YAVNE' => 'Palmachim Launch Complex',
1702
			'YUN' => 'Yunsong Launch Site'
1703
		);
1704
1705
		/*
1706
		$query = "DELETE FROM satellite";
1707
		try {
1708
			$Connection = new Connection();
1709
			$sth = $Connection->db->prepare($query);
1710
			$sth->execute(array(':source' => $filename));
1711
		} catch(PDOException $e) {
1712
			return "error : ".$e->getMessage();
1713
		}
1714
		*/
1715
		
1716
		$Connection = new Connection();
1717
		if (($handle = fopen($filename, 'r')) !== FALSE)
1718
		{
1719
			$i = 0;
1720
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1721
			//$Connection->db->beginTransaction();
1722
			while (($data = fgets($handle, 1000)) !== FALSE)
1723
			{
1724
				if ($data != '') {
1725
				$result = array();
1726
				$result['cospar'] = trim(substr($data,0,11));
1727
				$result['norad'] = trim(substr($data,13,6));
1728
				$result['operational'] = trim(substr($data,21,1));
1729
				$result['name'] = trim(substr($data,23,24));
1730
				/*
1731
				    * R/B(1) = Rocket body, first stage
1732
				    * R/B(2) = Rocket body, second stage
1733
				    * DEB = Debris
1734
				    * PLAT = Platform
1735
				    * Items in parentheses are alternate names
1736
				    * Items in brackets indicate type of object
1737
				    (e.g., BREEZE-M DEB [TANK] = tank)
1738
				    * An ampersand (&) indicates two or more objects are attached
1739
				*/
1740
				
1741
				$owner_code = trim(substr($data,49,5));
1742
				
1743
				if (!isset($satcat_sources[$owner_code]) && $satcat_sources[$owner_code] != 'TBD') {
1744
					if ($globalDebug) echo $data.'owner_code: '.$owner_code."\n";
1745
				}
1746
				if (!isset($satcat_launch_site[trim(substr($data,68,5))])) {
1747
					if ($globalDebug) echo 'launch_site_code: '.trim(substr($data,68,5))."\n";
1748
				}
1749
				
1750
				if ($owner_code != 'TBD' && isset($satcat_sources[$owner_code]) && isset($satcat_launch_site[trim(substr($data,68,5))])) {
1751
					$result['country_owner'] = $satcat_sources[$owner_code]['country'];
1752
					$result['owner'] = $satcat_sources[$owner_code]['owner'];
1753
					$result['launch_date'] = trim(substr($data,56,10));
1754
					$launch_site_code = trim(substr($data,68,5));
1755
					$result['launch_site'] = $satcat_launch_site[$launch_site_code];
1756
					$result['lifetime'] = trim(substr($data,75,10));
1757
					$result['period'] = trim(substr($data,87,7));
1758
					$result['inclination'] = trim(substr($data,96,5));
1759
					$result['apogee'] = trim(substr($data,103,6));
1760
					$result['perigee'] = trim(substr($data,111,6));
1761
					//$result['radarcross'] = trim(substr($data,119,8));
1762
					$result['status'] = trim(substr($data,129,3));
1763
					//print_r($result);
1764
					$result = array_map(function($value) {
1765
						return trim($value) === '' ? null : $value;
1766
					}, $result);
1767
					//print_r($data);
1768
					if ($result['operational'] != 'D') {
1769
						$query = "SELECT * FROM satellite WHERE cospar = :cospar LIMIT 1";
1770
						try {
1771
							$Connection = new Connection();
1772
							$sth = $Connection->db->prepare($query);
1773
							$sth->execute(array(':cospar' => $result['cospar']));
1774
							$exist = $sth->fetchAll(PDO::FETCH_ASSOC);
1775
						} catch(PDOException $e) {
1776
							return "error : ".$e->getMessage();
1777
						}
1778
						if (empty($exist)) {
1779
							$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) 
1780
							    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)';
1781
							try {
1782
								$sth = $Connection->db->prepare($query);
1783
								$sth->execute(array(
1784
								    ':name' => $result['name'], ':name_alternate' => '', ':country_un' => '', ':country_owner' => $result['country_owner'], ':owner' => $result['owner'], ':users' => '', ':purpose' => '', ':purpose_detailed' => '', ':orbit' => $result['status'],
1785
								    ':type' => '', ':longitude_geo' => NULL, ':perigee' => !empty($result['perigee']) ? $result['perigee'] : NULL, ':apogee' => !empty($result['apogee']) ? $result['apogee'] : NULL, ':eccentricity' => NULL, ':inclination' => $result['inclination'],
1786
								    ':period' => !empty($result['period']) ? $result['period'] : NULL, ':launch_mass' => NULL, ':dry_mass' => NULL, ':power' => NULL, ':launch_date' => $result['launch_date'], ':lifetime' => $result['lifetime'], 
1787
								    ':contractor' => '',':country_contractor' => '', ':launch_site' => $result['launch_site'], ':launch_vehicule' => '', ':cospar' => $result['cospar'], ':norad' => $result['norad'], ':comments' => '', ':source_orbital' => '', ':sources' => ''
1788
								    )
1789
								);
1790
							} catch(PDOException $e) {
1791
								return "error : ".$e->getMessage();
1792
							}
1793
						} elseif ($exist[0]['name'] != $result['name'] && $exist[0]['name_alternate'] != $result['name']) {
1794
							$query = "UPDATE satellite SET name_alternate = :name_alternate WHERE cospar = :cospar";
1795
							try {
1796
								$Connection = new Connection();
1797
								$sth = $Connection->db->prepare($query);
1798
								$sth->execute(array(':name_alternate' => $result['name'],':cospar' => $result['cospar']));
1799
							} catch(PDOException $e) {
1800
								return "error : ".$e->getMessage();
1801
							}
1802
						}
1803
					}
1804
				}
1805
				}
1806
				$i++;
1807
			}
1808
			fclose($handle);
1809
			//$Connection->db->commit();
1810
		}
1811
		return '';
1812
        }
1813
1814
	/**
1815
        * Convert a HTML table to an array
1816
        * @param String $data HTML page
1817
        * @return Array array of the tables in HTML page
1818
        */
1819
/*
1820
        private static function table2array($data) {
1821
                $html = str_get_html($data);
1822
                $tabledata=array();
1823
                foreach($html->find('tr') as $element)
1824
                {
1825
                        $td = array();
1826
                        foreach( $element->find('th') as $row)
1827
                        {
1828
                                $td [] = trim($row->plaintext);
1829
                        }
1830
                        $td=array_filter($td);
1831
                        $tabledata[] = $td;
1832
1833
                        $td = array();
1834
                        $tdi = array();
1835
                        foreach( $element->find('td') as $row)
1836
                        {
1837
                                $td [] = trim($row->plaintext);
1838
                                $tdi [] = trim($row->innertext);
1839
                        }
1840
                        $td=array_filter($td);
1841
                        $tdi=array_filter($tdi);
1842
                    //    $tabledata[]=array_merge($td,$tdi);
1843
                        $tabledata[]=$td;
1844
                }
1845
                return(array_filter($tabledata));
1846
        }
1847
*/
1848
       /**
1849
        * Get data from form result
1850
        * @param String $url form URL
1851
        * @return String the result
1852
        */
1853
/*
1854
        private static function getData($url) {
1855
                $ch = curl_init();
1856
                curl_setopt($ch, CURLOPT_URL, $url);
1857
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1858
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1859
                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');
1860
                return curl_exec($ch);
1861
        }
1862
*/
1863
/*
1864
	public static function waypoints() {
1865
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1866
		$table = update_db::table2array($data);
1867
//		print_r($table);
1868
		$query = 'TRUNCATE TABLE waypoints';
1869
		try {
1870
			$Connection = new Connection();
1871
			$sth = $Connection->db->prepare($query);
1872
                        $sth->execute();
1873
                } catch(PDOException $e) {
1874
                        return "error : ".$e->getMessage();
1875
                }
1876
1877
		$query_dest = 'INSERT INTO waypoints (ident,latitude,longitude,control,usage) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1878
		$Connection = new Connection();
1879
		$sth_dest = $Connection->db->prepare($query_dest);
1880
		$Connection->db->beginTransaction();
1881
                foreach ($table as $row) {
1882
            		if ($row[0] != 'Ident') {
1883
				$ident = $row[0];
1884
				$latitude = $row[2];
1885
				$longitude = $row[3];
1886
				$control = $row[4];
1887
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1888
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1889
				try {
1890
					$sth_dest->execute($query_dest_values);
1891
				} catch(PDOException $e) {
1892
					return "error : ".$e->getMessage();
1893
				}
1894
			}
1895
                }
1896
		$Connection->db->commit();
1897
1898
	}
1899
*/
1900
	public static function waypoints($filename) {
1901
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1902
		global $tmp_dir, $globalTransaction;
1903
		//$Spotter = new Spotter();
1904
		//$out_file = $tmp_dir.'translation.zip';
1905
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1906
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1907
		$Connection = new Connection();
1908
		//update_db::unzip($out_file);
1909
		$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...
1910
		$delimiter = ' ';
1911
		if (($handle = fopen($filename, 'r')) !== FALSE)
1912
		{
1913
			$i = 0;
1914
			if ($globalTransaction) $Connection->db->beginTransaction();
1915
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1916
			{
1917
				$i++;
1918
				if($i > 3 && count($row) > 2) {
1919
					$data = array_values(array_filter($row));
1920
					$cntdata = count($data);
1921
					if ($cntdata > 10) {
1922
						$value = $data[9];
1923
						
1924
						for ($i =10;$i < $cntdata;$i++) {
1925
							$value .= ' '.$data[$i];
1926
						}
1927
						$data[9] = $value;
1928
					}
1929
					//print_r($data);
1930
					if (count($data) > 9) {
1931
						$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)';
1932
						try {
1933
							$sth = $Connection->db->prepare($query);
1934
							$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]));
1935
						} catch(PDOException $e) {
1936
							return "error : ".$e->getMessage();
1937
						}
1938
					}
1939
				}
1940
			}
1941
			fclose($handle);
1942
			if ($globalTransaction) $Connection->db->commit();
1943
		}
1944
		return '';
1945
	}
1946
1947
	public static function update_fires() {
1948
		global $tmp_dir, $globalTransaction, $globalDebug;
1949
		require_once(dirname(__FILE__).'/../require/class.Source.php');
1950
		$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...
1951
		$Common = new Common();
1952
		$Common->download('http://firms.modaps.eosdis.nasa.gov/active_fire/viirs/text/VNP14IMGTDL_NRT_Global_24h.csv',$tmp_dir.'fires.csv');
1953
		$Connection = new Connection();
1954
		$Source = new Source();
1955
		$Source->deleteLocationByType('fires');
1956
		$i = 0;
1957
		if (($handle = fopen($tmp_dir.'fires.csv','r')) !== false) {
1958
			if ($globalTransaction) $Connection->db->beginTransaction();
1959
			while (($row = fgetcsv($handle,1000)) !== false) {
1960
				if ($i > 0 && $row[0] != '' && $row[8] != 'low') {
1961
					$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]);
1962
					$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)";
1963
					$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));
1964
					try {
1965
						$sth = $Connection->db->prepare($query);
1966
						$sth->execute($query_values);
1967
					} catch(PDOException $e) {
1968
						echo "error : ".$e->getMessage();
1969
					}
1970
				}
1971
				$i++;
1972
			}
1973
			if ($globalTransaction) $Connection->db->commit();
1974
		}
1975
	}
1976
1977
	public static function ivao_airlines($filename) {
1978
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1979
		global $tmp_dir, $globalTransaction;
1980
		//$query = 'TRUNCATE TABLE airlines';
1981
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1982
		try {
1983
			$Connection = new Connection();
1984
			$sth = $Connection->db->prepare($query);
1985
			$sth->execute();
1986
		} catch(PDOException $e) {
1987
			return "error : ".$e->getMessage();
1988
		}
1989
		$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...
1990
		$delimiter = ':';
1991
		$Connection = new Connection();
1992
		if (($handle = fopen($filename, 'r')) !== FALSE)
1993
		{
1994
			if ($globalTransaction) $Connection->db->beginTransaction();
1995
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1996
			{
1997
				if(count($row) > 1) {
1998
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1999
					try {
2000
						$sth = $Connection->db->prepare($query);
2001
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
2002
					} catch(PDOException $e) {
2003
						return "error : ".$e->getMessage();
2004
					}
2005
				}
2006
			}
2007
			fclose($handle);
2008
			if ($globalTransaction) $Connection->db->commit();
2009
		}
2010
		return '';
2011
        }
2012
	
2013
	public static function update_airspace() {
2014
		global $tmp_dir, $globalDBdriver;
2015
		include_once('class.create_db.php');
2016
		$Connection = new Connection();
2017
		if ($Connection->tableExists('airspace')) {
2018
			$query = 'DROP TABLE airspace';
2019
			try {
2020
				$sth = $Connection->db->prepare($query);
2021
                    		$sth->execute();
2022
	                } catch(PDOException $e) {
2023
				return "error : ".$e->getMessage();
2024
	                }
2025
	        }
2026
2027
2028
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
2029
		else {
2030
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
2031
			$query = "CREATE EXTENSION postgis";
2032
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
2033
			try {
2034
				$sth = $Connection->db->prepare($query);
2035
				$sth->execute();
2036
			} catch(PDOException $e) {
2037
				return "error : ".$e->getMessage();
2038
			}
2039
		}
2040
		$error = create_db::import_file($tmp_dir.'airspace.sql');
2041
		return $error;
2042
	}
2043
2044
	public static function update_notam_fam() {
2045
		global $tmp_dir, $globalDebug;
2046
		include_once('class.create_db.php');
2047
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
2048
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
2049
		update_db::download('http://data.flightairmap.com/data/notam.txt.gz.md5',$tmp_dir.'notam.txt.gz.md5');
2050
		$error = '';
2051
		if (file_exists($tmp_dir.'notam.txt.gz.md5')) {
2052
			$notam_md5_file = explode(' ',file_get_contents($tmp_dir.'notam.txt.gz.md5'));
2053
			$notam_md5 = $notam_md5_file[0];
2054
			if (!update_db::check_notam_version($notam_md5)) {
2055
				update_db::download('http://data.flightairmap.com/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
2056
				if (file_exists($tmp_dir.'notam.txt.gz')) {
2057
					if (md5_file($tmp_dir.'notam.txt.gz') == $notam_md5) {
2058
						if ($globalDebug) echo "Gunzip...";
2059
						update_db::gunzip($tmp_dir.'notam.txt.gz');
2060
						if ($globalDebug) echo "Add to DB...";
2061
						//$error = create_db::import_file($tmp_dir.'notam.sql');
2062
						$NOTAM = new NOTAM();
2063
						$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
2064
						update_db::insert_notam_version($notam_md5);
2065
					} else $error = "File ".$tmp_dir.'notam.txt.gz'." md5 failed. Download failed.";
2066
				} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
2067
			} elseif ($globalDebug) echo "No new version.";
2068
		} else $error = "File ".$tmp_dir.'notam.txt.gz.md5'." doesn't exist. Download failed.";
2069
		if ($error != '') {
2070
			return $error;
2071
		} elseif ($globalDebug) echo "Done\n";
2072
		return '';
2073
	}
2074
2075
	public static function update_vatsim() {
2076
		global $tmp_dir;
2077
		include_once('class.create_db.php');
2078
		$error = create_db::import_file('../db/vatsim/airlines.sql');
2079
		return $error;
2080
	}
2081
	
2082
	public static function update_countries() {
2083
		global $tmp_dir, $globalDBdriver;
2084
		include_once('class.create_db.php');
2085
		$Connection = new Connection();
2086
		if ($Connection->tableExists('countries')) {
2087
			$query = 'DROP TABLE countries';
2088
			try {
2089
				$sth = $Connection->db->prepare($query);
2090
            	        	$sth->execute();
2091
	                } catch(PDOException $e) {
2092
    	                	echo "error : ".$e->getMessage();
2093
	                }
2094
		}
2095
		if ($globalDBdriver == 'mysql') {
2096
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
2097
		} else {
2098
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
2099
		}
2100
		$error = create_db::import_file($tmp_dir.'countries.sql');
2101
		return $error;
2102
	}
2103
2104
	
2105
	public static function update_waypoints() {
2106
		global $tmp_dir;
2107
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
2108
//		update_db::unzip($tmp_dir.'AptNav.zip');
2109
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
2110
//		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');
2111
		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');
2112
		update_db::gunzip($tmp_dir.'awy.dat.gz');
2113
		$error = update_db::waypoints($tmp_dir.'awy.dat');
2114
		return $error;
2115
	}
2116
2117
	public static function update_ivao() {
2118
		global $tmp_dir, $globalDebug;
2119
		$Common = new Common();
2120
		$error = '';
2121
		//Direct download forbidden
2122
		//if ($globalDebug) echo "IVAO : Download...";
2123
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
2124
		if (extension_loaded('zip')) {
2125
			if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
2126
				if ($globalDebug) echo "Unzip...";
2127
				update_db::unzip($tmp_dir.'ivae_feb2013.zip');
2128
				if ($globalDebug) echo "Add to DB...";
2129
				update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
2130
				if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
2131
				if (is_writable(dirname(__FILE__).'/../images/airlines')) {
2132
					if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
2133
				} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
2134
			} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
2135
		} else $error = "ZIP module not loaded but required for IVAO.";
2136
		if ($error != '') {
2137
			return $error;
2138
		} elseif ($globalDebug) echo "Done\n";
2139
		return '';
2140
	}
2141
2142
	public static function update_routes() {
2143
		global $tmp_dir, $globalDebug;
2144
		$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...
2145
		if ($globalDebug) echo "Routes : Download...";
2146
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
2147
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
2148
			if ($globalDebug) echo "Gunzip...";
2149
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
2150
			if ($globalDebug) echo "Add to DB...";
2151
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
2152
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
2153
		if ($error != '') {
2154
			return $error;
2155
		} elseif ($globalDebug) echo "Done\n";
2156
		return '';
2157
	}
2158
	public static function update_oneworld() {
2159
		global $tmp_dir, $globalDebug;
2160
		$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...
2161
		if ($globalDebug) echo "Schedules Oneworld : Download...";
2162
		update_db::download('http://data.flightairmap.com/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
2163
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
2164
			if ($globalDebug) echo "Gunzip...";
2165
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
2166
			if ($globalDebug) echo "Add to DB...";
2167
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
2168
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
2169
		if ($error != '') {
2170
			return $error;
2171
		} elseif ($globalDebug) echo "Done\n";
2172
		return '';
2173
	}
2174
	public static function update_skyteam() {
2175
		global $tmp_dir, $globalDebug;
2176
		$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...
2177
		if ($globalDebug) echo "Schedules Skyteam : Download...";
2178
		update_db::download('http://data.flightairmap.com/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
2179
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
2180
			if ($globalDebug) echo "Gunzip...";
2181
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
2182
			if ($globalDebug) echo "Add to DB...";
2183
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
2184
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
2185
		if ($error != '') {
2186
			return $error;
2187
		} elseif ($globalDebug) echo "Done\n";
2188
		return '';
2189
	}
2190
	public static function update_ModeS() {
2191
		global $tmp_dir, $globalDebug;
2192
/*
2193
		if ($globalDebug) echo "Modes : Download...";
2194
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
2195
		if ($globalDebug) echo "Unzip...";
2196
		update_db::unzip($tmp_dir.'basestation_latest.zip');
2197
		if ($globalDebug) echo "Add to DB...";
2198
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
2199
		if ($error != true) {
2200
			echo $error;
2201
			exit;
2202
		} elseif ($globalDebug) echo "Done\n";
2203
*/
2204
		if ($globalDebug) echo "Modes : Download...";
2205
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
2206
		update_db::download('http://data.flightairmap.com/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
2207
2208
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
2209
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
2210
			if ($globalDebug) echo "Unzip...";
2211
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
2212
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
2213
			if ($globalDebug) echo "Add to DB...";
2214
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
2215
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
2216
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
2217
		if ($error != '') {
2218
			return $error;
2219
		} elseif ($globalDebug) echo "Done\n";
2220
		return '';
2221
	}
2222
2223
	public static function update_ModeS_faa() {
2224
		global $tmp_dir, $globalDebug;
2225
		if ($globalDebug) echo "Modes FAA: Download...";
2226
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
2227
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
2228
			if ($globalDebug) echo "Unzip...";
2229
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
2230
			if ($globalDebug) echo "Add to DB...";
2231
			$error = update_db::modes_faa();
2232
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
2233
		if ($error != '') {
2234
			return $error;
2235
		} elseif ($globalDebug) echo "Done\n";
2236
		return '';
2237
	}
2238
2239
	public static function update_ModeS_flarm() {
2240
		global $tmp_dir, $globalDebug;
2241
		if ($globalDebug) echo "Modes Flarmnet: Download...";
2242
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
2243
		if (file_exists($tmp_dir.'data.fln')) {
2244
			if ($globalDebug) echo "Add to DB...";
2245
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
2246
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
2247
		if ($error != '') {
2248
			return $error;
2249
		} elseif ($globalDebug) echo "Done\n";
2250
		return '';
2251
	}
2252
2253
	public static function update_ModeS_ogn() {
2254
		global $tmp_dir, $globalDebug;
2255
		if ($globalDebug) echo "Modes OGN: Download...";
2256
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
2257
		if (file_exists($tmp_dir.'ogn.csv')) {
2258
			if ($globalDebug) echo "Add to DB...";
2259
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
2260
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
2261
		if ($error != '') {
2262
			return $error;
2263
		} elseif ($globalDebug) echo "Done\n";
2264
		return '';
2265
	}
2266
2267
	public static function update_owner() {
2268
		global $tmp_dir, $globalDebug, $globalMasterSource;
2269
		
2270
		if ($globalDebug) echo "Owner France: Download...";
2271
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
2272
		if (file_exists($tmp_dir.'owner_f.csv')) {
2273
			if ($globalDebug) echo "Add to DB...";
2274
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
2275
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
2276
		if ($error != '') {
2277
			return $error;
2278
		} elseif ($globalDebug) echo "Done\n";
2279
		
2280
		if ($globalDebug) echo "Owner Ireland: Download...";
2281
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
2282
		if (file_exists($tmp_dir.'owner_ei.csv')) {
2283
			if ($globalDebug) echo "Add to DB...";
2284
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
2285
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
2286
		if ($error != '') {
2287
			return $error;
2288
		} elseif ($globalDebug) echo "Done\n";
2289
		if ($globalDebug) echo "Owner Switzerland: Download...";
2290
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
2291
		if (file_exists($tmp_dir.'owner_hb.csv')) {
2292
			if ($globalDebug) echo "Add to DB...";
2293
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
2294
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
2295
		if ($error != '') {
2296
			return $error;
2297
		} elseif ($globalDebug) echo "Done\n";
2298
		if ($globalDebug) echo "Owner Czech Republic: Download...";
2299
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
2300
		if (file_exists($tmp_dir.'owner_ok.csv')) {
2301
			if ($globalDebug) echo "Add to DB...";
2302
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
2303
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
2304
		if ($error != '') {
2305
			return $error;
2306
		} elseif ($globalDebug) echo "Done\n";
2307
		if ($globalDebug) echo "Owner Australia: Download...";
2308
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
2309
		if (file_exists($tmp_dir.'owner_vh.csv')) {
2310
			if ($globalDebug) echo "Add to DB...";
2311
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
2312
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
2313
		if ($error != '') {
2314
			return $error;
2315
		} elseif ($globalDebug) echo "Done\n";
2316
		if ($globalDebug) echo "Owner Austria: Download...";
2317
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
2318
		if (file_exists($tmp_dir.'owner_oe.csv')) {
2319
			if ($globalDebug) echo "Add to DB...";
2320
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
2321
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
2322
		if ($error != '') {
2323
			return $error;
2324
		} elseif ($globalDebug) echo "Done\n";
2325
		if ($globalDebug) echo "Owner Chile: Download...";
2326
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
2327
		if (file_exists($tmp_dir.'owner_cc.csv')) {
2328
			if ($globalDebug) echo "Add to DB...";
2329
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
2330
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
2331
		if ($error != '') {
2332
			return $error;
2333
		} elseif ($globalDebug) echo "Done\n";
2334
		if ($globalDebug) echo "Owner Colombia: Download...";
2335
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
2336
		if (file_exists($tmp_dir.'owner_hj.csv')) {
2337
			if ($globalDebug) echo "Add to DB...";
2338
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
2339
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
2340
		if ($error != '') {
2341
			return $error;
2342
		} elseif ($globalDebug) echo "Done\n";
2343
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
2344
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
2345
		if (file_exists($tmp_dir.'owner_e7.csv')) {
2346
			if ($globalDebug) echo "Add to DB...";
2347
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
2348
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
2349
		if ($error != '') {
2350
			return $error;
2351
		} elseif ($globalDebug) echo "Done\n";
2352
		if ($globalDebug) echo "Owner Brazil: Download...";
2353
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
2354
		if (file_exists($tmp_dir.'owner_pp.csv')) {
2355
			if ($globalDebug) echo "Add to DB...";
2356
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
2357
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
2358
		if ($error != '') {
2359
			return $error;
2360
		} elseif ($globalDebug) echo "Done\n";
2361
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
2362
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
2363
		if (file_exists($tmp_dir.'owner_vp.csv')) {
2364
			if ($globalDebug) echo "Add to DB...";
2365
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
2366
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
2367
		if ($error != '') {
2368
			return $error;
2369
		} elseif ($globalDebug) echo "Done\n";
2370
		if ($globalDebug) echo "Owner Croatia: Download...";
2371
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
2372
		if (file_exists($tmp_dir.'owner_9a.csv')) {
2373
			if ($globalDebug) echo "Add to DB...";
2374
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
2375
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
2376
		if ($error != '') {
2377
			return $error;
2378
		} elseif ($globalDebug) echo "Done\n";
2379
		if ($globalDebug) echo "Owner Luxembourg: Download...";
2380
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
2381
		if (file_exists($tmp_dir.'owner_lx.csv')) {
2382
			if ($globalDebug) echo "Add to DB...";
2383
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
2384
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
2385
		if ($error != '') {
2386
			return $error;
2387
		} elseif ($globalDebug) echo "Done\n";
2388
		if ($globalDebug) echo "Owner Maldives: Download...";
2389
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
2390
		if (file_exists($tmp_dir.'owner_8q.csv')) {
2391
			if ($globalDebug) echo "Add to DB...";
2392
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
2393
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
2394
		if ($error != '') {
2395
			return $error;
2396
		} elseif ($globalDebug) echo "Done\n";
2397
		if ($globalDebug) echo "Owner New Zealand: Download...";
2398
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
2399
		if (file_exists($tmp_dir.'owner_zk.csv')) {
2400
			if ($globalDebug) echo "Add to DB...";
2401
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
2402
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
2403
		if ($error != '') {
2404
			return $error;
2405
		} elseif ($globalDebug) echo "Done\n";
2406
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
2407
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
2408
		if (file_exists($tmp_dir.'owner_p2.csv')) {
2409
			if ($globalDebug) echo "Add to DB...";
2410
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
2411
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
2412
		if ($error != '') {
2413
			return $error;
2414
		} elseif ($globalDebug) echo "Done\n";
2415
		if ($globalDebug) echo "Owner Slovakia: Download...";
2416
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
2417
		if (file_exists($tmp_dir.'owner_om.csv')) {
2418
			if ($globalDebug) echo "Add to DB...";
2419
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
2420
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
2421
		if ($error != '') {
2422
			return $error;
2423
		} elseif ($globalDebug) echo "Done\n";
2424
		if ($globalDebug) echo "Owner Ecuador: Download...";
2425
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
2426
		if (file_exists($tmp_dir.'owner_hc.csv')) {
2427
			if ($globalDebug) echo "Add to DB...";
2428
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
2429
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
2430
		if ($error != '') {
2431
			return $error;
2432
		} elseif ($globalDebug) echo "Done\n";
2433
		if ($globalDebug) echo "Owner Iceland: Download...";
2434
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
2435
		if (file_exists($tmp_dir.'owner_tf.csv')) {
2436
			if ($globalDebug) echo "Add to DB...";
2437
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
2438
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
2439
		if ($error != '') {
2440
			return $error;
2441
		} elseif ($globalDebug) echo "Done\n";
2442
		if ($globalDebug) echo "Owner Isle of Man: Download...";
2443
		update_db::download('http://antonakis.co.uk/registers/IsleOfMan.txt',$tmp_dir.'owner_m.csv');
2444
		if (file_exists($tmp_dir.'owner_m.csv')) {
2445
			if ($globalDebug) echo "Add to DB...";
2446
			$error = update_db::retrieve_owner($tmp_dir.'owner_m.csv','M');
2447
		} else $error = "File ".$tmp_dir.'owner_m.csv'." doesn't exist. Download failed.";
2448
		if ($error != '') {
2449
			return $error;
2450
		} elseif ($globalDebug) echo "Done\n";
2451
		if ($globalMasterSource) {
2452
			if ($globalDebug) echo "ModeS Netherlands: Download...";
2453
			update_db::download('http://antonakis.co.uk/registers/Netherlands.txt',$tmp_dir.'owner_ph.csv');
2454
			if (file_exists($tmp_dir.'owner_ph.csv')) {
2455
				if ($globalDebug) echo "Add to DB...";
2456
				$error = update_db::retrieve_owner($tmp_dir.'owner_ph.csv','PH');
2457
			} else $error = "File ".$tmp_dir.'owner_ph.csv'." doesn't exist. Download failed.";
2458
			if ($error != '') {
2459
				return $error;
2460
			} elseif ($globalDebug) echo "Done\n";
2461
			if ($globalDebug) echo "ModeS Denmark: Download...";
2462
			update_db::download('http://antonakis.co.uk/registers/Denmark.txt',$tmp_dir.'owner_oy.csv');
2463
			if (file_exists($tmp_dir.'owner_oy.csv')) {
2464
				if ($globalDebug) echo "Add to DB...";
2465
				$error = update_db::retrieve_owner($tmp_dir.'owner_oy.csv','OY');
2466
			} else $error = "File ".$tmp_dir.'owner_oy.csv'." doesn't exist. Download failed.";
2467
			if ($error != '') {
2468
				return $error;
2469
			} elseif ($globalDebug) echo "Done\n";
2470
		} elseif ($globalDebug) echo "Done\n";
2471
		return '';
2472
	}
2473
2474
	public static function update_translation() {
2475
		global $tmp_dir, $globalDebug;
2476
		$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...
2477
		if ($globalDebug) echo "Translation : Download...";
2478
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
2479
		if (file_exists($tmp_dir.'translation.zip')) {
2480
			if ($globalDebug) echo "Unzip...";
2481
			update_db::unzip($tmp_dir.'translation.zip');
2482
			if ($globalDebug) echo "Add to DB...";
2483
			$error = update_db::translation();
2484
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
2485
		if ($error != '') {
2486
			return $error;
2487
		} elseif ($globalDebug) echo "Done\n";
2488
		return '';
2489
	}
2490
2491
	public static function update_translation_fam() {
2492
		global $tmp_dir, $globalDebug;
2493
		$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...
2494
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
2495
		update_db::download('http://data.flightairmap.com/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
2496
		update_db::download('http://data.flightairmap.com/data/translation.tsv.gz.md5',$tmp_dir.'translation.tsv.gz.md5');
2497
		if (file_exists($tmp_dir.'translation.tsv.gz') && file_exists($tmp_dir.'translation.tsv.gz')) {
2498
			$translation_md5_file = explode(' ',file_get_contents($tmp_dir.'translation.tsv.gz.md5'));
2499
			$translation_md5 = $translation_md5_file[0];
2500
			if (md5_file($tmp_dir.'translation.tsv.gz') == $translation_md5) {
2501
				if ($globalDebug) echo "Gunzip...";
2502
				update_db::gunzip($tmp_dir.'translation.tsv.gz');
2503
				if ($globalDebug) echo "Add to DB...";
2504
				$error = update_db::translation_fam();
2505
			} else $error = "File ".$tmp_dir.'translation.tsv.gz'." md5 failed. Download failed.";
2506
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
2507
		if ($error != '') {
2508
			return $error;
2509
		} elseif ($globalDebug) echo "Done\n";
2510
		return '';
2511
	}
2512
	public static function update_ModeS_fam() {
2513
		global $tmp_dir, $globalDebug;
2514
		$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...
2515
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
2516
		update_db::download('http://data.flightairmap.com/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
2517
		update_db::download('http://data.flightairmap.com/data/modes.tsv.gz.md5',$tmp_dir.'modes.tsv.gz.md5');
2518
		if (file_exists($tmp_dir.'modes.tsv.gz') && file_exists($tmp_dir.'modes.tsv.gz.md5')) {
2519
			$modes_md5_file = explode(' ',file_get_contents($tmp_dir.'modes.tsv.gz.md5'));
2520
			$modes_md5 = $modes_md5_file[0];
2521
			if (md5_file($tmp_dir.'modes.tsv.gz') == $modes_md5) {
2522
				if ($globalDebug) echo "Gunzip...";
2523
				update_db::gunzip($tmp_dir.'modes.tsv.gz');
2524
				if ($globalDebug) echo "Add to DB...";
2525
				$error = update_db::modes_fam();
2526
			} else $error = "File ".$tmp_dir.'modes.tsv.gz'." md5 failed. Download failed.";
2527
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
2528
		if ($error != '') {
2529
			return $error;
2530
		} elseif ($globalDebug) echo "Done\n";
2531
		return '';
2532
	}
2533
2534
	public static function update_airlines_fam() {
2535
		global $tmp_dir, $globalDebug;
2536
		$error = '';
2537
		if ($globalDebug) echo "Airlines from FlightAirMap website : Download...";
2538
		update_db::download('http://data.flightairmap.com/data/airlines.tsv.gz.md5',$tmp_dir.'airlines.tsv.gz.md5');
2539
		if (file_exists($tmp_dir.'airlines.tsv.gz.md5')) {
2540
			$airlines_md5_file = explode(' ',file_get_contents($tmp_dir.'airlines.tsv.gz.md5'));
2541
			$airlines_md5 = $airlines_md5_file[0];
2542
			if (!update_db::check_airlines_version($airlines_md5)) {
2543
				update_db::download('http://data.flightairmap.com/data/airlines.tsv.gz',$tmp_dir.'airlines.tsv.gz');
2544
				if (file_exists($tmp_dir.'airlines.tsv.gz')) {
2545
					if (md5_file($tmp_dir.'airlines.tsv.gz') == $airlines_md5) {
2546
						if ($globalDebug) echo "Gunzip...";
2547
						update_db::gunzip($tmp_dir.'airlines.tsv.gz');
2548
						if ($globalDebug) echo "Add to DB...";
2549
						$error = update_db::airlines_fam();
2550
						update_db::insert_airlines_version($airlines_md5);
2551
					} else $error = "File ".$tmp_dir.'airlines.tsv.gz'." md5 failed. Download failed.";
2552
			    } else $error = "File ".$tmp_dir.'airlines.tsv.gz'." doesn't exist. Download failed.";
2553
			} elseif ($globalDebug) echo "No update.";
2554
		} else $error = "File ".$tmp_dir.'airlines.tsv.gz.md5'." doesn't exist. Download failed.";
2555
		if ($error != '') {
2556
			return $error;
2557
		} else {
2558
			if ($globalDebug) echo "Done\n";
2559
		}
2560
		return '';
2561
	}
2562
2563
	public static function update_owner_fam() {
2564
		global $tmp_dir, $globalDebug, $globalOwner;
2565
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
2566
		$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...
2567
		if ($globalOwner === TRUE) {
2568
			update_db::download('http://data.flightairmap.com/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
2569
			update_db::download('http://data.flightairmap.com/data/owners_all.tsv.gz.md5',$tmp_dir.'owners.tsv.gz.md5');
2570
		} else {
2571
			update_db::download('http://data.flightairmap.com/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
2572
			update_db::download('http://data.flightairmap.com/data/owners.tsv.gz.md5',$tmp_dir.'owners.tsv.gz.md5');
2573
		}
2574
		if (file_exists($tmp_dir.'owners.tsv.gz') && file_exists($tmp_dir.'owners.tsv.gz.md5')) {
2575
			$owners_md5_file = explode(' ',file_get_contents($tmp_dir.'owners.tsv.gz.md5'));
2576
			$owners_md5 = $owners_md5_file[0];
2577
			if (md5_file($tmp_dir.'owners.tsv.gz') == $owners_md5) {
2578
				if ($globalDebug) echo "Gunzip...";
2579
				update_db::gunzip($tmp_dir.'owners.tsv.gz');
2580
				if ($globalDebug) echo "Add to DB...";
2581
				$error = update_db::owner_fam();
2582
			} else $error = "File ".$tmp_dir.'owners.tsv.gz'." md5 failed. Download failed.";
2583
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
2584
		if ($error != '') {
2585
			return $error;
2586
		} elseif ($globalDebug) echo "Done\n";
2587
		return '';
2588
	}
2589
	public static function update_routes_fam() {
2590
		global $tmp_dir, $globalDebug;
2591
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
2592
		update_db::download('http://data.flightairmap.com/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
2593
		update_db::download('http://data.flightairmap.com/data/routes.tsv.gz.md5',$tmp_dir.'routes.tsv.gz.md5');
2594
		if (file_exists($tmp_dir.'routes.tsv.gz') && file_exists($tmp_dir.'routes.tsv.gz.md5')) {
2595
			$routes_md5_file = explode(' ',file_get_contents($tmp_dir.'routes.tsv.gz.md5'));
2596
			$routes_md5 = $routes_md5_file[0];
2597
			if (md5_file($tmp_dir.'routes.tsv.gz') == $routes_md5) {
2598
				if ($globalDebug) echo "Gunzip...";
2599
				update_db::gunzip($tmp_dir.'routes.tsv.gz');
2600
				if ($globalDebug) echo "Add to DB...";
2601
				$error = update_db::routes_fam();
2602
			} else $error = "File ".$tmp_dir.'routes.tsv.gz'." md5 failed. Download failed.";
2603
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
2604
		if ($error != '') {
2605
			return $error;
2606
		} elseif ($globalDebug) echo "Done\n";
2607
		return '';
2608
	}
2609
	public static function update_block_fam() {
2610
		global $tmp_dir, $globalDebug;
2611
		if ($globalDebug) echo "Blocked aircraft from FlightAirMap website : Download...";
2612
		update_db::download('http://data.flightairmap.com/data/block.tsv.gz',$tmp_dir.'block.tsv.gz');
2613
		update_db::download('http://data.flightairmap.com/data/block.tsv.gz.md5',$tmp_dir.'block.tsv.gz.md5');
2614
		if (file_exists($tmp_dir.'block.tsv.gz') && file_exists($tmp_dir.'block.tsv.gz.md5')) {
2615
			$block_md5_file = explode(' ',file_get_contents($tmp_dir.'block.tsv.gz.md5'));
2616
			$block_md5 = $block_md5_file[0];
2617
			if (md5_file($tmp_dir.'block.tsv.gz') == $block_md5) {
2618
				if ($globalDebug) echo "Gunzip...";
2619
				update_db::gunzip($tmp_dir.'block.tsv.gz');
2620
				if ($globalDebug) echo "Add to DB...";
2621
				$error = update_db::block_fam();
2622
			} else $error = "File ".$tmp_dir.'block.tsv.gz'." md5 failed. Download failed.";
2623
		} else $error = "File ".$tmp_dir.'block.tsv.gz'." doesn't exist. Download failed.";
2624
		if ($error != '') {
2625
			return $error;
2626
		} elseif ($globalDebug) echo "Done\n";
2627
		return '';
2628
	}
2629
	public static function update_marine_identity_fam() {
2630
		global $tmp_dir, $globalDebug;
2631
		update_db::download('http://data.flightairmap.com/data/marine_identity.tsv.gz.md5',$tmp_dir.'marine_identity.tsv.gz.md5');
2632
		if (file_exists($tmp_dir.'marine_identity.tsv.gz.md5')) {
2633
			$marine_identity_md5_file = explode(' ',file_get_contents($tmp_dir.'marine_identity.tsv.gz.md5'));
2634
			$marine_identity_md5 = $marine_identity_md5_file[0];
2635
			if (!update_db::check_marine_identity_version($marine_identity_md5)) {
2636
				if ($globalDebug) echo "Marine identity from FlightAirMap website : Download...";
2637
				update_db::download('http://data.flightairmap.com/data/marine_identity.tsv.gz',$tmp_dir.'marine_identity.tsv.gz');
2638
				if (file_exists($tmp_dir.'marine_identity.tsv.gz')) {
2639
					if (md5_file($tmp_dir.'marine_identity.tsv.gz') == $marine_identity_md5) {
2640
						if ($globalDebug) echo "Gunzip...";
2641
						update_db::gunzip($tmp_dir.'marine_identity.tsv.gz');
2642
						if ($globalDebug) echo "Add to DB...";
2643
						$error = update_db::marine_identity_fam();
2644
					} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." md5 failed. Download failed.";
2645
				} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." doesn't exist. Download failed.";
2646
				if ($error != '') {
2647
					return $error;
2648
				} else {
2649
					update_db::insert_marine_identity_version($marine_identity_md5);
2650
					if ($globalDebug) echo "Done\n";
2651
				}
2652
			}
2653
		}
2654
		return '';
2655
	}
2656
2657
	public static function update_satellite_fam() {
2658
		global $tmp_dir, $globalDebug;
2659
		update_db::download('http://data.flightairmap.com/data/satellite.tsv.gz.md5',$tmp_dir.'satellite.tsv.gz.md5');
2660
		if (file_exists($tmp_dir.'satellite.tsv.gz.md5')) {
2661
			$satellite_md5_file = explode(' ',file_get_contents($tmp_dir.'satellite.tsv.gz.md5'));
2662
			$satellite_md5 = $satellite_md5_file[0];
2663
			if (!update_db::check_satellite_version($satellite_md5)) {
2664
				if ($globalDebug) echo "Satellite from FlightAirMap website : Download...";
2665
				update_db::download('http://data.flightairmap.com/data/satellite.tsv.gz',$tmp_dir.'satellite.tsv.gz');
2666
				if (file_exists($tmp_dir.'satellite.tsv.gz')) {
2667
					if (md5_file($tmp_dir.'satellite.tsv.gz') == $satellite_md5) {
2668
						if ($globalDebug) echo "Gunzip...";
2669
						update_db::gunzip($tmp_dir.'satellite.tsv.gz');
2670
						if ($globalDebug) echo "Add to DB...";
2671
						$error = update_db::satellite_fam();
2672
					} else $error = "File ".$tmp_dir.'satellite.tsv.gz'." md5 failed. Download failed.";
2673
				} else $error = "File ".$tmp_dir.'satellite.tsv.gz'." doesn't exist. Download failed.";
2674
				if ($error != '') {
2675
					return $error;
2676
				} else {
2677
					update_db::insert_satellite_version($satellite_md5);
2678
					if ($globalDebug) echo "Done\n";
2679
				}
2680
			}
2681
		}
2682
		return '';
2683
	}
2684
	public static function update_diagrams_fam() {
2685
		global $tmp_dir, $globalDebug;
2686
		update_db::download('http://data.flightairmap.com/data/diagrams/diagramspdf.md5',$tmp_dir.'diagramspdf.md5');
2687
		if (file_exists($tmp_dir.'diagramspdf.md5')) {
2688
			$diagrams_md5_file = explode(' ',file_get_contents($tmp_dir.'diagramspdf.md5'));
2689
			$diagrams_md5 = $diagrams_md5_file[0];
2690
			if (!update_db::check_diagrams_version($diagrams_md5)) {
2691
				if ($globalDebug) echo "Airports diagrams from FlightAirMap website : Download...";
2692
				update_db::download('http://data.flightairmap.com/data/diagrams/diagramspdf',$tmp_dir.'diagramspdf');
2693
				if (file_exists($tmp_dir.'diagramspdf')) {
2694
					if (md5_file($tmp_dir.'diagramspdf') == $diagrams_md5) {
2695
						if ($globalDebug) echo "Add to DB...";
2696
						$error = update_db::diagrams_fam();
2697
					} else $error = "File ".$tmp_dir.'diagramspdf'." md5 failed. Download failed.";
2698
				} else $error = "File ".$tmp_dir.'diagramspdf'." doesn't exist. Download failed.";
2699
				if ($error != '') {
2700
					return $error;
2701
				} else {
2702
					update_db::insert_diagrams_version($diagrams_md5);
2703
					if ($globalDebug) echo "Done\n";
2704
				}
2705
			}
2706
		}
2707
		return '';
2708
	}
2709
	public static function update_banned_fam() {
2710
		global $tmp_dir, $globalDebug;
2711
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
2712
		update_db::download('http://data.flightairmap.com/data/ban-eu.csv',$tmp_dir.'ban_eu.csv');
2713
		if (file_exists($tmp_dir.'ban_eu.csv')) {
2714
			//if ($globalDebug) echo "Gunzip...";
2715
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
2716
			if ($globalDebug) echo "Add to DB...";
2717
			$error = update_db::banned_fam();
2718
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
2719
		if ($error != '') {
2720
			return $error;
2721
		} elseif ($globalDebug) echo "Done\n";
2722
		return '';
2723
	}
2724
2725
	public static function update_airspace_fam() {
2726
		global $tmp_dir, $globalDebug, $globalDBdriver;
2727
		include_once('class.create_db.php');
2728
		$error = '';
2729
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
2730
		if ($globalDBdriver == 'mysql') {
2731
			update_db::download('http://data.flightairmap.com/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2732
		} else {
2733
			update_db::download('http://data.flightairmap.com/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2734
		}
2735
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
2736
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
2737
			$airspace_md5 = $airspace_md5_file[0];
2738
			if (!update_db::check_airspace_version($airspace_md5)) {
2739
				if ($globalDBdriver == 'mysql') {
2740
					update_db::download('http://data.flightairmap.com/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
2741
				} else {
2742
					update_db::download('http://data.flightairmap.com/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
2743
				}
2744
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
2745
					if (md5_file($tmp_dir.'airspace.sql.gz') == $airspace_md5) {
2746
						if ($globalDebug) echo "Gunzip...";
2747
						update_db::gunzip($tmp_dir.'airspace.sql.gz');
2748
						if ($globalDebug) echo "Add to DB...";
2749
						$Connection = new Connection();
2750
						if ($Connection->tableExists('airspace')) {
2751
							$query = 'DROP TABLE airspace';
2752
							try {
2753
								$sth = $Connection->db->prepare($query);
2754
								$sth->execute();
2755
							} catch(PDOException $e) {
2756
								return "error : ".$e->getMessage();
2757
							}
2758
						}
2759
						$error = create_db::import_file($tmp_dir.'airspace.sql');
2760
						update_db::insert_airspace_version($airspace_md5);
2761
					} else $error = "File ".$tmp_dir.'airspace.sql.gz'." md5 failed. Download failed.";
2762
				} else $error = "File ".$tmp_dir.'airspace.sql.gz'." doesn't exist. Download failed.";
2763
			}
2764
		} else $error = "File ".$tmp_dir.'airspace.sql.gz.md5'." doesn't exist. Download failed.";
2765
		if ($error != '') {
2766
			return $error;
2767
		} elseif ($globalDebug) echo "Done\n";
2768
		return '';
2769
	}
2770
2771
	public static function update_geoid_fam() {
2772
		global $tmp_dir, $globalDebug, $globalGeoidSource;
2773
		$error = '';
2774
		if ($globalDebug) echo "Geoid from FlightAirMap website : Download...";
2775
		update_db::download('http://data.flightairmap.com/data/geoid/'.$globalGeoidSource.'.pgm.gz.md5',$tmp_dir.$globalGeoidSource.'.pgm.gz.md5');
2776
		if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz.md5')) {
2777
			$geoid_md5_file = explode(' ',file_get_contents($tmp_dir.$globalGeoidSource.'.pgm.gz.md5'));
2778
			$geoid_md5 = $geoid_md5_file[0];
2779
			if (!update_db::check_geoid_version($geoid_md5)) {
2780
				update_db::download('http://data.flightairmap.com/data/geoid/'.$globalGeoidSource.'.pgm.gz',$tmp_dir.$globalGeoidSource.'.pgm.gz');
2781
				if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz')) {
2782
					if (md5_file($tmp_dir.$globalGeoidSource.'.pgm.gz') == $geoid_md5) {
2783
						if ($globalDebug) echo "Gunzip...";
2784
						update_db::gunzip($tmp_dir.$globalGeoidSource.'.pgm.gz',dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm');
2785
						if (file_exists(dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm')) {
2786
							update_db::insert_geoid_version($geoid_md5);
2787
						} else $error = "File data/".$globalGeoidSource.'.pgm'." doesn't exist. Gunzip failed.";
2788
					} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." md5 failed. Download failed.";
2789
				} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." doesn't exist. Download failed.";
2790
			} elseif ($globalDebug) echo 'No new version'."\n";
2791
		} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz.md5'." doesn't exist. Download failed.";
2792
		if ($error != '') {
2793
			return $error;
2794
		} elseif ($globalDebug) echo "Done\n";
2795
		return '';
2796
	}
2797
2798
	public static function update_tle() {
2799
		global $tmp_dir, $globalDebug;
2800
		if ($globalDebug) echo "Download TLE : Download...";
2801
		$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',
2802
		'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',
2803
		'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');
2804
		foreach ($alltle as $filename) {
2805
			if ($globalDebug) echo "downloading ".$filename.'...';
2806
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
2807
			if (file_exists($tmp_dir.$filename)) {
2808
				if ($globalDebug) echo "Add to DB ".$filename."...";
2809
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
2810
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
2811
			if ($error != '') {
2812
				echo $error."\n";
2813
			} elseif ($globalDebug) echo "Done\n";
2814
		}
2815
		return '';
2816
	}
2817
2818
	public static function update_ucsdb() {
2819
		global $tmp_dir, $globalDebug;
2820
		if ($globalDebug) echo "Download UCS DB : Download...";
2821
		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');
2822
		if (file_exists($tmp_dir.'UCS_Satellite_Database_officialname_1-1-17.txt')) {
2823
			if ($globalDebug) echo "Add to DB...";
2824
			$error = update_db::satellite_ucsdb($tmp_dir.'UCS_Satellite_Database_officialname_9-1-2017.txt');
2825
		} else $error = "File ".$tmp_dir.'UCS_Satellite_Database_officialname_9-1-2017.txt'." doesn't exist. Download failed.";
2826
		if ($error != '') {
2827
			echo $error."\n";
2828
		} elseif ($globalDebug) echo "Done\n";
2829
		return '';
2830
	}
2831
2832
	public static function update_celestrak() {
2833
		global $tmp_dir, $globalDebug;
2834
		if ($globalDebug) echo "Download Celestrak DB : Download...";
2835
		update_db::download('http://celestrak.com/pub/satcat.txt',$tmp_dir.'satcat.txt');
2836
		if (file_exists($tmp_dir.'satcat.txt')) {
2837
			if ($globalDebug) echo "Add to DB...";
2838
			$error = update_db::satellite_celestrak($tmp_dir.'satcat.txt');
2839
		} else $error = "File ".$tmp_dir.'satcat.txt'." doesn't exist. Download failed.";
2840
		if ($error != '') {
2841
			echo $error."\n";
2842
		} elseif ($globalDebug) echo "Done\n";
2843
		return '';
2844
	}
2845
2846
	public static function update_models() {
2847
		global $tmp_dir, $globalDebug;
2848
		$error = '';
2849
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2850
		if (!is_writable(dirname(__FILE__).'/../models')) {
2851
			if ($globalDebug) echo dirname(__FILE__).'/../models'.' is not writable !';
2852
			return '';
2853
		}
2854
		update_db::download('http://data.flightairmap.com/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2855
		if (file_exists($tmp_dir.'models.md5sum')) {
2856
			if ($globalDebug) echo "Check files...\n";
2857
			$newmodelsdb = array();
2858
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2859
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2860
					$model = trim($row[2]);
2861
					$newmodelsdb[$model] = trim($row[0]);
2862
				}
2863
			}
2864
			$modelsdb = array();
2865
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2866
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2867
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2868
						$model = trim($row[2]);
2869
						$modelsdb[$model] = trim($row[0]);
2870
					}
2871
				}
2872
			}
2873
			$diff = array_diff($newmodelsdb,$modelsdb);
2874
			foreach ($diff as $key => $value) {
2875
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2876
				update_db::download('http://data.flightairmap.com/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2877
			}
2878
			update_db::download('http://data.flightairmap.com/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2879
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2880
		if ($error != '') {
2881
			return $error;
2882
		} elseif ($globalDebug) echo "Done\n";
2883
		if ($globalDebug) echo "glTF 2.0 Models from FlightAirMap website : Download...";
2884
		update_db::download('http://data.flightairmap.com/data/models/gltf2/models.md5sum',$tmp_dir.'modelsgltf2.md5sum');
2885
		if (file_exists($tmp_dir.'modelsgltf2.md5sum')) {
2886
			if ($globalDebug) echo "Check files...\n";
2887
			$newmodelsdb = array();
2888
			if (($handle = fopen($tmp_dir.'modelsgltf2.md5sum','r')) !== FALSE) {
2889
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2890
					$model = trim($row[2]);
2891
					$newmodelsdb[$model] = trim($row[0]);
2892
				}
2893
			}
2894
			$modelsdb = array();
2895
			if (file_exists(dirname(__FILE__).'/../models/gltf2/models.md5sum')) {
2896
				if (($handle = fopen(dirname(__FILE__).'/../models/gltf2/models.md5sum','r')) !== FALSE) {
2897
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2898
						$model = trim($row[2]);
2899
						$modelsdb[$model] = trim($row[0]);
2900
					}
2901
				}
2902
			}
2903
			$diff = array_diff($newmodelsdb,$modelsdb);
2904
			foreach ($diff as $key => $value) {
2905
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2906
				update_db::download('http://data.flightairmap.com/data/models/gltf2/'.$key,dirname(__FILE__).'/../models/gltf2/'.$key);
2907
				
2908
			}
2909
			update_db::download('http://data.flightairmap.com/data/models/gltf2/models.md5sum',dirname(__FILE__).'/../models/gltf2/models.md5sum');
2910
		} else $error = "File ".$tmp_dir.'modelsgltf2.md5sum'." doesn't exist. Download failed.";
2911
		if ($error != '') {
2912
			return $error;
2913
		} elseif ($globalDebug) echo "Done\n";
2914
		return '';
2915
	}
2916
	public static function update_weather_models() {
2917
		global $tmp_dir, $globalDebug;
2918
		$error = '';
2919
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2920
		if (!is_writable(dirname(__FILE__).'/../models/gltf2/weather')) {
2921
			if ($globalDebug) echo dirname(__FILE__).'/../models/gltf2/weather'.' is not writable !';
2922
			return '';
2923
		}
2924
		if ($globalDebug) echo "Weather Models from FlightAirMap website : Download...";
2925
		update_db::download('http://data.flightairmap.com/data/models/gltf2/weather/models.md5sum',$tmp_dir.'modelsweather.md5sum');
2926
		if (file_exists($tmp_dir.'modelsweather.md5sum')) {
2927
			if ($globalDebug) echo "Check files...\n";
2928
			$newmodelsdb = array();
2929
			if (($handle = fopen($tmp_dir.'modelsweather.md5sum','r')) !== FALSE) {
2930
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2931
					$model = trim($row[2]);
2932
					$newmodelsdb[$model] = trim($row[0]);
2933
				}
2934
			}
2935
			$modelsdb = array();
2936
			if (file_exists(dirname(__FILE__).'/../models/gltf2/weather/models.md5sum')) {
2937
				if (($handle = fopen(dirname(__FILE__).'/../models/gltf2/weather/models.md5sum','r')) !== FALSE) {
2938
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2939
						$model = trim($row[2]);
2940
						$modelsdb[$model] = trim($row[0]);
2941
					}
2942
				}
2943
			}
2944
			$diff = array_diff($newmodelsdb,$modelsdb);
2945
			foreach ($diff as $key => $value) {
2946
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2947
				update_db::download('http://data.flightairmap.com/data/models/gltf2/weather/'.$key,dirname(__FILE__).'/../models/gltf2/weather/'.$key);
2948
				
2949
			}
2950
			update_db::download('http://data.flightairmap.com/data/models/gltf2/weather/models.md5sum',dirname(__FILE__).'/../models/gltf2/weather/models.md5sum');
2951
		} else $error = "File ".$tmp_dir.'modelsweather.md5sum'." doesn't exist. Download failed.";
2952
		if ($error != '') {
2953
			return $error;
2954
		} elseif ($globalDebug) echo "Done\n";
2955
		return '';
2956
	}
2957
2958
	public static function update_liveries() {
2959
		global $tmp_dir, $globalDebug;
2960
		$error = '';
2961
		if ($globalDebug) echo "Liveries from FlightAirMap website : Download...";
2962
		update_db::download('http://data.flightairmap.com/data/models/gltf2/liveries/liveries.md5sum',$tmp_dir.'liveries.md5sum');
2963
		if (file_exists($tmp_dir.'liveries.md5sum')) {
2964
			if ($globalDebug) echo "Check files...\n";
2965
			$newmodelsdb = array();
2966
			if (($handle = fopen($tmp_dir.'liveries.md5sum','r')) !== FALSE) {
2967
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2968
					$model = trim($row[2]);
2969
					$newmodelsdb[$model] = trim($row[0]);
2970
				}
2971
			}
2972
			$modelsdb = array();
2973
			if (file_exists(dirname(__FILE__).'/../models/gltf2/liveries/liveries.md5sum')) {
2974
				if (($handle = fopen(dirname(__FILE__).'/../models/gltf2/liveries/liveries.md5sum','r')) !== FALSE) {
2975
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2976
						$model = trim($row[2]);
2977
						$modelsdb[$model] = trim($row[0]);
2978
					}
2979
				}
2980
			}
2981
			$diff = array_diff($newmodelsdb,$modelsdb);
2982
			foreach ($diff as $key => $value) {
2983
				if ($globalDebug) echo 'Downloading liveries '.$key.' ...'."\n";
2984
				update_db::download('http://data.flightairmap.com/data/models/gltf2/liveries/'.$key,dirname(__FILE__).'/../models/gltf2/liveries/'.$key);
2985
				
2986
			}
2987
			update_db::download('http://data.flightairmap.com/data/models/gltf2/liveries/liveries.md5sum',dirname(__FILE__).'/../models/gltf2/liveries/liveries.md5sum');
2988
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2989
		if ($error != '') {
2990
			return $error;
2991
		} elseif ($globalDebug) echo "Done\n";
2992
		return '';
2993
	}
2994
2995
	public static function update_space_models() {
2996
		global $tmp_dir, $globalDebug;
2997
		$error = '';
2998
		if (!is_writable(dirname(__FILE__).'/../models')) {
2999
			if ($globalDebug) echo dirname(__FILE__).'/../models'.' is not writable !';
3000
			return '';
3001
		}
3002
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
3003
		update_db::download('http://data.flightairmap.com/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
3004
		if (file_exists($tmp_dir.'space_models.md5sum')) {
3005
			if ($globalDebug) echo "Check files...\n";
3006
			$newmodelsdb = array();
3007
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
3008
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
3009
					$model = trim($row[2]);
3010
					$newmodelsdb[$model] = trim($row[0]);
3011
				}
3012
			}
3013
			$modelsdb = array();
3014
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
3015
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
3016
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
3017
						$model = trim($row[2]);
3018
						$modelsdb[$model] = trim($row[0]);
3019
					}
3020
				}
3021
			}
3022
			$diff = array_diff($newmodelsdb,$modelsdb);
3023
			foreach ($diff as $key => $value) {
3024
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
3025
				update_db::download('http://data.flightairmap.com/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
3026
				
3027
			}
3028
			update_db::download('http://data.flightairmap.com/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
3029
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
3030
		if ($error != '') {
3031
			return $error;
3032
		} elseif ($globalDebug) echo "Done\n";
3033
		return '';
3034
	}
3035
3036
	public static function update_vehicules_models() {
3037
		global $tmp_dir, $globalDebug;
3038
		$error = '';
3039
		if (!is_writable(dirname(__FILE__).'/../models/vehicules')) {
3040
			if ($globalDebug) echo dirname(__FILE__).'/../models/vehicules'.' is not writable !';
3041
			return '';
3042
		}
3043
		if ($globalDebug) echo "Vehicules models from FlightAirMap website : Download...";
3044
		update_db::download('http://data.flightairmap.com/data/models/vehicules/vehicules_models.md5sum',$tmp_dir.'vehicules_models.md5sum');
3045
		if (file_exists($tmp_dir.'vehicules_models.md5sum')) {
3046
			if ($globalDebug) echo "Check files...\n";
3047
			$newmodelsdb = array();
3048
			if (($handle = fopen($tmp_dir.'vehicules_models.md5sum','r')) !== FALSE) {
3049
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
3050
					$model = trim($row[2]);
3051
					$newmodelsdb[$model] = trim($row[0]);
3052
				}
3053
			}
3054
			$modelsdb = array();
3055
			if (file_exists(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum')) {
3056
				if (($handle = fopen(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum','r')) !== FALSE) {
3057
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
3058
						$model = trim($row[2]);
3059
						$modelsdb[$model] = trim($row[0]);
3060
					}
3061
				}
3062
			}
3063
			$diff = array_diff($newmodelsdb,$modelsdb);
3064
			foreach ($diff as $key => $value) {
3065
				if ($globalDebug) echo 'Downloading vehicules model '.$key.' ...'."\n";
3066
				update_db::download('http://data.flightairmap.com/data/models/vehicules/'.$key,dirname(__FILE__).'/../models/vehicules/'.$key);
3067
				
3068
			}
3069
			update_db::download('http://data.flightairmap.com/data/models/vehicules/vehicules_models.md5sum',dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum');
3070
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
3071
		if ($error != '') {
3072
			return $error;
3073
		} elseif ($globalDebug) echo "Done\n";
3074
		return '';
3075
	}
3076
3077
	public static function update_aircraft() {
3078
		global $tmp_dir, $globalDebug;
3079
		date_default_timezone_set('UTC');
3080
		$Common = new Common();
3081
		$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);
3082
		$all = json_decode($data,true);
3083
		$Connection = new Connection();
3084
		$querychk = "SELECT COUNT(1) as nb FROM aircraft WHERE icao = :icao";
3085
		$sth = $Connection->db->prepare($querychk);
3086
		$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,'')";
3087
		$queryup = "UPDATE aircraft SET type = :type WHERE icao = :icao";
3088
		$sthins = $Connection->db->prepare($queryins);
3089
		$sthup = $Connection->db->prepare($queryup);
3090
		$allicao = array();
3091
		foreach ($all as $model) {
3092
			$icao = $model['Designator'];
3093
			if (!isset($allicao[$icao])) {
3094
				$aircraft_shadow = 'generic_'.substr($model['EngineType'],0,1).$model['EngineCount'].$model['WTC'].'.png';
3095
				$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']);
3096
			} else {
3097
				$allicao[$icao][':type'] = $allicao[$icao][':type'].'/'.$model['ModelFullName'];
3098
			}
3099
		}
3100
		foreach ($allicao as $icao => $airdata) {
3101
			try {
3102
				$sth->execute(array(':icao' => $icao));
3103
				$exist = $sth->fetchAll(PDO::FETCH_ASSOC);
3104
				if ($exist[0]['nb'] == 0) {
3105
					$sthins->execute($airdata);
3106
				} else {
3107
					$sthup->execute(array(':type' => $airdata[':type'],':icao' => $icao));
3108
				}
3109
			} catch(PDOException $e) {
3110
				return "error : ".$e->getMessage();
3111
			}
3112
		}
3113
		
3114
		/*
3115
		foreach ($all as $model) {
3116
			try {
3117
				$sth->execute(array(':icao' => $model['Designator']));
3118
				$exist = $sth->fetchAll(PDO::FETCH_ASSOC);
3119
				if ($exist[0]['nb'] == 0) {
3120
					echo 'ICAO: '.$model['Designator'].' is not available'."\n";
3121
					$aircraft_shadow = 'generic_'.substr($model['EngineType'],0,1).$model['EngineCount'].$model['WTC'].'.png';
3122
					$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']));
3123
				}
3124
			} catch(PDOException $e) {
3125
				return "error : ".$e->getMessage();
3126
			}
3127
		}
3128
		*/
3129
	}
3130
	
3131
	public static function update_notam() {
3132
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
3133
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
3134
		$Common = new Common();
3135
		date_default_timezone_set('UTC');
3136
		$query = 'TRUNCATE TABLE notam';
3137
		try {
3138
			$Connection = new Connection();
3139
			$sth = $Connection->db->prepare($query);
3140
                        $sth->execute();
3141
                } catch(PDOException $e) {
3142
                        return "error : ".$e->getMessage();
3143
                }
3144
3145
		$error = '';
3146
		if ($globalDebug) echo "Notam : Download...";
3147
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
3148
		if (file_exists($tmp_dir.'notam.rss')) {
3149
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
3150
			foreach ($notams['channel']['item'] as $notam) {
3151
				$title = explode(':',$notam['title']);
3152
				$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...
3153
				unset($title[0]);
3154
				$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...
3155
				$description = strip_tags($notam['description'],'<pre>');
3156
				preg_match(':^(.*?)<pre>:',$description,$match);
3157
				$q = explode('/',$match[1]);
3158
				$data['fir'] = $q[0];
3159
				$data['code'] = $q[1];
3160
				$ifrvfr = $q[2];
3161
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
3162
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
3163
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
3164
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
3165
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
3166
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
3167
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
3168
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
3169
				//$data['scope'] = $q[4];
3170
				$data['lower_limit'] = $q[5];
3171
				$data['upper_limit'] = $q[6];
3172
				$latlonrad = $q[7];
3173
				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...
3174
				$latitude = $Common->convertDec($las,'latitude');
3175
				$longitude = $Common->convertDec($lns,'longitude');
3176
				if ($lac == 'S') $latitude = '-'.$latitude;
3177
				if ($lnc == 'W') $longitude = '-'.$longitude;
3178
				$data['center_latitude'] = $latitude;
3179
				$data['center_longitude'] = $longitude;
3180
				$data['radius'] = intval($radius);
3181
				
3182
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
3183
				$data['text'] = $match[1];
3184
				preg_match(':</pre>(.*?)$:',$description,$match);
3185
				$fromto = $match[1];
3186
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
3187
				$fromall = trim($match[1]);
3188
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
3189
				$from = trim($match[1]);
3190
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
3191
				preg_match('#TO:(.*?)$#',$fromto,$match);
3192
				$toall = trim($match[1]);
3193
				if (!preg_match(':Permanent:',$toall)) {
3194
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
3195
					$to = trim($match[1]);
3196
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
3197
					$data['permanent'] = 0;
3198
				} else {
3199
				    $data['date_end'] = NULL;
3200
				    $data['permanent'] = 1;
3201
				}
3202
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
3203
				$NOTAM = new NOTAM();
3204
				$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']);
3205
				unset($data);
3206
			} 
3207
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
3208
		if ($error != '') {
3209
			return $error;
3210
		} elseif ($globalDebug) echo "Done\n";
3211
		return '';
3212
	}
3213
	
3214
	public static function create_airspace() {
3215
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
3216
		$Connection = new Connection();
3217
		if ($Connection->tableExists('airspace')) {
3218
			if ($globalDBdriver == 'mysql') {
3219
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
3220
			} else {
3221
				$query = 'DROP TABLE airspace';
3222
			}
3223
			try {
3224
				$Connection = new Connection();
3225
				$sth = $Connection->db->prepare($query);
3226
				$sth->execute();
3227
			} catch(PDOException $e) {
3228
				return "error : ".$e->getMessage();
3229
			}
3230
		}
3231
		$Common = new Common();
3232
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
3233
		$airspace_json = json_decode($airspace_lst,true);
3234
		foreach ($airspace_json['records'] as $airspace) {
3235
			if ($globalDebug) echo $airspace['name']."...\n";
3236
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
3237
			if (file_exists($tmp_dir.$airspace['name'])) {
3238
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
3239
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
3240
				if ($globalDBdriver == 'mysql') {
3241
					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'].'"');
3242
				} else {
3243
					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'].'"');
3244
				}
3245
			}
3246
		}
3247
	}
3248
	
3249
	public static function fix_icaotype() {
3250
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
3251
		$Spotter = new Spotter();
3252
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
3253
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
3254
			try {
3255
				$Connection = new Connection();
3256
				$sth = $Connection->db->prepare($query);
3257
				$sth->execute(array(':new' => $new, ':old' => $old));
3258
			} catch(PDOException $e) {
3259
				return "error : ".$e->getMessage();
3260
			}
3261
		}
3262
	}
3263
3264
	public static function check_last_update() {
3265
		global $globalDBdriver;
3266
		if ($globalDBdriver == 'mysql') {
3267
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3268
		} else {
3269
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3270
		}
3271
		try {
3272
			$Connection = new Connection();
3273
			$sth = $Connection->db->prepare($query);
3274
                        $sth->execute();
3275
                } catch(PDOException $e) {
3276
                        return "error : ".$e->getMessage();
3277
                }
3278
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3279
                if ($row['nb'] > 0) return false;
3280
                else return true;
3281
	}
3282
3283
	public static function insert_last_update() {
3284
		$query = "DELETE FROM config WHERE name = 'last_update_db';
3285
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
3286
		try {
3287
			$Connection = new Connection();
3288
			$sth = $Connection->db->prepare($query);
3289
                        $sth->execute();
3290
                } catch(PDOException $e) {
3291
                        return "error : ".$e->getMessage();
3292
                }
3293
	}
3294
3295
	public static function check_airspace_version($version) {
3296
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
3297
		try {
3298
			$Connection = new Connection();
3299
			$sth = $Connection->db->prepare($query);
3300
                        $sth->execute(array(':version' => $version));
3301
                } catch(PDOException $e) {
3302
                        return "error : ".$e->getMessage();
3303
                }
3304
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3305
                if ($row['nb'] > 0) return true;
3306
                else return false;
3307
	}
3308
3309
	public static function check_geoid_version($version) {
3310
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'geoid_version' AND value = :version";
3311
		try {
3312
			$Connection = new Connection();
3313
			$sth = $Connection->db->prepare($query);
3314
                        $sth->execute(array(':version' => $version));
3315
                } catch(PDOException $e) {
3316
                        return "error : ".$e->getMessage();
3317
                }
3318
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3319
                if ($row['nb'] > 0) return true;
3320
                else return false;
3321
	}
3322
3323
	public static function check_marine_identity_version($version) {
3324
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'marine_identity_version' AND value = :version";
3325
		try {
3326
			$Connection = new Connection();
3327
			$sth = $Connection->db->prepare($query);
3328
			$sth->execute(array(':version' => $version));
3329
		} catch(PDOException $e) {
3330
			return "error : ".$e->getMessage();
3331
		}
3332
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3333
		if ($row['nb'] > 0) return true;
3334
		else return false;
3335
	}
3336
3337
	public static function check_satellite_version($version) {
3338
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'satellite_version' AND value = :version";
3339
		try {
3340
			$Connection = new Connection();
3341
			$sth = $Connection->db->prepare($query);
3342
			$sth->execute(array(':version' => $version));
3343
		} catch(PDOException $e) {
3344
			return "error : ".$e->getMessage();
3345
		}
3346
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3347
		if ($row['nb'] > 0) return true;
3348
		else return false;
3349
	}
3350
	public static function check_diagrams_version($version) {
3351
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'diagrams_version' AND value = :version";
3352
		try {
3353
			$Connection = new Connection();
3354
			$sth = $Connection->db->prepare($query);
3355
			$sth->execute(array(':version' => $version));
3356
		} catch(PDOException $e) {
3357
			return "error : ".$e->getMessage();
3358
		}
3359
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3360
		if ($row['nb'] > 0) return true;
3361
		else return false;
3362
	}
3363
3364
	public static function check_airlines_version($version) {
3365
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airlines_version' AND value = :version";
3366
		try {
3367
			$Connection = new Connection();
3368
			$sth = $Connection->db->prepare($query);
3369
			$sth->execute(array(':version' => $version));
3370
		} catch(PDOException $e) {
3371
			return "error : ".$e->getMessage();
3372
		}
3373
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3374
		if ($row['nb'] > 0) return true;
3375
		else return false;
3376
	}
3377
3378
	public static function check_notam_version($version) {
3379
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'notam_version' AND value = :version";
3380
		try {
3381
			$Connection = new Connection();
3382
			$sth = $Connection->db->prepare($query);
3383
			$sth->execute(array(':version' => $version));
3384
		} catch(PDOException $e) {
3385
			return "error : ".$e->getMessage();
3386
		}
3387
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3388
		if ($row['nb'] > 0) return true;
3389
		else return false;
3390
	}
3391
3392
	public static function insert_airlines_version($version) {
3393
		$query = "DELETE FROM config WHERE name = 'airlines_version';
3394
			INSERT INTO config (name,value) VALUES ('airlines_version',:version);";
3395
		try {
3396
			$Connection = new Connection();
3397
			$sth = $Connection->db->prepare($query);
3398
			$sth->execute(array(':version' => $version));
3399
		} catch(PDOException $e) {
3400
			return "error : ".$e->getMessage();
3401
		}
3402
	}
3403
3404
	public static function insert_notam_version($version) {
3405
		$query = "DELETE FROM config WHERE name = 'notam_version';
3406
			INSERT INTO config (name,value) VALUES ('notam_version',:version);";
3407
		try {
3408
			$Connection = new Connection();
3409
			$sth = $Connection->db->prepare($query);
3410
			$sth->execute(array(':version' => $version));
3411
		} catch(PDOException $e) {
3412
			return "error : ".$e->getMessage();
3413
		}
3414
	}
3415
3416
	public static function insert_airspace_version($version) {
3417
		$query = "DELETE FROM config WHERE name = 'airspace_version';
3418
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
3419
		try {
3420
			$Connection = new Connection();
3421
			$sth = $Connection->db->prepare($query);
3422
			$sth->execute(array(':version' => $version));
3423
		} catch(PDOException $e) {
3424
			return "error : ".$e->getMessage();
3425
		}
3426
	}
3427
	
3428
	public static function insert_geoid_version($version) {
3429
		$query = "DELETE FROM config WHERE name = 'geoid_version';
3430
			INSERT INTO config (name,value) VALUES ('geoid_version',:version);";
3431
		try {
3432
			$Connection = new Connection();
3433
			$sth = $Connection->db->prepare($query);
3434
                        $sth->execute(array(':version' => $version));
3435
                } catch(PDOException $e) {
3436
                        return "error : ".$e->getMessage();
3437
                }
3438
	}
3439
3440
	public static function insert_marine_identity_version($version) {
3441
		$query = "DELETE FROM config WHERE name = 'marine_identity_version';
3442
			INSERT INTO config (name,value) VALUES ('marine_identity_version',:version);";
3443
		try {
3444
			$Connection = new Connection();
3445
			$sth = $Connection->db->prepare($query);
3446
			$sth->execute(array(':version' => $version));
3447
		} catch(PDOException $e) {
3448
			return "error : ".$e->getMessage();
3449
		}
3450
	}
3451
3452
	public static function insert_satellite_version($version) {
3453
		$query = "DELETE FROM config WHERE name = 'satellite_version';
3454
			INSERT INTO config (name,value) VALUES ('satellite_version',:version);";
3455
		try {
3456
			$Connection = new Connection();
3457
			$sth = $Connection->db->prepare($query);
3458
			$sth->execute(array(':version' => $version));
3459
		} catch(PDOException $e) {
3460
			return "error : ".$e->getMessage();
3461
		}
3462
	}
3463
	public static function insert_diagrams_version($version) {
3464
		$query = "DELETE FROM config WHERE name = 'diagrams_version';
3465
			INSERT INTO config (name,value) VALUES ('diagrams_version',:version);";
3466
		try {
3467
			$Connection = new Connection();
3468
			$sth = $Connection->db->prepare($query);
3469
			$sth->execute(array(':version' => $version));
3470
		} catch(PDOException $e) {
3471
			return "error : ".$e->getMessage();
3472
		}
3473
	}
3474
3475
	public static function check_last_notam_update() {
3476
		global $globalDBdriver;
3477
		if ($globalDBdriver == 'mysql') {
3478
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
3479
		} else {
3480
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
3481
		}
3482
		try {
3483
			$Connection = new Connection();
3484
			$sth = $Connection->db->prepare($query);
3485
                        $sth->execute();
3486
                } catch(PDOException $e) {
3487
                        return "error : ".$e->getMessage();
3488
                }
3489
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3490
                if ($row['nb'] > 0) return false;
3491
                else return true;
3492
	}
3493
3494
	public static function insert_last_notam_update() {
3495
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
3496
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
3497
		try {
3498
			$Connection = new Connection();
3499
			$sth = $Connection->db->prepare($query);
3500
                        $sth->execute();
3501
                } catch(PDOException $e) {
3502
                        return "error : ".$e->getMessage();
3503
                }
3504
	}
3505
3506
	public static function check_last_airspace_update() {
3507
		global $globalDBdriver;
3508
		if ($globalDBdriver == 'mysql') {
3509
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3510
		} else {
3511
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3512
		}
3513
		try {
3514
			$Connection = new Connection();
3515
			$sth = $Connection->db->prepare($query);
3516
                        $sth->execute();
3517
                } catch(PDOException $e) {
3518
                        return "error : ".$e->getMessage();
3519
                }
3520
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3521
                if ($row['nb'] > 0) return false;
3522
                else return true;
3523
	}
3524
3525
	public static function insert_last_airspace_update() {
3526
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
3527
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
3528
		try {
3529
			$Connection = new Connection();
3530
			$sth = $Connection->db->prepare($query);
3531
                        $sth->execute();
3532
                } catch(PDOException $e) {
3533
                        return "error : ".$e->getMessage();
3534
                }
3535
	}
3536
3537
	public static function check_last_geoid_update() {
3538
		global $globalDBdriver;
3539
		if ($globalDBdriver == 'mysql') {
3540
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3541
		} else {
3542
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3543
		}
3544
		try {
3545
			$Connection = new Connection();
3546
			$sth = $Connection->db->prepare($query);
3547
                        $sth->execute();
3548
                } catch(PDOException $e) {
3549
                        return "error : ".$e->getMessage();
3550
                }
3551
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3552
                if ($row['nb'] > 0) return false;
3553
                else return true;
3554
	}
3555
3556
	public static function insert_last_geoid_update() {
3557
		$query = "DELETE FROM config WHERE name = 'last_update_geoid';
3558
			INSERT INTO config (name,value) VALUES ('last_update_geoid',NOW());";
3559
		try {
3560
			$Connection = new Connection();
3561
			$sth = $Connection->db->prepare($query);
3562
                        $sth->execute();
3563
                } catch(PDOException $e) {
3564
                        return "error : ".$e->getMessage();
3565
                }
3566
	}
3567
3568
	public static function check_last_owner_update() {
3569
		global $globalDBdriver;
3570
		if ($globalDBdriver == 'mysql') {
3571
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3572
		} else {
3573
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3574
		}
3575
		try {
3576
			$Connection = new Connection();
3577
			$sth = $Connection->db->prepare($query);
3578
			$sth->execute();
3579
		} catch(PDOException $e) {
3580
			return "error : ".$e->getMessage();
3581
		}
3582
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3583
		if ($row['nb'] > 0) return false;
3584
		else return true;
3585
	}
3586
3587
	public static function insert_last_owner_update() {
3588
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
3589
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
3590
		try {
3591
			$Connection = new Connection();
3592
			$sth = $Connection->db->prepare($query);
3593
			$sth->execute();
3594
		} catch(PDOException $e) {
3595
			return "error : ".$e->getMessage();
3596
		}
3597
	}
3598
3599
	public static function check_last_fires_update() {
3600
		global $globalDBdriver;
3601
		if ($globalDBdriver == 'mysql') {
3602
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_fires' AND value > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
3603
		} else {
3604
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_fires' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 HOUR'";
3605
		}
3606
		try {
3607
			$Connection = new Connection();
3608
			$sth = $Connection->db->prepare($query);
3609
			$sth->execute();
3610
		} catch(PDOException $e) {
3611
			return "error : ".$e->getMessage();
3612
		}
3613
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3614
		if ($row['nb'] > 0) return false;
3615
		else return true;
3616
	}
3617
3618
	public static function insert_last_fires_update() {
3619
		$query = "DELETE FROM config WHERE name = 'last_update_fires';
3620
			INSERT INTO config (name,value) VALUES ('last_update_fires',NOW());";
3621
		try {
3622
			$Connection = new Connection();
3623
			$sth = $Connection->db->prepare($query);
3624
			$sth->execute();
3625
		} catch(PDOException $e) {
3626
			return "error : ".$e->getMessage();
3627
		}
3628
	}
3629
3630
	public static function check_last_airlines_update() {
3631
		global $globalDBdriver;
3632
		if ($globalDBdriver == 'mysql') {
3633
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airlines_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3634
		} else {
3635
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airlines_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3636
		}
3637
		try {
3638
			$Connection = new Connection();
3639
			$sth = $Connection->db->prepare($query);
3640
			$sth->execute();
3641
		} catch(PDOException $e) {
3642
			return "error : ".$e->getMessage();
3643
		}
3644
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3645
		if ($row['nb'] > 0) return false;
3646
		else return true;
3647
	}
3648
3649
	public static function insert_last_airlines_update() {
3650
		$query = "DELETE FROM config WHERE name = 'last_update_airlines_db';
3651
			INSERT INTO config (name,value) VALUES ('last_update_airlines_db',NOW());";
3652
		try {
3653
			$Connection = new Connection();
3654
			$sth = $Connection->db->prepare($query);
3655
			$sth->execute();
3656
		} catch(PDOException $e) {
3657
			return "error : ".$e->getMessage();
3658
		}
3659
	}
3660
3661
	public static function check_last_schedules_update() {
3662
		global $globalDBdriver;
3663
		if ($globalDBdriver == 'mysql') {
3664
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
3665
		} else {
3666
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
3667
		}
3668
		try {
3669
			$Connection = new Connection();
3670
			$sth = $Connection->db->prepare($query);
3671
                        $sth->execute();
3672
                } catch(PDOException $e) {
3673
                        return "error : ".$e->getMessage();
3674
                }
3675
                $row = $sth->fetch(PDO::FETCH_ASSOC);
3676
                if ($row['nb'] > 0) return false;
3677
                else return true;
3678
	}
3679
3680
	public static function insert_last_schedules_update() {
3681
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
3682
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
3683
		try {
3684
			$Connection = new Connection();
3685
			$sth = $Connection->db->prepare($query);
3686
			$sth->execute();
3687
		} catch(PDOException $e) {
3688
			return "error : ".$e->getMessage();
3689
		}
3690
	}
3691
3692
	public static function check_last_tle_update() {
3693
		global $globalDBdriver;
3694
		if ($globalDBdriver == 'mysql') {
3695
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3696
		} else {
3697
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3698
		}
3699
		try {
3700
			$Connection = new Connection();
3701
			$sth = $Connection->db->prepare($query);
3702
			$sth->execute();
3703
		} catch(PDOException $e) {
3704
			return "error : ".$e->getMessage();
3705
		}
3706
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3707
		if ($row['nb'] > 0) return false;
3708
		else return true;
3709
	}
3710
3711
	public static function insert_last_tle_update() {
3712
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
3713
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
3714
		try {
3715
			$Connection = new Connection();
3716
			$sth = $Connection->db->prepare($query);
3717
			$sth->execute();
3718
		} catch(PDOException $e) {
3719
			return "error : ".$e->getMessage();
3720
		}
3721
	}
3722
3723
	public static function check_last_ucsdb_update() {
3724
		global $globalDBdriver;
3725
		if ($globalDBdriver == 'mysql') {
3726
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
3727
		} else {
3728
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_ucsdb' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 MONTH'";
3729
		}
3730
		try {
3731
			$Connection = new Connection();
3732
			$sth = $Connection->db->prepare($query);
3733
			$sth->execute();
3734
		} catch(PDOException $e) {
3735
			return "error : ".$e->getMessage();
3736
		}
3737
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3738
		if ($row['nb'] > 0) return false;
3739
		else return true;
3740
	}
3741
3742
	public static function insert_last_ucsdb_update() {
3743
		$query = "DELETE FROM config WHERE name = 'last_update_ucsdb';
3744
			INSERT INTO config (name,value) VALUES ('last_update_ucsdb',NOW());";
3745
		try {
3746
			$Connection = new Connection();
3747
			$sth = $Connection->db->prepare($query);
3748
			$sth->execute();
3749
		} catch(PDOException $e) {
3750
			return "error : ".$e->getMessage();
3751
		}
3752
	}
3753
3754
	public static function check_last_celestrak_update() {
3755
		global $globalDBdriver;
3756
		if ($globalDBdriver == 'mysql') {
3757
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3758
		} else {
3759
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_celestrak' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3760
		}
3761
		try {
3762
			$Connection = new Connection();
3763
			$sth = $Connection->db->prepare($query);
3764
			$sth->execute();
3765
		} catch(PDOException $e) {
3766
			return "error : ".$e->getMessage();
3767
		}
3768
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3769
		if ($row['nb'] > 0) return false;
3770
		else return true;
3771
	}
3772
3773
	public static function insert_last_celestrak_update() {
3774
		$query = "DELETE FROM config WHERE name = 'last_update_celestrak';
3775
			INSERT INTO config (name,value) VALUES ('last_update_celestrak',NOW());";
3776
		try {
3777
			$Connection = new Connection();
3778
			$sth = $Connection->db->prepare($query);
3779
			$sth->execute();
3780
		} catch(PDOException $e) {
3781
			return "error : ".$e->getMessage();
3782
		}
3783
	}
3784
3785
	public static function check_last_marine_identity_update() {
3786
		global $globalDBdriver;
3787
		if ($globalDBdriver == 'mysql') {
3788
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
3789
		} else {
3790
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
3791
		}
3792
		try {
3793
			$Connection = new Connection();
3794
			$sth = $Connection->db->prepare($query);
3795
			$sth->execute();
3796
		} catch(PDOException $e) {
3797
			return "error : ".$e->getMessage();
3798
		}
3799
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3800
		if ($row['nb'] > 0) return false;
3801
		else return true;
3802
	}
3803
3804
	public static function check_last_satellite_update() {
3805
		global $globalDBdriver;
3806
		if ($globalDBdriver == 'mysql') {
3807
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
3808
		} else {
3809
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_satellite' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
3810
		}
3811
		try {
3812
			$Connection = new Connection();
3813
			$sth = $Connection->db->prepare($query);
3814
			$sth->execute();
3815
		} catch(PDOException $e) {
3816
			return "error : ".$e->getMessage();
3817
		}
3818
		$row = $sth->fetch(PDO::FETCH_ASSOC);
3819
		if ($row['nb'] > 0) return false;
3820
		else return true;
3821
	}
3822
3823
	public static function insert_last_marine_identity_update() {
3824
		$query = "DELETE FROM config WHERE name = 'last_update_marine_identity';
3825
			INSERT INTO config (name,value) VALUES ('last_update_marine_identity',NOW());";
3826
		try {
3827
			$Connection = new Connection();
3828
			$sth = $Connection->db->prepare($query);
3829
			$sth->execute();
3830
		} catch(PDOException $e) {
3831
			return "error : ".$e->getMessage();
3832
		}
3833
	}
3834
3835
	public static function insert_last_satellite_update() {
3836
		$query = "DELETE FROM config WHERE name = 'last_update_satellite';
3837
			INSERT INTO config (name,value) VALUES ('last_update_satellite',NOW());";
3838
		try {
3839
			$Connection = new Connection();
3840
			$sth = $Connection->db->prepare($query);
3841
			$sth->execute();
3842
		} catch(PDOException $e) {
3843
			return "error : ".$e->getMessage();
3844
		}
3845
	}
3846
3847
	public static function delete_duplicatemodes() {
3848
		global $globalDBdriver;
3849
		if ($globalDBdriver == 'mysql') {
3850
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
3851
		} else {
3852
			$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'";
3853
		}
3854
		try {
3855
			$Connection = new Connection();
3856
			$sth = $Connection->db->prepare($query);
3857
                        $sth->execute();
3858
                } catch(PDOException $e) {
3859
                        return "error : ".$e->getMessage();
3860
                }
3861
	}
3862
	public static function delete_duplicateowner() {
3863
		global $globalDBdriver;
3864
		if ($globalDBdriver == 'mysql') {
3865
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
3866
		} else {
3867
			$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)";
3868
		}
3869
		try {
3870
			$Connection = new Connection();
3871
			$sth = $Connection->db->prepare($query);
3872
                        $sth->execute();
3873
                } catch(PDOException $e) {
3874
                        return "error : ".$e->getMessage();
3875
                }
3876
	}
3877
	
3878
	public static function update_all() {
3879
		global $globalMasterServer, $globalMasterSource;
3880
		if (!isset($globalMasterServer) || !$globalMasterServer) {
3881
			if (isset($globalMasterSource) && $globalMasterSource) {
3882
				echo update_db::update_routes();
3883
				echo update_db::update_translation();
3884
				//echo update_db::update_notam_fam();
3885
				echo update_db::update_ModeS();
3886
				//echo update_db::update_ModeS_flarm();
3887
				echo update_db::update_ModeS_ogn();
3888
				echo update_db::update_ModeS_faa();
3889
				echo update_db::fix_icaotype();
3890
				echo update_db::update_banned_fam();
3891
				echo update_db::update_block_fam();
3892
				echo update_db::update_diagrams();
0 ignored issues
show
Bug introduced by
The method update_diagrams() does not exist on update_db. Did you maybe mean update_diagrams_fam()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
3893
				//echo update_db::update_celestrak();
3894
				//echo update_db::delete_duplicatemodes();
3895
			} else {
3896
				//echo update_db::update_routes();
3897
				echo update_db::update_routes_fam();
3898
				//echo update_db::update_translation();
3899
				echo update_db::update_translation_fam();
3900
				//echo update_db::update_notam_fam();
3901
				//echo update_db::update_ModeS();
3902
				echo update_db::update_ModeS_fam();
3903
				//echo update_db::update_ModeS_flarm();
3904
				echo update_db::update_ModeS_ogn();
3905
				//echo update_db::delete_duplicatemodes();
3906
				echo update_db::update_banned_fam();
3907
				echo update_db::update_block_fam();
3908
				echo update_db::update_diagrams();
0 ignored issues
show
Bug introduced by
The method update_diagrams() does not exist on update_db. Did you maybe mean update_diagrams_fam()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
3909
			}
3910
		}
3911
	}
3912
}
3913
3914
//echo update_db::update_airports();
3915
//echo update_db::translation();
3916
//echo update_db::update_waypoints();
3917
//echo update_db::update_airspace();
3918
//echo update_db::update_notam();
3919
//echo update_db::update_ivao();
3920
//echo update_db::update_ModeS_flarm();
3921
//echo update_db::update_ModeS_ogn();
3922
//echo update_db::update_aircraft();
3923
//$update_db = new update_db();
3924
//echo update_db::update_owner();
3925
//update_db::update_translation_fam();
3926
//echo update_db::update_routes();
3927
//update_db::update_models();
3928
//echo $update_db::update_skyteam();
3929
//echo $update_db::update_tle();
3930
//echo update_db::update_notam_fam();
3931
//echo update_db::create_airspace();
3932
//echo update_db::update_ModeS();
3933
//echo update_db::update_ModeS_fam();
3934
//echo update_db::update_routes_fam();
3935
//echo update_db::update_ModeS_faa();
3936
//echo update_db::update_banned_fam();
3937
//echo update_db::modes_faa();
3938
//echo update_db::update_owner_fam();
3939
//echo update_db::delete_duplicateowner();
3940
//echo update_db::fix_icaotype();
3941
//echo update_db::satellite_ucsdb('tmp/UCS_Satellite_Database_officialname_1-1-17.txt');
3942
//echo update_db::update_celestrak();
3943
//echo update_db::update_aircraft();
3944
//echo update_db::update_block_fam();
3945
//echo update_db::update_diagrams_fam();
3946
3947
?>
3948