Completed
Push — master ( e3409a...79a372 )
by Yannick
05:31
created

update_db::delete_duplicateowner()   A

Complexity

Conditions 3
Paths 8

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 8
nop 0
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
//require_once('libs/simple_html_dom.php');
3
require(dirname(__FILE__).'/../require/settings.php');
4
require_once(dirname(__FILE__).'/../require/class.Common.php');
5
require_once(dirname(__FILE__).'/../require/class.Connection.php');
6
7
$tmp_dir = dirname(__FILE__).'/tmp/';
8
//$globalDebug = true;
9
//$globalTransaction = true;
10
class update_db {
11
	public static $db_sqlite;
12
13
	public static function download($url, $file, $referer = '') {
14
		$fp = fopen($file, 'w+');
15
		$ch = curl_init();
16
		curl_setopt($ch, CURLOPT_URL, $url);
17
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
18
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
19
		if ($referer != '') curl_setopt($ch, CURLOPT_REFERER, $referer);
20
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
21
		curl_setopt($ch, CURLOPT_FILE, $fp);
22
		curl_exec($ch);
23
		curl_close($ch);
24
		fclose($fp);
25
	}
26
27
	public static function gunzip($in_file,$out_file_name = '') {
28
		//echo $in_file.' -> '.$out_file_name."\n";
29
		$buffer_size = 4096; // read 4kb at a time
30
		if ($out_file_name == '') $out_file_name = str_replace('.gz', '', $in_file); 
31
		if ($in_file != '' && file_exists($in_file)) {
32
			// PHP version of Ubuntu use gzopen64 instead of gzopen
33
			if (function_exists('gzopen')) $file = gzopen($in_file,'rb');
34
			elseif (function_exists('gzopen64')) $file = gzopen64($in_file,'rb');
35
			else {
36
				echo 'gzopen not available';
37
				die;
38
			}
39
			$out_file = fopen($out_file_name, 'wb'); 
40
			while(!gzeof($file)) {
41
				fwrite($out_file, gzread($file, $buffer_size));
42
			}  
43
			fclose($out_file);
44
			gzclose($file);
45
		}
46
	}
47
48
	public static function unzip($in_file) {
49
		if ($in_file != '' && file_exists($in_file)) {
50
			$path = pathinfo(realpath($in_file), PATHINFO_DIRNAME);
51
			$zip = new ZipArchive;
52
			$res = $zip->open($in_file);
53
			if ($res === TRUE) {
54
				$zip->extractTo($path);
55
				$zip->close();
56
			} else return false;
57
		} else return false;
58
	}
59
	
60
	public static function connect_sqlite($database) {
61
		try {
62
			self::$db_sqlite = new PDO('sqlite:'.$database);
63
			self::$db_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
64
		} catch(PDOException $e) {
65
			return "error : ".$e->getMessage();
66
		}
67
	}
68
	
69
	public static function retrieve_route_sqlite_to_dest($database_file) {
70
		global $globalDebug, $globalTransaction;
71
		//$query = 'TRUNCATE TABLE routes';
72
		if ($globalDebug) echo " - Delete previous routes from DB -";
73
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
74
		$Connection = new Connection();
75
		try {
76
			//$Connection = new Connection();
77
			$sth = $Connection->db->prepare($query);
78
                        $sth->execute(array(':source' => $database_file));
79
                } catch(PDOException $e) {
80
                        return "error : ".$e->getMessage();
81
                }
82
83
    		if ($globalDebug) echo " - Add routes to DB -";
84
    		update_db::connect_sqlite($database_file);
85
		//$query = 'select Route.RouteID, Route.callsign, operator.Icao AS operator_icao, FromAir.Icao AS FromAirportIcao, ToAir.Icao AS ToAirportIcao from Route inner join operator ON Route.operatorId = operator.operatorId LEFT JOIN Airport AS FromAir ON route.FromAirportId = FromAir.AirportId LEFT JOIN Airport AS ToAir ON ToAir.AirportID = route.ToAirportID';
86
		$query = "select Route.RouteID, Route.callsign, operator.Icao AS operator_icao, FromAir.Icao AS FromAirportIcao, ToAir.Icao AS ToAirportIcao, rstp.allstop AS AllStop from Route inner join operator ON Route.operatorId = operator.operatorId LEFT JOIN Airport AS FromAir ON route.FromAirportId = FromAir.AirportId LEFT JOIN Airport AS ToAir ON ToAir.AirportID = route.ToAirportID LEFT JOIN (select RouteId,GROUP_CONCAT(icao,' ') as allstop from routestop left join Airport as air ON routestop.AirportId = air.AirportID group by RouteID) AS rstp ON Route.RouteID = rstp.RouteID";
87
		try {
88
                        $sth = update_db::$db_sqlite->prepare($query);
89
                        $sth->execute();
90
                } catch(PDOException $e) {
91
                        return "error : ".$e->getMessage();
92
                }
93
		//$query_dest = 'INSERT INTO routes (`RouteID`,`CallSign`,`Operator_ICAO`,`FromAirport_ICAO`,`ToAirport_ICAO`,`RouteStop`,`Source`) VALUES (:RouteID, :CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
94
		$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,ToAirport_ICAO,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
95
		$Connection = new Connection();
96
		$sth_dest = $Connection->db->prepare($query_dest);
97
		try {
98
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
99
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
100
				//$query_dest_values = array(':RouteID' => $values['RouteId'],':CallSign' => $values['Callsign'],':Operator_ICAO' => $values['operator_icao'],':FromAirport_ICAO' => $values['FromAirportIcao'],':ToAirport_ICAO' => $values['ToAirportIcao'],':routestop' => $values['AllStop'],':source' => $database_file);
101
				$query_dest_values = array(':CallSign' => $values['Callsign'],':Operator_ICAO' => $values['operator_icao'],':FromAirport_ICAO' => $values['FromAirportIcao'],':ToAirport_ICAO' => $values['ToAirportIcao'],':routestop' => $values['AllStop'],':source' => $database_file);
102
				$sth_dest->execute($query_dest_values);
103
            		}
104
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
105
		} catch(PDOException $e) {
106
			if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
107
			return "error : ".$e->getMessage();
108
		}
109
                return '';
110
	}
111
	public static function retrieve_route_oneworld($database_file) {
112
		global $globalDebug, $globalTransaction;
113
		//$query = 'TRUNCATE TABLE routes';
114
		if ($globalDebug) echo " - Delete previous routes from DB -";
115
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
116
		$Connection = new Connection();
117
		try {
118
			//$Connection = new Connection();
119
			$sth = $Connection->db->prepare($query);
120
                        $sth->execute(array(':source' => 'oneworld'));
121
                } catch(PDOException $e) {
122
                        return "error : ".$e->getMessage();
123
                }
124
125
    		if ($globalDebug) echo " - Add routes to DB -";
126
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
127
		$Spotter = new Spotter();
128
		if ($fh = fopen($database_file,"r")) {
129
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
130
			$Connection = new Connection();
131
			$sth_dest = $Connection->db->prepare($query_dest);
132
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
133
			while (!feof($fh)) {
134
				$line = fgetcsv($fh,9999,',');
135
				if ($line[0] != '') {
136
					if (($line[2] == '-' || ($line[2] != '-' && (strtotime($line[2]) > time()))) && ($line[3] == '-' || ($line[3] != '-' && (strtotime($line[3]) < time())))) {
137
						try {
138
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[7]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[5],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[6],':routestop' => '',':source' => 'oneworld');
139
							$sth_dest->execute($query_dest_values);
140
						} catch(PDOException $e) {
141
							if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
142
							return "error : ".$e->getMessage();
143
						}
144
					}
145
				}
146
			}
147
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
148
		}
149
                return '';
150
	}
151
	
152
	public static function retrieve_route_skyteam($database_file) {
153
		global $globalDebug, $globalTransaction;
154
		//$query = 'TRUNCATE TABLE routes';
155
		if ($globalDebug) echo " - Delete previous routes from DB -";
156
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
157
		$Connection = new Connection();
158
		try {
159
			//$Connection = new Connection();
160
			$sth = $Connection->db->prepare($query);
161
                        $sth->execute(array(':source' => 'skyteam'));
162
                } catch(PDOException $e) {
163
                        return "error : ".$e->getMessage();
164
                }
165
166
    		if ($globalDebug) echo " - Add routes to DB -";
167
168
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
169
		$Spotter = new Spotter();
170
		if ($fh = fopen($database_file,"r")) {
171
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
172
			$Connection = new Connection();
173
			$sth_dest = $Connection->db->prepare($query_dest);
174
			try {
175
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
176
				while (!feof($fh)) {
177
					$line = fgetcsv($fh,9999,',');
178
					if ($line[0] != '') {
179
						$datebe = explode('  -  ',$line[2]);
180
						if (strtotime($datebe[0]) > time() && strtotime($datebe[1]) < time()) {
181
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[6]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[4],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[5],':routestop' => '',':source' => 'skyteam');
182
							$sth_dest->execute($query_dest_values);
183
						}
184
					}
185
				}
186
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
187
			} catch(PDOException $e) {
188
				if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
189
				return "error : ".$e->getMessage();
190
			}
191
		}
192
                return '';
193
	}
194
	public static function retrieve_modes_sqlite_to_dest($database_file) {
195
		global $globalTransaction;
196
		//$query = 'TRUNCATE TABLE aircraft_modes';
197
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
198
		try {
199
			$Connection = new Connection();
200
			$sth = $Connection->db->prepare($query);
201
                        $sth->execute(array(':source' => $database_file));
202
                } catch(PDOException $e) {
203
                        return "error : ".$e->getMessage();
204
                }
205
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
206
		try {
207
			$Connection = new Connection();
208
			$sth = $Connection->db->prepare($query);
209
                        $sth->execute(array(':source' => $database_file));
210
                } catch(PDOException $e) {
211
                        return "error : ".$e->getMessage();
212
                }
213
214
    		update_db::connect_sqlite($database_file);
215
		$query = 'select * from Aircraft';
216
		try {
217
                        $sth = update_db::$db_sqlite->prepare($query);
218
                        $sth->execute();
219
                } catch(PDOException $e) {
220
                        return "error : ".$e->getMessage();
221
                }
222
		//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
223
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
224
		
225
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
226
		
227
		$Connection = new Connection();
228
		$sth_dest = $Connection->db->prepare($query_dest);
229
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
230
		try {
231
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
232
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
233
			//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
234
				if ($values['UserString4'] == 'M') $type = 'military';
235
				else $type = null;
236
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
237
				$sth_dest->execute($query_dest_values);
238
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
239
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
240
				    $sth_dest_owner->execute($query_dest_owner_values);
241
				}
242
            		}
243
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
244
		} catch(PDOException $e) {
245
			return "error : ".$e->getMessage();
246
		}
247
248
		// Remove data already in DB from ACARS
249
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
250
		try {
251
			$Connection = new Connection();
252
			$sth = $Connection->db->prepare($query);
253
                        $sth->execute(array(':source' => $database_file));
254
                } catch(PDOException $e) {
255
                        return "error : ".$e->getMessage();
256
                }
257
		return '';
258
	}
259
260
	public static function retrieve_modes_flarmnet($database_file) {
261
		global $globalTransaction;
262
		$Common = new Common();
263
		//$query = 'TRUNCATE TABLE aircraft_modes';
264
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
265
		try {
266
			$Connection = new Connection();
267
			$sth = $Connection->db->prepare($query);
268
                        $sth->execute(array(':source' => $database_file));
269
                } catch(PDOException $e) {
270
                        return "error : ".$e->getMessage();
271
                }
272
		
273
		if ($fh = fopen($database_file,"r")) {
274
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
275
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
276
		
277
			$Connection = new Connection();
278
			$sth_dest = $Connection->db->prepare($query_dest);
279
			try {
280
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
281
            			while (!feof($fh)) {
282
            				$values = array();
283
            				$line = $Common->hex2str(fgets($fh,9999));
284
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
285
            				$values['ModeS'] = substr($line,0,6);
286
            				$values['Registration'] = trim(substr($line,69,6));
287
            				$aircraft_name = trim(substr($line,48,6));
288
            				// Check if we can find ICAO, else set it to GLID
289
            				$aircraft_name_split = explode(' ',$aircraft_name);
290
            				$search_more = '';
291
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
292
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
293
            				$sth_search = $Connection->db->prepare($query_search);
294
					try {
295
                                    		$sth_search->execute();
296
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
297
	            				//if (count($result) > 0) {
298
	            				if (isset($result['icao']) && $result['icao'] != '') {
299
	            				    $values['ICAOTypeCode'] = $result['icao'];
300
	            				} 
301
					} catch(PDOException $e) {
302
						return "error : ".$e->getMessage();
303
					}
304
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
305
					// Add data to db
306
					if ($values['Registration'] != '' && $values['Registration'] != '0000') {
307
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
308
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
309
						//print_r($query_dest_values);
310
						$sth_dest->execute($query_dest_values);
311
					}
312
				}
313
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
314
			} catch(PDOException $e) {
315
				return "error : ".$e->getMessage();
316
			}
317
		}
318
319
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
320
		try {
321
			$Connection = new Connection();
322
			$sth = $Connection->db->prepare($query);
323
                        $sth->execute(array(':source' => $database_file));
324
                } catch(PDOException $e) {
325
                        return "error : ".$e->getMessage();
326
                }
327
		return '';
328
	}
329
330
	public static function retrieve_modes_ogn($database_file) {
331
		global $globalTransaction;
332
		//$query = 'TRUNCATE TABLE aircraft_modes';
333
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
334
		try {
335
			$Connection = new Connection();
336
			$sth = $Connection->db->prepare($query);
337
                        $sth->execute(array(':source' => $database_file));
338
                } catch(PDOException $e) {
339
                        return "error : ".$e->getMessage();
340
                }
341
		
342
		if ($fh = fopen($database_file,"r")) {
343
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
344
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
345
		
346
			$Connection = new Connection();
347
			$sth_dest = $Connection->db->prepare($query_dest);
348
			try {
349
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
350
				$tmp = fgetcsv($fh,9999,',',"'");
0 ignored issues
show
Unused Code introduced by
$tmp is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
351
            			while (!feof($fh)) {
352
            				$line = fgetcsv($fh,9999,',',"'");
353
            				
354
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
355
					//print_r($line);
356
            				$values['ModeS'] = $line[1];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$values was never initialized. Although not strictly required by PHP, it is generally a good practice to add $values = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
357
            				$values['Registration'] = $line[3];
0 ignored issues
show
Bug introduced by
The variable $values does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
358
            				$aircraft_name = $line[2];
359
            				// Check if we can find ICAO, else set it to GLID
360
            				$aircraft_name_split = explode(' ',$aircraft_name);
361
            				$search_more = '';
362
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
363
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
364
            				$sth_search = $Connection->db->prepare($query_search);
365
					try {
366
                                    		$sth_search->execute();
367
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
368
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
369
					} catch(PDOException $e) {
370
						return "error : ".$e->getMessage();
371
					}
372
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
373
					// Add data to db
374
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
375
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
376
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
377
						//print_r($query_dest_values);
378
						$sth_dest->execute($query_dest_values);
379
					}
380
				}
381
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
382
			} catch(PDOException $e) {
383
				return "error : ".$e->getMessage();
384
			}
385
		}
386
387
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
388
		try {
389
			$Connection = new Connection();
390
			$sth = $Connection->db->prepare($query);
391
                        $sth->execute(array(':source' => $database_file));
392
                } catch(PDOException $e) {
393
                        return "error : ".$e->getMessage();
394
                }
395
		return '';
396
	}
397
398
	public static function retrieve_owner($database_file,$country = 'F') {
399
		global $globalTransaction;
400
		//$query = 'TRUNCATE TABLE aircraft_modes';
401
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
402
		try {
403
			$Connection = new Connection();
404
			$sth = $Connection->db->prepare($query);
405
                        $sth->execute(array(':source' => $database_file));
406
                } catch(PDOException $e) {
407
                        return "error : ".$e->getMessage();
408
                }
409
		
410
		if ($fh = fopen($database_file,"r")) {
411
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
412
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
413
		
414
			$Connection = new Connection();
415
			$sth_dest = $Connection->db->prepare($query_dest);
416
			try {
417
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
418
				$tmp = fgetcsv($fh,9999,',','"');
0 ignored issues
show
Unused Code introduced by
$tmp is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
419
            			while (!feof($fh)) {
420
            				$line = fgetcsv($fh,9999,',','"');
421
            				$values = array();
422
            				//print_r($line);
423
            				if ($country == 'F') {
424
            				    $values['registration'] = $line[0];
425
            				    $values['base'] = $line[4];
426
            				    $values['owner'] = $line[5];
427
            				    if ($line[6] == '') $values['date_first_reg'] = null;
428
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
429
					    $values['cancel'] = $line[7];
430
					} elseif ($country == 'EI') {
431
					    // TODO : add modeS & reg to aircraft_modes
432
            				    $values['registration'] = $line[0];
433
            				    $values['base'] = $line[3];
434
            				    $values['owner'] = $line[2];
435
            				    if ($line[1] == '') $values['date_first_reg'] = null;
436
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
437
					    $values['cancel'] = '';
438
					} elseif ($country == 'HB') {
439
					    // TODO : add modeS & reg to aircraft_modes
440
            				    $values['registration'] = $line[0];
441
            				    $values['base'] = null;
442
            				    $values['owner'] = $line[5];
443
            				    $values['date_first_reg'] = null;
444
					    $values['cancel'] = '';
445
					} elseif ($country == 'OK') {
446
					    // TODO : add modeS & reg to aircraft_modes
447
            				    $values['registration'] = $line[3];
448
            				    $values['base'] = null;
449
            				    $values['owner'] = $line[5];
450
            				    if ($line[18] == '') $values['date_first_reg'] = null;
451
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
452
					    $values['cancel'] = '';
453
					} elseif ($country == 'VH') {
454
					    // TODO : add modeS & reg to aircraft_modes
455
            				    $values['registration'] = $line[0];
456
            				    $values['base'] = null;
457
            				    $values['owner'] = $line[12];
458
            				    if ($line[28] == '') $values['date_first_reg'] = null;
459
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
460
461
					    $values['cancel'] = $line[39];
462
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
463
            				    $values['registration'] = $line[0];
464
            				    $values['base'] = null;
465
            				    $values['owner'] = $line[4];
466
            				    $values['date_first_reg'] = null;
467
					    $values['cancel'] = '';
468
					} elseif ($country == 'CC') {
469
            				    $values['registration'] = $line[0];
470
            				    $values['base'] = null;
471
            				    $values['owner'] = $line[6];
472
            				    $values['date_first_reg'] = null;
473
					    $values['cancel'] = '';
474
					} elseif ($country == 'HJ') {
475
            				    $values['registration'] = $line[0];
476
            				    $values['base'] = null;
477
            				    $values['owner'] = $line[8];
478
            				    if ($line[7] == '') $values['date_first_reg'] = null;
479
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
480
					    $values['cancel'] = '';
481
					} elseif ($country == 'PP') {
482
            				    $values['registration'] = $line[0];
483
            				    $values['base'] = null;
484
            				    $values['owner'] = $line[4];
485
            				    if ($line[6] == '') $values['date_first_reg'] = null;
486
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
487
					    $values['cancel'] = $line[7];
488
					} elseif ($country == 'E7') {
489
            				    $values['registration'] = $line[0];
490
            				    $values['base'] = null;
491
            				    $values['owner'] = $line[4];
492
            				    if ($line[5] == '') $values['date_first_reg'] = null;
493
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
494
					    $values['cancel'] = '';
495
					} elseif ($country == '8Q') {
496
            				    $values['registration'] = $line[0];
497
            				    $values['base'] = null;
498
            				    $values['owner'] = $line[3];
499
            				    if ($line[7] == '') $values['date_first_reg'] = null;
500
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
501
					    $values['cancel'] = '';
502
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
503
            				    $values['registration'] = $line[0];
504
            				    $values['base'] = null;
505
            				    $values['owner'] = $line[3];
506
            				    $values['date_first_reg'] = null;
507
					    $values['cancel'] = '';
508
					}
509
					if ($values['cancel'] == '' && $values['registration'] != null) {
510
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
511
						$sth_dest->execute($query_dest_values);
512
					}
513
				}
514
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
515
			} catch(PDOException $e) {
516
				return "error : ".$e->getMessage();
517
			}
518
		}
519
		return '';
520
	}
521
522
	/*
523
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
524
	*/
525
	public static function update_airports() {
526
		global $tmp_dir, $globalTransaction, $globalDebug;
527
528
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
529
		$db = sparql_connect('http://dbpedia.org/sparql');
0 ignored issues
show
Unused Code introduced by
$db is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
530
		$query = '
531
		    PREFIX dbo: <http://dbpedia.org/ontology/>
532
		    PREFIX dbp: <http://dbpedia.org/property/>
533
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
534
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
535
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
536
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
537
		    FROM <http://dbpedia.org>
538
		    WHERE {
539
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
540
541
			OPTIONAL {
542
			    ?airport dbo:icaoLocationIdentifier ?icao .
543
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
544
			}
545
546
			OPTIONAL {
547
			    ?airport dbo:iataLocationIdentifier ?iata .
548
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
549
			}
550
551
			OPTIONAL {
552
			    ?airport dbo:locationIdentifier ?lid .
553
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
554
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
555
			    OPTIONAL {
556
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
557
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
558
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
559
			    }
560
			    FILTER (!bound(?other_icao))
561
			}
562
563
			OPTIONAL {
564
			    ?airport dbo:faaLocationIdentifier ?faa .
565
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
566
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
567
			    OPTIONAL {
568
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
569
				?airport_x dbo:iataLocationIdentifier ?other_iata .
570
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
571
			    }
572
			    FILTER (!bound(?other_iata))
573
			}
574
575
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
576
	
577
			OPTIONAL {
578
			    ?airport rdfs:label ?name
579
			    FILTER (lang(?name) = "en")
580
			}
581
    
582
			OPTIONAL {
583
			    ?airport foaf:homepage ?homepage
584
			}
585
		    
586
			OPTIONAL {
587
			    ?airport dbp:coordinatesRegion ?country
588
			}
589
    
590
			OPTIONAL {
591
			    ?airport dbp:type ?type
592
			}
593
			
594
			OPTIONAL {
595
			    ?airport dbo:elevation ?altitude
596
			}
597
			OPTIONAL {
598
			    ?airport dbp:image ?image
599
			}
600
601
			{
602
			    ?airport geo:lat ?latitude .
603
			    ?airport geo:long ?longitude .
604
			    FILTER (datatype(?latitude) = xsd:float)
605
			    FILTER (datatype(?longitude) = xsd:float)
606
			} UNION {
607
			    ?airport geo:lat ?latitude .
608
			    ?airport geo:long ?longitude .
609
			    FILTER (datatype(?latitude) = xsd:double)
610
			    FILTER (datatype(?longitude) = xsd:double)
611
			    OPTIONAL {
612
				?airport geo:lat ?lat_f .
613
				?airport geo:long ?long_f .
614
				FILTER (datatype(?lat_f) = xsd:float)
615
				FILTER (datatype(?long_f) = xsd:float)
616
			    }
617
			    FILTER (!bound(?lat_f) && !bound(?long_f))
618
			}
619
620
		    }
621
		    ORDER BY ?airport
622
		';
623
		$result = sparql_query($query);
624
  
625
		$query = 'TRUNCATE TABLE airport';
626
		try {
627
			$Connection = new Connection();
628
			$sth = $Connection->db->prepare($query);
629
                        $sth->execute();
630
                } catch(PDOException $e) {
631
                        return "error : ".$e->getMessage();
632
                }
633
634
635
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
636
		try {
637
			$Connection = new Connection();
638
			$sth = $Connection->db->prepare($query);
639
                        $sth->execute();
640
                } catch(PDOException $e) {
641
                        return "error : ".$e->getMessage();
642
                }
643
644
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
645
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
646
		$Connection = new Connection();
647
		$sth_dest = $Connection->db->prepare($query_dest);
648
		if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
649
  
650
		$i = 0;
651
		while($row = sparql_fetch_array($result))
652
		{
653
			if ($i >= 1) {
654
			//print_r($row);
655
			if (!isset($row['iata'])) $row['iata'] = '';
656
			if (!isset($row['icao'])) $row['icao'] = '';
657
			if (!isset($row['type'])) $row['type'] = '';
658
			if (!isset($row['altitude'])) $row['altitude'] = '';
659
			if (isset($row['city_bis'])) {
660
				$row['city'] = $row['city_bis'];
661
			}
662
			if (!isset($row['city'])) $row['city'] = '';
663
			if (!isset($row['country'])) $row['country'] = '';
664
			if (!isset($row['homepage'])) $row['homepage'] = '';
665
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
666
			if (!isset($row['name'])) continue;
667
			if (!isset($row['image'])) {
668
				$row['image'] = '';
669
				$row['image_thumb'] = '';
670
			} else {
671
				$image = str_replace(' ','_',$row['image']);
672
				$digest = md5($image);
673
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
674
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
675
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
676
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
677
			}
678
			
679
			$country = explode('-',$row['country']);
680
			$row['country'] = $country[0];
681
			
682
			$row['type'] = trim($row['type']);
683
			if ($row['type'] == 'Military: Naval Auxiliary Air Station' || $row['type'] == 'http://dbpedia.org/resource/Naval_air_station' || $row['type'] == 'Military: Naval Air Station' || $row['type'] == 'Military Northern Fleet' || $row['type'] == 'Military and industrial' || $row['type'] == 'Military: Royal Air Force station' || $row['type'] == 'http://dbpedia.org/resource/Military_airbase' || $row['type'] == 'Military: Naval air station' || preg_match('/air base/i',$row['name'])) {
684
				$row['type'] = 'Military';
685
			} elseif ($row['type'] == 'http://dbpedia.org/resource/Airport' || $row['type'] == 'Civil' || $row['type'] == 'Public use' || $row['type'] == 'Public' || $row['type'] == 'http://dbpedia.org/resource/Civilian' || $row['type'] == 'Public, Civilian' || $row['type'] == 'Public / Military' || $row['type'] == 'Private & Civilian' || $row['type'] == 'Civilian and Military' || $row['type'] == 'Public/military' || $row['type'] == 'Active With Few Facilities' || $row['type'] == '?ivilian' || $row['type'] == 'Civil/Military' || $row['type'] == 'NA' || $row['type'] == 'Public/Military') {
686
				$row['type'] = 'small_airport';
687
			}
688
			
689
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
690
			$query_dest_values = array(':airport_id' => $i, ':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => $row['altitude'],':type' => $row['type'],':city' => $row['city'],':country' => $row['country'],':home_link' => $row['homepage'],':wikipedia_link' => $row['wikipedia_page'],':image' => $row['image'],':image_thumb' => $row['image_thumb']);
691
			//print_r($query_dest_values);
692
			
693
			try {
694
				$sth_dest->execute($query_dest_values);
695
			} catch(PDOException $e) {
696
				return "error : ".$e->getMessage();
697
			}
698
			}
699
700
			$i++;
701
		}
702
		if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
703
		echo "Delete duplicate rows...\n";
704
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
705
		try {
706
			$Connection = new Connection();
707
			$sth = $Connection->db->prepare($query);
708
                        $sth->execute();
709
                } catch(PDOException $e) {
710
                        return "error : ".$e->getMessage();
711
                }
712
713
714
		if ($globalDebug) echo "Insert Not available Airport...\n";
715
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
716
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
717
		$query_values = array(':airport_id' => $i, ':name' => 'Not available',':iata' => 'NA',':icao' => 'NA',':latitude' => '0',':longitude' => '0',':altitude' => '0',':type' => 'NA',':city' => 'N/A',':country' => 'N/A',':home_link' => '',':wikipedia_link' => '',':image' => '',':image_thumb' => '');
718
		try {
719
			$Connection = new Connection();
720
			$sth = $Connection->db->prepare($query);
721
                        $sth->execute($query_values);
722
                } catch(PDOException $e) {
723
                        return "error : ".$e->getMessage();
724
                }
725
		$i++;
726
/*
727
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
728
		try {
729
			$Connection = new Connection();
730
			$sth = $Connection->db->prepare($query);
731
                        $sth->execute();
732
                } catch(PDOException $e) {
733
                        return "error : ".$e->getMessage();
734
                }
735
*/
736
737
		echo "Download data from ourairports.com...\n";
738
		$delimiter = ',';
739
		$out_file = $tmp_dir.'airports.csv';
740
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
741
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
742
		echo "Add data from ourairports.com...\n";
743
744
		$header = NULL;
745
		if (($handle = fopen($out_file, 'r')) !== FALSE)
746
		{
747
			$Connection = new Connection();
748
			//$Connection->db->beginTransaction();
749
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
750
			{
751
				if(!$header) $header = $row;
752
				else {
753
					$data = array();
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
754
					$data = array_combine($header, $row);
755
					try {
756
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
757
						$sth->execute(array(':icao' => $data['gps_code']));
758
					} catch(PDOException $e) {
759
						return "error : ".$e->getMessage();
760
					}
761
					if ($sth->fetchColumn() > 0) {
762
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
763
						try {
764
							$sth = $Connection->db->prepare($query);
765
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
766
						} catch(PDOException $e) {
767
							return "error : ".$e->getMessage();
768
						}
769
					} else {
770
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
771
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
772
						$query_values = array(':airport_id' => $i, ':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => $data['elevation_ft'],':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
773
						try {
774
							$sth = $Connection->db->prepare($query);
775
							$sth->execute($query_values);
776
						} catch(PDOException $e) {
777
							return "error : ".$e->getMessage();
778
						}
779
						$i++;
780
					}
781
				}
782
			}
783
			fclose($handle);
784
			//$Connection->db->commit();
785
		}
786
787
		echo "Download data from another free database...\n";
788
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
789
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
790
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
791
		update_db::unzip($out_file);
792
		$header = NULL;
793
		echo "Add data from another free database...\n";
794
		$delimiter = ':';
795
		$Connection = new Connection();
796
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
797
		{
798
			//$Connection->db->beginTransaction();
799
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
800
			{
801
				if(!$header) $header = $row;
802
				else {
803
					$data = $row;
804
805
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
806
					try {
807
						$sth = $Connection->db->prepare($query);
808
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
809
					} catch(PDOException $e) {
810
						return "error : ".$e->getMessage();
811
					}
812
				}
813
			}
814
			fclose($handle);
815
			//$Connection->db->commit();
816
		}
817
818
		echo "Put type military for all air base";
819
		$Connection = new Connection();
820
		try {
821
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
822
			$sth->execute();
823
		} catch(PDOException $e) {
824
			return "error : ".$e->getMessage();
825
		}
826
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
827
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
828
			try {
829
				$sth2 = $Connection->db->prepare($query2);
830
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
831
			} catch(PDOException $e) {
832
				return "error : ".$e->getMessage();
833
			}
834
		}
835
836
837
838
                return "success";
839
	}
840
	
841
	public static function translation() {
842
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
843
		global $tmp_dir, $globalTransaction;
844
		$Spotter = new Spotter();
845
		//$out_file = $tmp_dir.'translation.zip';
846
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
847
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
848
		
849
		//$query = 'TRUNCATE TABLE translation';
850
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
851
		try {
852
			$Connection = new Connection();
853
			$sth = $Connection->db->prepare($query);
854
                        $sth->execute(array(':source' => 'translation.csv'));
855
                } catch(PDOException $e) {
856
                        return "error : ".$e->getMessage();
857
                }
858
859
		
860
		//update_db::unzip($out_file);
861
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
862
		$delimiter = ';';
863
		$Connection = new Connection();
864
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
865
		{
866
			$i = 0;
867
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
868
			//$Connection->db->beginTransaction();
869
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
870
			{
871
				$i++;
872
				if($i > 12) {
873
					$data = $row;
874
					$operator = $data[2];
875
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
876
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
877
                                                //echo substr($operator, 0, 2)."\n";;
878
                                                if (count($airline_array) > 0) {
879
							//print_r($airline_array);
880
							$operator = $airline_array[0]['icao'].substr($operator,2);
881
                                                }
882
                                        }
883
					
884
					$operator_correct = $data[3];
885
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
886
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
887
                                                if (count($airline_array) > 0) {
888
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
889
                                            	}
890
                                        }
891
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
892
					try {
893
						$sth = $Connection->db->prepare($query);
894
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
895
					} catch(PDOException $e) {
896
						return "error : ".$e->getMessage();
897
					}
898
				}
899
			}
900
			fclose($handle);
901
			//$Connection->db->commit();
902
		}
903
		return '';
904
        }
905
	
906
	public static function translation_fam() {
907
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
908
		global $tmp_dir, $globalTransaction;
909
		$Spotter = new Spotter();
0 ignored issues
show
Unused Code introduced by
$Spotter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
910
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
911
		try {
912
			$Connection = new Connection();
913
			$sth = $Connection->db->prepare($query);
914
                        $sth->execute(array(':source' => 'website_fam'));
915
                } catch(PDOException $e) {
916
                        return "error : ".$e->getMessage();
917
                }
918
919
		
920
		//update_db::unzip($out_file);
921
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
922
		$delimiter = "\t";
923
		$Connection = new Connection();
924
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
925
		{
926
			$i = 0;
927
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
928
			//$Connection->db->beginTransaction();
929
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
930
			{
931
				if ($i > 0) {
932
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
933
					try {
934
						$sth = $Connection->db->prepare($query);
935
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
936
					} catch(PDOException $e) {
937
						return "error : ".$e->getMessage();
938
					}
939
				}
940
				$i++;
941
			}
942
			fclose($handle);
943
			//$Connection->db->commit();
944
		}
945
		return '';
946
        }
947
948
	public static function modes_faa() {
949
		global $tmp_dir, $globalTransaction;
950
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
951
		try {
952
			$Connection = new Connection();
953
			$sth = $Connection->db->prepare($query);
954
                        $sth->execute(array(':source' => 'website_faa'));
955
                } catch(PDOException $e) {
956
                        return "error : ".$e->getMessage();
957
                }
958
959
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
960
		try {
961
			$Connection = new Connection();
962
			$sth = $Connection->db->prepare($query);
963
                        $sth->execute(array(':source' => 'website_faa'));
964
                } catch(PDOException $e) {
965
                        return "error : ".$e->getMessage();
966
                }
967
968
		
969
		//$aircrafts_icao = array('7102811' => 'P28R',...
970
		$delimiter = ",";
971
		$Connection = new Connection();
972
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
973
		{
974
			$i = 0;
975
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
976
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
977
			{
978
				if ($i > 0) {
979
					/*
980
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
981
					try {
982
						$sth = $Connection->db->prepare($query);
983
						$sth->execute(array(':FirstCreated' => $data[16],':LastModified' => $data[15],':ModeS' => $data[33],':ModeSCountry' => $data[14], ':Registration' => 'N'.$data[0],':ICAOTypeCode' => $data[5],':type_flight' => $data[6],':source' => 'website_fam'));
984
					} catch(PDOException $e) {
985
						return "error : ".$e->getMessage();
986
					}
987
					*/
988
					if (strtotime($data[29]) > time()) {
989
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
990
						try {
991
							$sth = $Connection->db->prepare($query);
992
							$sth->execute(array(':registration' => 'N'.$data[0],':base' => $data[9],':owner' => $data[6],':date_first_reg' => date('Y-m-d',strtotime($data[23])), ':source' => 'website_faa'));
993
						} catch(PDOException $e) {
994
							return "error : ".$e->getMessage();
995
						}
996
					}
997
				}
998
				$i++;
999
			}
1000
			fclose($handle);
1001
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1002
		}
1003
		return '';
1004
        }
1005
	public static function modes_fam() {
1006
		global $tmp_dir, $globalTransaction;
1007
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1008
		try {
1009
			$Connection = new Connection();
1010
			$sth = $Connection->db->prepare($query);
1011
                        $sth->execute(array(':source' => 'website_fam'));
1012
                } catch(PDOException $e) {
1013
                        return "error : ".$e->getMessage();
1014
                }
1015
1016
		
1017
		//update_db::unzip($out_file);
1018
		$delimiter = "\t";
1019
		$Connection = new Connection();
1020
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1021
		{
1022
			$i = 0;
1023
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1024
			//$Connection->db->beginTransaction();
1025
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1026
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1027
			{
1028
				if ($i > 0) {
1029
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1030
					try {
1031
						$sth = $Connection->db->prepare($query);
1032
						$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'));
1033
					} catch(PDOException $e) {
1034
						return "error : ".$e->getMessage();
1035
					}
1036
				}
1037
				$i++;
1038
			}
1039
			fclose($handle);
1040
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1041
		}
1042
		return '';
1043
        }
1044
        
1045
	public static function owner_fam() {
1046
		global $tmp_dir, $globalTransaction;
1047
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1048
		try {
1049
			$Connection = new Connection();
1050
			$sth = $Connection->db->prepare($query);
1051
                        $sth->execute(array(':source' => 'website_fam'));
1052
                } catch(PDOException $e) {
1053
                        return "error : ".$e->getMessage();
1054
                }
1055
1056
		$delimiter = "\t";
1057
		$Connection = new Connection();
1058
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1059
		{
1060
			$i = 0;
1061
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1062
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1063
			{
1064
				if ($i > 0) {
1065
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1066
					try {
1067
						$sth = $Connection->db->prepare($query);
1068
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1069
					} catch(PDOException $e) {
1070
						print_r($data);
1071
						return "error : ".$e->getMessage();
1072
					}
1073
				}
1074
				$i++;
1075
			}
1076
			fclose($handle);
1077
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1078
		}
1079
		return '';
1080
        }
1081
1082
	public static function routes_fam() {
1083
		global $tmp_dir, $globalTransaction;
1084
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1085
		try {
1086
			$Connection = new Connection();
1087
			$sth = $Connection->db->prepare($query);
1088
                        $sth->execute(array(':source' => 'website_fam'));
1089
                } catch(PDOException $e) {
1090
                        return "error : ".$e->getMessage();
1091
                }
1092
1093
		
1094
		//update_db::unzip($out_file);
1095
		$delimiter = "\t";
1096
		$Connection = new Connection();
1097
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1098
		{
1099
			$i = 0;
1100
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1101
			//$Connection->db->beginTransaction();
1102
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1103
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1104
			{
1105
				if ($i > 0) {
1106
					$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)';
1107
					try {
1108
						$sth = $Connection->db->prepare($query);
1109
						$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'));
1110
					} catch(PDOException $e) {
1111
						return "error : ".$e->getMessage();
1112
					}
1113
				}
1114
				$i++;
1115
			}
1116
			fclose($handle);
1117
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1118
		}
1119
		return '';
1120
        }
1121
1122
	public static function tle($filename,$tletype) {
1123
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1124
		global $tmp_dir, $globalTransaction;
1125
		//$Spotter = new Spotter();
1126
		
1127
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1128
		try {
1129
			$Connection = new Connection();
1130
			$sth = $Connection->db->prepare($query);
1131
                        $sth->execute(array(':source' => $filename));
1132
                } catch(PDOException $e) {
1133
                        return "error : ".$e->getMessage();
1134
                }
1135
		
1136
		$Connection = new Connection();
1137
		if (($handle = fopen($filename, 'r')) !== FALSE)
1138
		{
1139
			$i = 0;
1140
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1141
			//$Connection->db->beginTransaction();
1142
			$dbdata = array();
1143
			while (($data = fgets($handle, 1000)) !== FALSE)
1144
			{
1145
				if ($i == 0) {
1146
					$dbdata['name'] = trim($data);
1147
					$i++;
1148
				} elseif ($i == 1) {
1149
					$dbdata['tle1'] = trim($data);
1150
					$i++;
1151
				} elseif ($i == 2) {
1152
					$dbdata['tle2'] = trim($data);
1153
					//print_r($dbdata);
1154
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1155
					try {
1156
						$sth = $Connection->db->prepare($query);
1157
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1158
					} catch(PDOException $e) {
1159
						return "error : ".$e->getMessage();
1160
					}
1161
1162
					$i = 0;
1163
				}
1164
			}
1165
			fclose($handle);
1166
			//$Connection->db->commit();
1167
		}
1168
		return '';
1169
        }
1170
1171
	/**
1172
        * Convert a HTML table to an array
1173
        * @param String $data HTML page
1174
        * @return Array array of the tables in HTML page
1175
        */
1176
        private static function table2array($data) {
1177
                $html = str_get_html($data);
1178
                $tabledata=array();
1179
                foreach($html->find('tr') as $element)
1180
                {
1181
                        $td = array();
1182
                        foreach( $element->find('th') as $row)
1183
                        {
1184
                                $td [] = trim($row->plaintext);
1185
                        }
1186
                        $td=array_filter($td);
1187
                        $tabledata[] = $td;
1188
1189
                        $td = array();
1190
                        $tdi = array();
1191
                        foreach( $element->find('td') as $row)
1192
                        {
1193
                                $td [] = trim($row->plaintext);
1194
                                $tdi [] = trim($row->innertext);
1195
                        }
1196
                        $td=array_filter($td);
1197
                        $tdi=array_filter($tdi);
0 ignored issues
show
Unused Code introduced by
$tdi is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1198
                    //    $tabledata[]=array_merge($td,$tdi);
1199
                        $tabledata[]=$td;
1200
                }
1201
                return(array_filter($tabledata));
1202
        }
1203
1204
       /**
1205
        * Get data from form result
1206
        * @param String $url form URL
1207
        * @return String the result
1208
        */
1209
        private static function getData($url) {
1210
                $ch = curl_init();
1211
                curl_setopt($ch, CURLOPT_URL, $url);
1212
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1213
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1214
                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');
1215
                return curl_exec($ch);
1216
        }
1217
/*
1218
	public static function waypoints() {
1219
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1220
		$table = update_db::table2array($data);
1221
//		print_r($table);
1222
		$query = 'TRUNCATE TABLE waypoints';
1223
		try {
1224
			$Connection = new Connection();
1225
			$sth = $Connection->db->prepare($query);
1226
                        $sth->execute();
1227
                } catch(PDOException $e) {
1228
                        return "error : ".$e->getMessage();
1229
                }
1230
1231
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1232
		$Connection = new Connection();
1233
		$sth_dest = $Connection->db->prepare($query_dest);
1234
		$Connection->db->beginTransaction();
1235
                foreach ($table as $row) {
1236
            		if ($row[0] != 'Ident') {
1237
				$ident = $row[0];
1238
				$latitude = $row[2];
1239
				$longitude = $row[3];
1240
				$control = $row[4];
1241
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1242
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1243
				try {
1244
					$sth_dest->execute($query_dest_values);
1245
				} catch(PDOException $e) {
1246
					return "error : ".$e->getMessage();
1247
				}
1248
			}
1249
                }
1250
		$Connection->db->commit();
1251
1252
	}
1253
*/
1254
	public static function waypoints($filename) {
1255
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1256
		global $tmp_dir, $globalTransaction;
1257
		//$Spotter = new Spotter();
1258
		//$out_file = $tmp_dir.'translation.zip';
1259
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1260
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1261
		$Connection = new Connection();
1262
		//update_db::unzip($out_file);
1263
		$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...
1264
		$delimiter = ' ';
1265
		if (($handle = fopen($filename, 'r')) !== FALSE)
1266
		{
1267
			$i = 0;
1268
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1269
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1270
			{
1271
				$i++;
1272
				if($i > 3 && count($row) > 2) {
1273
					$data = array_values(array_filter($row));
1274
					$cntdata = count($data);
1275
					if ($cntdata > 10) {
1276
						$value = $data[9];
1277
						
1278
						for ($i =10;$i < $cntdata;$i++) {
1279
							$value .= ' '.$data[$i];
1280
						}
1281
						$data[9] = $value;
1282
					}
1283
					//print_r($data);
1284
					if (count($data) > 9) {
1285
						$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)';
1286
						try {
1287
							$sth = $Connection->db->prepare($query);
1288
							$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]));
1289
						} catch(PDOException $e) {
1290
							return "error : ".$e->getMessage();
1291
						}
1292
					}
1293
				}
1294
			}
1295
			fclose($handle);
1296
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1297
		}
1298
		return '';
1299
        }
1300
1301
	public static function ivao_airlines($filename) {
1302
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1303
		global $tmp_dir, $globalTransaction;
1304
		//$query = 'TRUNCATE TABLE airlines';
1305
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1306
		try {
1307
			$Connection = new Connection();
1308
			$sth = $Connection->db->prepare($query);
1309
                        $sth->execute();
1310
                } catch(PDOException $e) {
1311
                        return "error : ".$e->getMessage();
1312
                }
1313
1314
		$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...
1315
		$delimiter = ':';
1316
		$Connection = new Connection();
1317
		if (($handle = fopen($filename, 'r')) !== FALSE)
1318
		{
1319
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1320
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1321
			{
1322
				if(count($row) > 1) {
1323
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1324
					try {
1325
						$sth = $Connection->db->prepare($query);
1326
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1327
					} catch(PDOException $e) {
1328
						return "error : ".$e->getMessage();
1329
					}
1330
				}
1331
			}
1332
			fclose($handle);
1333
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1334
		}
1335
		return '';
1336
        }
1337
	
1338
	public static function update_airspace() {
1339
		global $tmp_dir, $globalDBdriver;
1340
		include_once('class.create_db.php');
1341
		$Connection = new Connection();
1342
		if ($Connection->tableExists('airspace')) {
1343
			$query = 'DROP TABLE airspace';
1344
			try {
1345
				$sth = $Connection->db->prepare($query);
1346
                    		$sth->execute();
1347
	                } catch(PDOException $e) {
1348
				return "error : ".$e->getMessage();
1349
	                }
1350
	        }
1351
1352
1353
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1354
		else {
1355
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1356
			$query = "CREATE EXTENSION postgis";
1357
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1358
			try {
1359
				$sth = $Connection->db->prepare($query);
1360
				$sth->execute();
1361
			} catch(PDOException $e) {
1362
				return "error : ".$e->getMessage();
1363
			}
1364
		}
1365
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1366
		return $error;
1367
	}
1368
1369
	public static function update_notam_fam() {
1370
		global $tmp_dir, $globalDebug;
1371
		include_once('class.create_db.php');
1372
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1373
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1374
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1375
		$error = '';
1376
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1377
			if ($globalDebug) echo "Gunzip...";
1378
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1379
			if ($globalDebug) echo "Add to DB...";
1380
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1381
			$NOTAM = new NOTAM();
1382
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1383
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1384
		if ($error != '') {
1385
			return $error;
1386
		} elseif ($globalDebug) echo "Done\n";
1387
		return '';
1388
	}
1389
1390
	public static function update_vatsim() {
1391
		global $tmp_dir;
1392
		include_once('class.create_db.php');
1393
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1394
		return $error;
1395
	}
1396
	
1397
	public static function update_countries() {
1398
		global $tmp_dir, $globalDBdriver;
1399
		include_once('class.create_db.php');
1400
		$Connection = new Connection();
1401
		if ($Connection->tableExists('countries')) {
1402
			$query = 'DROP TABLE countries';
1403
			try {
1404
				$sth = $Connection->db->prepare($query);
1405
            	        	$sth->execute();
1406
	                } catch(PDOException $e) {
1407
    	                	echo "error : ".$e->getMessage();
1408
	                }
1409
		}
1410
		if ($globalDBdriver == 'mysql') {
1411
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1412
		} else {
1413
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1414
		}
1415
		$error = create_db::import_file($tmp_dir.'countries.sql');
1416
		return $error;
1417
	}
1418
1419
	
1420
	public static function update_waypoints() {
1421
		global $tmp_dir;
1422
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1423
//		update_db::unzip($tmp_dir.'AptNav.zip');
1424
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1425
//		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');
1426
		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');
1427
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1428
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1429
		return $error;
1430
	}
1431
1432
	public static function update_ivao() {
1433
		global $tmp_dir, $globalDebug;
1434
		$Common = new Common();
1435
		$error = '';
1436
		//Direct download forbidden
1437
		//if ($globalDebug) echo "IVAO : Download...";
1438
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1439
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1440
			if ($globalDebug) echo "Unzip...";
1441
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1442
			if ($globalDebug) echo "Add to DB...";
1443
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1444
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1445
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1446
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1447
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1448
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1449
		if ($error != '') {
1450
			return $error;
1451
		} elseif ($globalDebug) echo "Done\n";
1452
		return '';
1453
	}
1454
1455
	public static function update_routes() {
1456
		global $tmp_dir, $globalDebug;
1457
		$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...
1458
		if ($globalDebug) echo "Routes : Download...";
1459
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1460
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1461
			if ($globalDebug) echo "Gunzip...";
1462
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1463
			if ($globalDebug) echo "Add to DB...";
1464
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1465
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1466
		if ($error != '') {
1467
			return $error;
1468
		} elseif ($globalDebug) echo "Done\n";
1469
		return '';
1470
	}
1471
	public static function update_oneworld() {
1472
		global $tmp_dir, $globalDebug;
1473
		$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...
1474
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1475
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1476
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1477
			if ($globalDebug) echo "Gunzip...";
1478
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1479
			if ($globalDebug) echo "Add to DB...";
1480
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1481
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1482
		if ($error != '') {
1483
			return $error;
1484
		} elseif ($globalDebug) echo "Done\n";
1485
		return '';
1486
	}
1487
	public static function update_skyteam() {
1488
		global $tmp_dir, $globalDebug;
1489
		$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...
1490
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1491
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1492
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1493
			if ($globalDebug) echo "Gunzip...";
1494
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1495
			if ($globalDebug) echo "Add to DB...";
1496
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1497
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1498
		if ($error != '') {
1499
			return $error;
1500
		} elseif ($globalDebug) echo "Done\n";
1501
		return '';
1502
	}
1503
	public static function update_ModeS() {
1504
		global $tmp_dir, $globalDebug;
1505
/*
1506
		if ($globalDebug) echo "Modes : Download...";
1507
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1508
		if ($globalDebug) echo "Unzip...";
1509
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1510
		if ($globalDebug) echo "Add to DB...";
1511
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1512
		if ($error != true) {
1513
			echo $error;
1514
			exit;
1515
		} elseif ($globalDebug) echo "Done\n";
1516
*/
1517
		if ($globalDebug) echo "Modes : Download...";
1518
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1519
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1520
1521
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1522
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1523
			if ($globalDebug) echo "Unzip...";
1524
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1525
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1526
			if ($globalDebug) echo "Add to DB...";
1527
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1528
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1529
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1530
		if ($error != '') {
1531
			return $error;
1532
		} elseif ($globalDebug) echo "Done\n";
1533
		return '';
1534
	}
1535
1536
	public static function update_ModeS_faa() {
1537
		global $tmp_dir, $globalDebug;
1538
		if ($globalDebug) echo "Modes FAA: Download...";
1539
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
1540
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
1541
			if ($globalDebug) echo "Unzip...";
1542
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
1543
			if ($globalDebug) echo "Add to DB...";
1544
			$error = update_db::modes_faa($tmp_dir.'ReleasableAircraft.zip');
0 ignored issues
show
Unused Code introduced by
The call to update_db::modes_faa() has too many arguments starting with $tmp_dir . 'ReleasableAircraft.zip'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1545
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
1546
		if ($error != '') {
1547
			return $error;
1548
		} elseif ($globalDebug) echo "Done\n";
1549
		return '';
1550
	}
1551
1552
	public static function update_ModeS_flarm() {
1553
		global $tmp_dir, $globalDebug;
1554
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1555
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1556
		if (file_exists($tmp_dir.'data.fln')) {
1557
			if ($globalDebug) echo "Add to DB...";
1558
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1559
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1560
		if ($error != '') {
1561
			return $error;
1562
		} elseif ($globalDebug) echo "Done\n";
1563
		return '';
1564
	}
1565
1566
	public static function update_ModeS_ogn() {
1567
		global $tmp_dir, $globalDebug;
1568
		if ($globalDebug) echo "Modes OGN: Download...";
1569
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1570
		if (file_exists($tmp_dir.'ogn.csv')) {
1571
			if ($globalDebug) echo "Add to DB...";
1572
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1573
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1574
		if ($error != '') {
1575
			return $error;
1576
		} elseif ($globalDebug) echo "Done\n";
1577
		return '';
1578
	}
1579
1580
	public static function update_owner() {
1581
		global $tmp_dir, $globalDebug;
1582
		
1583
		if ($globalDebug) echo "Owner France: Download...";
1584
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1585
		if (file_exists($tmp_dir.'owner_f.csv')) {
1586
			if ($globalDebug) echo "Add to DB...";
1587
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1588
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1589
		if ($error != '') {
1590
			return $error;
1591
		} elseif ($globalDebug) echo "Done\n";
1592
		
1593
		if ($globalDebug) echo "Owner Ireland: Download...";
1594
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1595
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1596
			if ($globalDebug) echo "Add to DB...";
1597
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1598
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1599
		if ($error != '') {
1600
			return $error;
1601
		} elseif ($globalDebug) echo "Done\n";
1602
		if ($globalDebug) echo "Owner Switzerland: Download...";
1603
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1604
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1605
			if ($globalDebug) echo "Add to DB...";
1606
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1607
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1608
		if ($error != '') {
1609
			return $error;
1610
		} elseif ($globalDebug) echo "Done\n";
1611
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1612
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1613
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1614
			if ($globalDebug) echo "Add to DB...";
1615
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1616
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1617
		if ($error != '') {
1618
			return $error;
1619
		} elseif ($globalDebug) echo "Done\n";
1620
		if ($globalDebug) echo "Owner Australia: Download...";
1621
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1622
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1623
			if ($globalDebug) echo "Add to DB...";
1624
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1625
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1626
		if ($error != '') {
1627
			return $error;
1628
		} elseif ($globalDebug) echo "Done\n";
1629
		if ($globalDebug) echo "Owner Austria: Download...";
1630
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1631
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1632
			if ($globalDebug) echo "Add to DB...";
1633
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1634
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1635
		if ($error != '') {
1636
			return $error;
1637
		} elseif ($globalDebug) echo "Done\n";
1638
		if ($globalDebug) echo "Owner Chile: Download...";
1639
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1640
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1641
			if ($globalDebug) echo "Add to DB...";
1642
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1643
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1644
		if ($error != '') {
1645
			return $error;
1646
		} elseif ($globalDebug) echo "Done\n";
1647
		if ($globalDebug) echo "Owner Colombia: Download...";
1648
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1649
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1650
			if ($globalDebug) echo "Add to DB...";
1651
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1652
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1653
		if ($error != '') {
1654
			return $error;
1655
		} elseif ($globalDebug) echo "Done\n";
1656
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1657
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1658
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1659
			if ($globalDebug) echo "Add to DB...";
1660
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1661
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1662
		if ($error != '') {
1663
			return $error;
1664
		} elseif ($globalDebug) echo "Done\n";
1665
		if ($globalDebug) echo "Owner Brazil: Download...";
1666
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1667
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1668
			if ($globalDebug) echo "Add to DB...";
1669
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1670
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1671
		if ($error != '') {
1672
			return $error;
1673
		} elseif ($globalDebug) echo "Done\n";
1674
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1675
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1676
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1677
			if ($globalDebug) echo "Add to DB...";
1678
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1679
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1680
		if ($error != '') {
1681
			return $error;
1682
		} elseif ($globalDebug) echo "Done\n";
1683
		if ($globalDebug) echo "Owner Croatia: Download...";
1684
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1685
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1686
			if ($globalDebug) echo "Add to DB...";
1687
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1688
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1689
		if ($error != '') {
1690
			return $error;
1691
		} elseif ($globalDebug) echo "Done\n";
1692
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1693
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1694
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1695
			if ($globalDebug) echo "Add to DB...";
1696
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1697
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1698
		if ($error != '') {
1699
			return $error;
1700
		} elseif ($globalDebug) echo "Done\n";
1701
		if ($globalDebug) echo "Owner Maldives: Download...";
1702
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1703
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1704
			if ($globalDebug) echo "Add to DB...";
1705
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1706
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1707
		if ($error != '') {
1708
			return $error;
1709
		} elseif ($globalDebug) echo "Done\n";
1710
		if ($globalDebug) echo "Owner New Zealand: Download...";
1711
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1712
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1713
			if ($globalDebug) echo "Add to DB...";
1714
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1715
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1716
		if ($error != '') {
1717
			return $error;
1718
		} elseif ($globalDebug) echo "Done\n";
1719
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1720
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1721
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1722
			if ($globalDebug) echo "Add to DB...";
1723
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1724
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1725
		if ($error != '') {
1726
			return $error;
1727
		} elseif ($globalDebug) echo "Done\n";
1728
		if ($globalDebug) echo "Owner Slovakia: Download...";
1729
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1730
		if (file_exists($tmp_dir.'owner_om.csv')) {
1731
			if ($globalDebug) echo "Add to DB...";
1732
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1733
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1734
		if ($error != '') {
1735
			return $error;
1736
		} elseif ($globalDebug) echo "Done\n";
1737
		if ($globalDebug) echo "Owner Ecuador: Download...";
1738
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1739
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1740
			if ($globalDebug) echo "Add to DB...";
1741
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1742
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1743
		if ($error != '') {
1744
			return $error;
1745
		} elseif ($globalDebug) echo "Done\n";
1746
		if ($globalDebug) echo "Owner Iceland: Download...";
1747
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1748
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1749
			if ($globalDebug) echo "Add to DB...";
1750
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1751
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1752
		if ($error != '') {
1753
			return $error;
1754
		} elseif ($globalDebug) echo "Done\n";
1755
		return '';
1756
	}
1757
1758
	public static function update_translation() {
1759
		global $tmp_dir, $globalDebug;
1760
		$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...
1761
		if ($globalDebug) echo "Translation : Download...";
1762
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1763
		if (file_exists($tmp_dir.'translation.zip')) {
1764
			if ($globalDebug) echo "Unzip...";
1765
			update_db::unzip($tmp_dir.'translation.zip');
1766
			if ($globalDebug) echo "Add to DB...";
1767
			$error = update_db::translation();
1768
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1769
		if ($error != '') {
1770
			return $error;
1771
		} elseif ($globalDebug) echo "Done\n";
1772
		return '';
1773
	}
1774
1775
	public static function update_translation_fam() {
1776
		global $tmp_dir, $globalDebug;
1777
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1778
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1779
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1780
			if ($globalDebug) echo "Gunzip...";
1781
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1782
			if ($globalDebug) echo "Add to DB...";
1783
			$error = update_db::translation_fam();
1784
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1785
		if ($error != '') {
1786
			return $error;
1787
		} elseif ($globalDebug) echo "Done\n";
1788
		return '';
1789
	}
1790
	public static function update_ModeS_fam() {
1791
		global $tmp_dir, $globalDebug;
1792
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1793
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1794
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1795
			if ($globalDebug) echo "Gunzip...";
1796
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1797
			if ($globalDebug) echo "Add to DB...";
1798
			$error = update_db::modes_fam();
1799
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1800
		if ($error != '') {
1801
			return $error;
1802
		} elseif ($globalDebug) echo "Done\n";
1803
		return '';
1804
	}
1805
	public static function update_owner_fam() {
1806
		global $tmp_dir, $globalDebug, $globalOwner;
1807
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
1808
		if ($globalOwner === TRUE) {
1809
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
1810
		} else {
1811
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
1812
		}
1813
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
1814
			if ($globalDebug) echo "Gunzip...";
1815
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
1816
			if ($globalDebug) echo "Add to DB...";
1817
			$error = update_db::owner_fam();
1818
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
1819
		if ($error != '') {
1820
			return $error;
1821
		} elseif ($globalDebug) echo "Done\n";
1822
		return '';
1823
	}
1824
	public static function update_routes_fam() {
1825
		global $tmp_dir, $globalDebug;
1826
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
1827
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
1828
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
1829
			if ($globalDebug) echo "Gunzip...";
1830
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
1831
			if ($globalDebug) echo "Add to DB...";
1832
			$error = update_db::routes_fam();
1833
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
1834
		if ($error != '') {
1835
			return $error;
1836
		} elseif ($globalDebug) echo "Done\n";
1837
		return '';
1838
	}
1839
1840
	public static function update_airspace_fam() {
1841
		global $tmp_dir, $globalDebug, $globalDBdriver;
1842
		include_once('class.create_db.php');
1843
		$error = '';
1844
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1845
		if ($globalDBdriver == 'mysql') {
1846
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1847
		} else {
1848
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1849
		}
1850
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1851
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1852
			$airspace_md5 = $airspace_md5_file[0];
1853
			if (!update_db::check_airspace_version($airspace_md5)) {
1854
				if ($globalDBdriver == 'mysql') {
1855
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1856
				} else {
1857
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1858
				}
1859
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1860
					if ($globalDebug) echo "Gunzip...";
1861
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1862
					if ($globalDebug) echo "Add to DB...";
1863
					$Connection = new Connection();
1864
					if ($Connection->tableExists('airspace')) {
1865
						$query = 'DROP TABLE airspace';
1866
						try {
1867
							$sth = $Connection->db->prepare($query);
1868
    	    	    					$sth->execute();
1869
			            		} catch(PDOException $e) {
1870
							return "error : ".$e->getMessage();
1871
		            			}
1872
		    			}
1873
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1874
					update_db::insert_airspace_version($airspace_md5);
1875
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1876
			}
1877
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1878
		if ($error != '') {
1879
			return $error;
1880
		} elseif ($globalDebug) echo "Done\n";
1881
		return '';
1882
	}
1883
1884
	public static function update_tle() {
1885
		global $tmp_dir, $globalDebug;
1886
		if ($globalDebug) echo "Download TLE : Download...";
1887
		$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',
1888
		'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',
1889
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1890
		foreach ($alltle as $filename) {
1891
			if ($globalDebug) echo "downloading ".$filename.'...';
1892
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1893
			if (file_exists($tmp_dir.$filename)) {
1894
				if ($globalDebug) echo "Add to DB ".$filename."...";
1895
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1896
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1897
			if ($error != '') {
1898
				echo $error."\n";
1899
			} elseif ($globalDebug) echo "Done\n";
1900
		}
1901
		return '';
1902
	}
1903
1904
	public static function update_models() {
1905
		global $tmp_dir, $globalDebug;
1906
		$error = '';
1907
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1908
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1909
		if (file_exists($tmp_dir.'models.md5sum')) {
1910
			if ($globalDebug) echo "Check files...\n";
1911
			$newmodelsdb = array();
1912
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1913
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1914
					$model = trim($row[2]);
1915
					$newmodelsdb[$model] = trim($row[0]);
1916
				}
1917
			}
1918
			$modelsdb = array();
1919
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1920
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1921
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1922
						$model = trim($row[2]);
1923
						$modelsdb[$model] = trim($row[0]);
1924
					}
1925
				}
1926
			}
1927
			$diff = array_diff($newmodelsdb,$modelsdb);
1928
			foreach ($diff as $key => $value) {
1929
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1930
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1931
				
1932
			}
1933
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1934
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1935
		if ($error != '') {
1936
			return $error;
1937
		} elseif ($globalDebug) echo "Done\n";
1938
		return '';
1939
	}
1940
1941
	public static function update_space_models() {
1942
		global $tmp_dir, $globalDebug;
1943
		$error = '';
1944
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1945
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1946
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1947
			if ($globalDebug) echo "Check files...\n";
1948
			$newmodelsdb = array();
1949
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1950
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1951
					$model = trim($row[2]);
1952
					$newmodelsdb[$model] = trim($row[0]);
1953
				}
1954
			}
1955
			$modelsdb = array();
1956
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1957
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1958
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1959
						$model = trim($row[2]);
1960
						$modelsdb[$model] = trim($row[0]);
1961
					}
1962
				}
1963
			}
1964
			$diff = array_diff($newmodelsdb,$modelsdb);
1965
			foreach ($diff as $key => $value) {
1966
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1967
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1968
				
1969
			}
1970
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1971
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1972
		if ($error != '') {
1973
			return $error;
1974
		} elseif ($globalDebug) echo "Done\n";
1975
		return '';
1976
	}
1977
1978
	public static function update_aircraft() {
1979
		global $tmp_dir, $globalDebug;
1980
		date_default_timezone_set('UTC');
1981
		//$error = '';
1982
		/*
1983
		if ($globalDebug) echo "Aircrafts : Download...";
1984
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1985
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1986
		//$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,array('Content-Type: application/x-www-form-urlencoded','Host: cfapp.icao.int','Origin: http://cfapp.icao.int','Pragma: no-cache','Upgrade-Insecure-Requests: 1','Content-Length: '.strlen($data_req)),'','http://cfapp.icao.int/Doc8643/search.cfm',20);
1987
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1988
//		echo strlen($data_req);
1989
		echo $data;
1990
		*/
1991
		if (file_exists($tmp_dir.'aircrafts.html')) {
1992
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1993
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1994
		    $result = fread($fh,100000000);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1995
		    //echo $result;
1996
		    //var_dump(str_get_html($result));
1997
		    //print_r(self::table2array($result));
1998
		}
1999
2000
	}
2001
	
2002
	public static function update_notam() {
2003
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2004
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2005
		$Common = new Common();
2006
		date_default_timezone_set('UTC');
2007
		$query = 'TRUNCATE TABLE notam';
2008
		try {
2009
			$Connection = new Connection();
2010
			$sth = $Connection->db->prepare($query);
2011
                        $sth->execute();
2012
                } catch(PDOException $e) {
2013
                        return "error : ".$e->getMessage();
2014
                }
2015
2016
		$error = '';
2017
		if ($globalDebug) echo "Notam : Download...";
2018
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2019
		if (file_exists($tmp_dir.'notam.rss')) {
2020
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2021
			foreach ($notams['channel']['item'] as $notam) {
2022
				$title = explode(':',$notam['title']);
2023
				$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...
2024
				unset($title[0]);
2025
				$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...
2026
				$description = strip_tags($notam['description'],'<pre>');
2027
				preg_match(':^(.*?)<pre>:',$description,$match);
2028
				$q = explode('/',$match[1]);
2029
				$data['fir'] = $q[0];
2030
				$data['code'] = $q[1];
2031
				$ifrvfr = $q[2];
2032
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2033
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2034
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2035
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2036
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2037
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2038
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2039
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2040
				//$data['scope'] = $q[4];
2041
				$data['lower_limit'] = $q[5];
2042
				$data['upper_limit'] = $q[6];
2043
				$latlonrad = $q[7];
2044
				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...
2045
				$latitude = $Common->convertDec($las,'latitude');
2046
				$longitude = $Common->convertDec($lns,'longitude');
2047
				if ($lac == 'S') $latitude = '-'.$latitude;
2048
				if ($lnc == 'W') $longitude = '-'.$longitude;
2049
				$data['center_latitude'] = $latitude;
2050
				$data['center_longitude'] = $longitude;
2051
				$data['radius'] = intval($radius);
2052
				
2053
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2054
				$data['text'] = $match[1];
2055
				preg_match(':</pre>(.*?)$:',$description,$match);
2056
				$fromto = $match[1];
2057
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2058
				$fromall = trim($match[1]);
2059
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2060
				$from = trim($match[1]);
2061
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2062
				preg_match('#TO:(.*?)$#',$fromto,$match);
2063
				$toall = trim($match[1]);
2064
				if (!preg_match(':Permanent:',$toall)) {
2065
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2066
					$to = trim($match[1]);
2067
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2068
					$data['permanent'] = 0;
2069
				} else {
2070
				    $data['date_end'] = NULL;
2071
				    $data['permanent'] = 1;
2072
				}
2073
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2074
				$NOTAM = new NOTAM();
2075
				$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']);
2076
				unset($data);
2077
			} 
2078
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2079
		if ($error != '') {
2080
			return $error;
2081
		} elseif ($globalDebug) echo "Done\n";
2082
		return '';
2083
	}
2084
	
2085
	public static function create_airspace() {
2086
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2087
		$Connection = new Connection();
2088
		if ($Connection->tableExists('airspace')) {
2089
			if ($globalDBdriver == 'mysql') {
2090
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2091
			} else {
2092
				$query = 'DROP TABLE airspace';
2093
			}
2094
			try {
2095
				$Connection = new Connection();
2096
				$sth = $Connection->db->prepare($query);
2097
				$sth->execute();
2098
			} catch(PDOException $e) {
2099
				return "error : ".$e->getMessage();
2100
			}
2101
		}
2102
		$Common = new Common();
2103
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2104
		$airspace_json = json_decode($airspace_lst,true);
2105
		foreach ($airspace_json['records'] as $airspace) {
2106
			if ($globalDebug) echo $airspace['name']."...\n";
2107
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2108
			if (file_exists($tmp_dir.$airspace['name'])) {
2109
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2110
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2111
				if ($globalDBdriver == 'mysql') {
2112
					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'].'"');
2113
				} else {
2114
					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'].'"');
2115
				}
2116
			}
2117
		}
2118
	}
2119
	
2120
	public static function check_last_update() {
2121
		global $globalDBdriver;
2122
		if ($globalDBdriver == 'mysql') {
2123
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2124
		} else {
2125
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2126
		}
2127
		try {
2128
			$Connection = new Connection();
2129
			$sth = $Connection->db->prepare($query);
2130
                        $sth->execute();
2131
                } catch(PDOException $e) {
2132
                        return "error : ".$e->getMessage();
2133
                }
2134
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2135
                if ($row['nb'] > 0) return false;
2136
                else return true;
2137
	}
2138
2139
	public static function insert_last_update() {
2140
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2141
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2142
		try {
2143
			$Connection = new Connection();
2144
			$sth = $Connection->db->prepare($query);
2145
                        $sth->execute();
2146
                } catch(PDOException $e) {
2147
                        return "error : ".$e->getMessage();
2148
                }
2149
	}
2150
2151
	public static function check_airspace_version($version) {
2152
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2153
		try {
2154
			$Connection = new Connection();
2155
			$sth = $Connection->db->prepare($query);
2156
                        $sth->execute(array(':version' => $version));
2157
                } catch(PDOException $e) {
2158
                        return "error : ".$e->getMessage();
2159
                }
2160
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2161
                if ($row['nb'] > 0) return true;
2162
                else return false;
2163
	}
2164
2165
2166
	public static function insert_airspace_version($version) {
2167
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2168
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2169
		try {
2170
			$Connection = new Connection();
2171
			$sth = $Connection->db->prepare($query);
2172
                        $sth->execute(array(':version' => $version));
2173
                } catch(PDOException $e) {
2174
                        return "error : ".$e->getMessage();
2175
                }
2176
	}
2177
2178
	public static function check_last_notam_update() {
2179
		global $globalDBdriver;
2180
		if ($globalDBdriver == 'mysql') {
2181
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2182
		} else {
2183
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2184
		}
2185
		try {
2186
			$Connection = new Connection();
2187
			$sth = $Connection->db->prepare($query);
2188
                        $sth->execute();
2189
                } catch(PDOException $e) {
2190
                        return "error : ".$e->getMessage();
2191
                }
2192
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2193
                if ($row['nb'] > 0) return false;
2194
                else return true;
2195
	}
2196
2197
	public static function insert_last_notam_update() {
2198
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2199
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2200
		try {
2201
			$Connection = new Connection();
2202
			$sth = $Connection->db->prepare($query);
2203
                        $sth->execute();
2204
                } catch(PDOException $e) {
2205
                        return "error : ".$e->getMessage();
2206
                }
2207
	}
2208
	public static function check_last_airspace_update() {
2209
		global $globalDBdriver;
2210
		if ($globalDBdriver == 'mysql') {
2211
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2212
		} else {
2213
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2214
		}
2215
		try {
2216
			$Connection = new Connection();
2217
			$sth = $Connection->db->prepare($query);
2218
                        $sth->execute();
2219
                } catch(PDOException $e) {
2220
                        return "error : ".$e->getMessage();
2221
                }
2222
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2223
                if ($row['nb'] > 0) return false;
2224
                else return true;
2225
	}
2226
2227
	public static function insert_last_airspace_update() {
2228
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2229
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2230
		try {
2231
			$Connection = new Connection();
2232
			$sth = $Connection->db->prepare($query);
2233
                        $sth->execute();
2234
                } catch(PDOException $e) {
2235
                        return "error : ".$e->getMessage();
2236
                }
2237
	}
2238
2239
	public static function check_last_owner_update() {
2240
		global $globalDBdriver;
2241
		if ($globalDBdriver == 'mysql') {
2242
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2243
		} else {
2244
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2245
		}
2246
		try {
2247
			$Connection = new Connection();
2248
			$sth = $Connection->db->prepare($query);
2249
                        $sth->execute();
2250
                } catch(PDOException $e) {
2251
                        return "error : ".$e->getMessage();
2252
                }
2253
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2254
                if ($row['nb'] > 0) return false;
2255
                else return true;
2256
	}
2257
2258
	public static function insert_last_owner_update() {
2259
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2260
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2261
		try {
2262
			$Connection = new Connection();
2263
			$sth = $Connection->db->prepare($query);
2264
                        $sth->execute();
2265
                } catch(PDOException $e) {
2266
                        return "error : ".$e->getMessage();
2267
                }
2268
	}
2269
	public static function check_last_schedules_update() {
2270
		global $globalDBdriver;
2271
		if ($globalDBdriver == 'mysql') {
2272
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2273
		} else {
2274
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2275
		}
2276
		try {
2277
			$Connection = new Connection();
2278
			$sth = $Connection->db->prepare($query);
2279
                        $sth->execute();
2280
                } catch(PDOException $e) {
2281
                        return "error : ".$e->getMessage();
2282
                }
2283
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2284
                if ($row['nb'] > 0) return false;
2285
                else return true;
2286
	}
2287
2288
	public static function insert_last_schedules_update() {
2289
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2290
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2291
		try {
2292
			$Connection = new Connection();
2293
			$sth = $Connection->db->prepare($query);
2294
                        $sth->execute();
2295
                } catch(PDOException $e) {
2296
                        return "error : ".$e->getMessage();
2297
                }
2298
	}
2299
	public static function check_last_tle_update() {
2300
		global $globalDBdriver;
2301
		if ($globalDBdriver == 'mysql') {
2302
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2303
		} else {
2304
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2305
		}
2306
		try {
2307
			$Connection = new Connection();
2308
			$sth = $Connection->db->prepare($query);
2309
                        $sth->execute();
2310
                } catch(PDOException $e) {
2311
                        return "error : ".$e->getMessage();
2312
                }
2313
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2314
                if ($row['nb'] > 0) return false;
2315
                else return true;
2316
	}
2317
2318
	public static function insert_last_tle_update() {
2319
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2320
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2321
		try {
2322
			$Connection = new Connection();
2323
			$sth = $Connection->db->prepare($query);
2324
                        $sth->execute();
2325
                } catch(PDOException $e) {
2326
                        return "error : ".$e->getMessage();
2327
                }
2328
	}
2329
	public static function delete_duplicatemodes() {
2330
		global $globalDBdriver;
2331
		if ($globalDBdriver == 'mysql') {
2332
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
2333
		} else {
2334
			$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'";
2335
		}
2336
		try {
2337
			$Connection = new Connection();
2338
			$sth = $Connection->db->prepare($query);
2339
                        $sth->execute();
2340
                } catch(PDOException $e) {
2341
                        return "error : ".$e->getMessage();
2342
                }
2343
	}
2344
	public static function delete_duplicateowner() {
2345
		global $globalDBdriver;
2346
		if ($globalDBdriver == 'mysql') {
2347
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
2348
		} else {
2349
			$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)";
2350
		}
2351
		try {
2352
			$Connection = new Connection();
2353
			$sth = $Connection->db->prepare($query);
2354
                        $sth->execute();
2355
                } catch(PDOException $e) {
2356
                        return "error : ".$e->getMessage();
2357
                }
2358
	}
2359
	
2360
	public static function update_all() {
2361
		global $globalMasterServer, $globalMasterSource;
2362
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2363
			if (isset($globalMasterSource) && $globalMasterSource) {
2364
				echo update_db::update_routes();
2365
				echo update_db::update_translation();
2366
				echo update_db::update_notam_fam();
2367
				echo update_db::update_ModeS();
2368
				echo update_db::update_ModeS_flarm();
2369
				echo update_db::update_ModeS_ogn();
2370
				echo update_db::update_ModeS_faa();
2371
				//echo update_db::delete_duplicatemodes();
2372
			} else {
2373
				//echo update_db::update_routes();
2374
				echo update_db::update_routes_fam();
2375
				echo update_db::update_translation();
2376
				echo update_db::update_translation_fam();
2377
				echo update_db::update_notam_fam();
2378
				//echo update_db::update_ModeS();
2379
				echo update_db::update_ModeS_fam();
2380
				echo update_db::update_ModeS_flarm();
2381
				echo update_db::update_ModeS_ogn();
2382
				echo update_db::delete_duplicatemodes();
2383
			}
2384
		}
2385
	}
2386
}
2387
2388
//echo update_db::update_airports();
2389
//echo update_db::translation();
2390
//echo update_db::update_waypoints();
2391
//echo update_db::update_airspace();
2392
//echo update_db::update_notam();
2393
//echo update_db::update_ivao();
2394
//echo update_db::update_ModeS_flarm();
2395
//echo update_db::update_ModeS_ogn();
2396
//echo update_db::update_aircraft();
2397
//$update_db = new update_db();
2398
//echo $update_db->update_owner();
2399
//update_db::update_translation_fam();
2400
//echo update_db::update_routes();
2401
//update_db::update_models();
2402
//echo $update_db::update_skyteam();
2403
//echo $update_db::update_tle();
2404
//echo update_db::update_notam_fam();
2405
//echo update_db::create_airspace();
2406
//echo update_db::update_ModeS();
2407
//echo update_db::update_ModeS_fam();
2408
//echo update_db::update_routes_fam();
2409
//echo update_db::update_ModeS_faa();
2410
//echo update_db::update_owner_fam();
2411
//echo update_db::delete_duplicateowner();
2412
?>
2413