Completed
Push — master ( 0ab643...ed68c3 )
by Yannick
09:23
created

update_db::routes_fam()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
108
			return "error : ".$e->getMessage();
109
		}
110
                return '';
111
	}
112
	public static function retrieve_route_oneworld($database_file) {
113
		global $globalDebug, $globalTransaction;
114
		//$query = 'TRUNCATE TABLE routes';
115
		if ($globalDebug) echo " - Delete previous routes from DB -";
116
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
117
		$Connection = new Connection();
118
		try {
119
			//$Connection = new Connection();
120
			$sth = $Connection->db->prepare($query);
121
                        $sth->execute(array(':source' => 'oneworld'));
122
                } catch(PDOException $e) {
123
                        return "error : ".$e->getMessage();
124
                }
125
126
    		if ($globalDebug) echo " - Add routes to DB -";
127
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
128
		$Spotter = new Spotter();
129
		if ($fh = fopen($database_file,"r")) {
130
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
131
			$Connection = new Connection();
132
			$sth_dest = $Connection->db->prepare($query_dest);
133
			if ($globalTransaction) $Connection->db->beginTransaction();
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...
134
			while (!feof($fh)) {
135
				$line = fgetcsv($fh,9999,',');
136
				if ($line[0] != '') {
137
					if (($line[2] == '-' || ($line[2] != '-' && (strtotime($line[2]) > time()))) && ($line[3] == '-' || ($line[3] != '-' && (strtotime($line[3]) < time())))) {
138
						try {
139
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[7]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[5],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[6],':routestop' => '',':source' => 'oneworld');
140
							$sth_dest->execute($query_dest_values);
141
						} catch(PDOException $e) {
142
							if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

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

Loading history...
143
							return "error : ".$e->getMessage();
144
						}
145
					}
146
				}
147
			}
148
			if ($globalTransaction) $Connection->db->commit();
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...
149
		}
150
                return '';
151
	}
152
	
153
	public static function retrieve_route_skyteam($database_file) {
154
		global $globalDebug, $globalTransaction;
155
		//$query = 'TRUNCATE TABLE routes';
156
		if ($globalDebug) echo " - Delete previous routes from DB -";
157
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
158
		$Connection = new Connection();
159
		try {
160
			//$Connection = new Connection();
161
			$sth = $Connection->db->prepare($query);
162
                        $sth->execute(array(':source' => 'skyteam'));
163
                } catch(PDOException $e) {
164
                        return "error : ".$e->getMessage();
165
                }
166
167
    		if ($globalDebug) echo " - Add routes to DB -";
168
169
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
170
		$Spotter = new Spotter();
171
		if ($fh = fopen($database_file,"r")) {
172
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
173
			$Connection = new Connection();
174
			$sth_dest = $Connection->db->prepare($query_dest);
175
			try {
176
				if ($globalTransaction) $Connection->db->beginTransaction();
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...
177
				while (!feof($fh)) {
178
					$line = fgetcsv($fh,9999,',');
179
					if ($line[0] != '') {
180
						$datebe = explode('  -  ',$line[2]);
181
						if (strtotime($datebe[0]) > time() && strtotime($datebe[1]) < time()) {
182
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[6]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[4],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[5],':routestop' => '',':source' => 'skyteam');
183
							$sth_dest->execute($query_dest_values);
184
						}
185
					}
186
				}
187
				if ($globalTransaction) $Connection->db->commit();
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...
188
			} catch(PDOException $e) {
189
				if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

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

Loading history...
190
				return "error : ".$e->getMessage();
191
			}
192
		}
193
                return '';
194
	}
195
	public static function retrieve_modes_sqlite_to_dest($database_file) {
196
		global $globalTransaction;
197
		//$query = 'TRUNCATE TABLE aircraft_modes';
198
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
199
		try {
200
			$Connection = new Connection();
201
			$sth = $Connection->db->prepare($query);
202
                        $sth->execute(array(':source' => $database_file));
203
                } catch(PDOException $e) {
204
                        return "error : ".$e->getMessage();
205
                }
206
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
207
		try {
208
			$Connection = new Connection();
209
			$sth = $Connection->db->prepare($query);
210
                        $sth->execute(array(':source' => $database_file));
211
                } catch(PDOException $e) {
212
                        return "error : ".$e->getMessage();
213
                }
214
215
    		update_db::connect_sqlite($database_file);
216
		$query = 'select * from Aircraft';
217
		try {
218
                        $sth = update_db::$db_sqlite->prepare($query);
219
                        $sth->execute();
220
                } catch(PDOException $e) {
221
                        return "error : ".$e->getMessage();
222
                }
223
		//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
224
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
225
		
226
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
227
		
228
		$Connection = new Connection();
229
		$sth_dest = $Connection->db->prepare($query_dest);
230
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
231
		try {
232
			if ($globalTransaction) $Connection->db->beginTransaction();
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...
233
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
234
			//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
235
				if ($values['UserString4'] == 'M') $type = 'military';
236
				else $type = null;
237
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
238
				$sth_dest->execute($query_dest_values);
239
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
240
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
241
				    $sth_dest_owner->execute($query_dest_owner_values);
242
				}
243
            		}
244
			if ($globalTransaction) $Connection->db->commit();
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...
245
		} catch(PDOException $e) {
246
			return "error : ".$e->getMessage();
247
		}
248
249
		// Remove data already in DB from ACARS
250
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
251
		try {
252
			$Connection = new Connection();
253
			$sth = $Connection->db->prepare($query);
254
                        $sth->execute(array(':source' => $database_file));
255
                } catch(PDOException $e) {
256
                        return "error : ".$e->getMessage();
257
                }
258
		return '';
259
	}
260
261
	public static function retrieve_modes_flarmnet($database_file) {
262
		global $globalTransaction;
263
		$Common = new Common();
264
		//$query = 'TRUNCATE TABLE aircraft_modes';
265
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
266
		try {
267
			$Connection = new Connection();
268
			$sth = $Connection->db->prepare($query);
269
                        $sth->execute(array(':source' => $database_file));
270
                } catch(PDOException $e) {
271
                        return "error : ".$e->getMessage();
272
                }
273
		
274
		if ($fh = fopen($database_file,"r")) {
275
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
276
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
277
		
278
			$Connection = new Connection();
279
			$sth_dest = $Connection->db->prepare($query_dest);
280
			try {
281
				if ($globalTransaction) $Connection->db->beginTransaction();
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...
282
            			while (!feof($fh)) {
283
            				$values = array();
284
            				$line = $Common->hex2str(fgets($fh,9999));
285
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
286
            				$values['ModeS'] = substr($line,0,6);
287
            				$values['Registration'] = trim(substr($line,69,6));
288
            				$aircraft_name = trim(substr($line,48,6));
289
            				// Check if we can find ICAO, else set it to GLID
290
            				$aircraft_name_split = explode(' ',$aircraft_name);
291
            				$search_more = '';
292
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
293
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
294
            				$sth_search = $Connection->db->prepare($query_search);
295
					try {
296
                                    		$sth_search->execute();
297
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
298
	            				//if (count($result) > 0) {
299
	            				if (isset($result['icao']) && $result['icao'] != '') {
300
	            				    $values['ICAOTypeCode'] = $result['icao'];
301
	            				} 
302
					} catch(PDOException $e) {
303
						return "error : ".$e->getMessage();
304
					}
305
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
306
					// Add data to db
307
					if ($values['Registration'] != '' && $values['Registration'] != '0000') {
308
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
309
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':source_type' => 'flarm');
310
						//print_r($query_dest_values);
311
						$sth_dest->execute($query_dest_values);
312
					}
313
				}
314
				if ($globalTransaction) $Connection->db->commit();
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...
315
			} catch(PDOException $e) {
316
				return "error : ".$e->getMessage();
317
			}
318
		}
319
320
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
321
		try {
322
			$Connection = new Connection();
323
			$sth = $Connection->db->prepare($query);
324
                        $sth->execute(array(':source' => $database_file));
325
                } catch(PDOException $e) {
326
                        return "error : ".$e->getMessage();
327
                }
328
		return '';
329
	}
330
331
	public static function retrieve_modes_ogn($database_file) {
332
		global $globalTransaction;
333
		//$query = 'TRUNCATE TABLE aircraft_modes';
334
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
335
		try {
336
			$Connection = new Connection();
337
			$sth = $Connection->db->prepare($query);
338
                        $sth->execute(array(':source' => $database_file));
339
                } catch(PDOException $e) {
340
                        return "error : ".$e->getMessage();
341
                }
342
		
343
		if ($fh = fopen($database_file,"r")) {
344
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
345
			$query_dest = 'INSERT INTO aircraft_modes (LastModified,ModeS,Registration,ICAOTypeCode,Source,source_type) VALUES (:lastmodified,:ModeS,:Registration,:ICAOTypeCode,:source,:source_type)';
346
		
347
			$Connection = new Connection();
348
			$sth_dest = $Connection->db->prepare($query_dest);
349
			try {
350
				if ($globalTransaction) $Connection->db->beginTransaction();
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...
351
				$tmp = fgetcsv($fh,9999,',',"'");
0 ignored issues
show
Unused Code introduced by
$tmp is not used, you could remove the assignment.

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

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

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

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

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

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
359
            				$values['ICAOTypeCode'] = '';
360
            				$aircraft_name = $line[2];
361
            				// Check if we can find ICAO, else set it to GLID
362
            				$aircraft_name_split = explode(' ',$aircraft_name);
363
            				$search_more = '';
364
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
365
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
366
            				$sth_search = $Connection->db->prepare($query_search);
367
					try {
368
                                    		$sth_search->execute();
369
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
370
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
371
					} catch(PDOException $e) {
372
						return "error : ".$e->getMessage();
373
					}
374
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
375
					// Add data to db
376
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
377
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
378
						$query_dest_values = array(':lastmodified' => date('Y-m-d H:m:s'),':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':source_type' => 'flarm');
379
						//print_r($query_dest_values);
380
						$sth_dest->execute($query_dest_values);
381
					}
382
				}
383
				if ($globalTransaction) $Connection->db->commit();
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...
384
			} catch(PDOException $e) {
385
				return "error : ".$e->getMessage();
386
			}
387
		}
388
389
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
390
		try {
391
			$Connection = new Connection();
392
			$sth = $Connection->db->prepare($query);
393
                        $sth->execute(array(':source' => $database_file));
394
                } catch(PDOException $e) {
395
                        return "error : ".$e->getMessage();
396
                }
397
		return '';
398
	}
399
400
	public static function retrieve_owner($database_file,$country = 'F') {
401
		global $globalTransaction, $globalMasterSource;
402
		//$query = 'TRUNCATE TABLE aircraft_modes';
403
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source; DELETE FROM aircraft_modes WHERE Source = :source;";
404
		try {
405
			$Connection = new Connection();
406
			$sth = $Connection->db->prepare($query);
407
                        $sth->execute(array(':source' => $database_file));
408
                } catch(PDOException $e) {
409
                        return "error : ".$e->getMessage();
410
                }
411
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
412
		$Spotter = new Spotter();
413
		if ($fh = fopen($database_file,"r")) {
414
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
415
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
416
		        $query_modes = 'INSERT INTO aircraft_modes (ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:modes,:modescountry,:registration,:icaotypecode,:source)';
417
		        
418
			$Connection = new Connection();
419
			$sth_dest = $Connection->db->prepare($query_dest);
420
			$sth_modes = $Connection->db->prepare($query_modes);
421
			try {
422
				if ($globalTransaction) $Connection->db->beginTransaction();
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...
423
				$tmp = fgetcsv($fh,9999,',','"');
0 ignored issues
show
Unused Code introduced by
$tmp is not used, you could remove the assignment.

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

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

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

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

Loading history...
424
            			while (!feof($fh)) {
425
            				$line = fgetcsv($fh,9999,',','"');
426
            				$values = array();
427
            				//print_r($line);
428
            				if ($country == 'F') {
429
            				    $values['registration'] = $line[0];
430
            				    $values['base'] = $line[4];
431
            				    $values['owner'] = $line[5];
432
            				    if ($line[6] == '') $values['date_first_reg'] = null;
433
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
434
					    $values['cancel'] = $line[7];
435
					} elseif ($country == 'EI') {
436
					    // TODO : add modeS & reg to aircraft_modes
437
            				    $values['registration'] = $line[0];
438
            				    $values['base'] = $line[3];
439
            				    $values['owner'] = $line[2];
440
            				    if ($line[1] == '') $values['date_first_reg'] = null;
441
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
442
					    $values['cancel'] = '';
443
					    $values['modes'] = $line[7];
444
					    $values['icao'] = $line[8];
445
					    
446
					} elseif ($country == 'HB') {
447
					    // TODO : add modeS & reg to aircraft_modes
448
            				    $values['registration'] = $line[0];
449
            				    $values['base'] = null;
450
            				    $values['owner'] = $line[5];
451
            				    $values['date_first_reg'] = null;
452
					    $values['cancel'] = '';
453
					    $values['modes'] = $line[4];
454
					    $values['icao'] = $line[7];
455
					} elseif ($country == 'OK') {
456
					    // TODO : add modeS & reg to aircraft_modes
457
            				    $values['registration'] = $line[3];
458
            				    $values['base'] = null;
459
            				    $values['owner'] = $line[5];
460
            				    if ($line[18] == '') $values['date_first_reg'] = null;
461
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
462
					    $values['cancel'] = '';
463
					} elseif ($country == 'VH') {
464
					    // TODO : add modeS & reg to aircraft_modes
465
            				    $values['registration'] = $line[0];
466
            				    $values['base'] = null;
467
            				    $values['owner'] = $line[12];
468
            				    if ($line[28] == '') $values['date_first_reg'] = null;
469
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
470
471
					    $values['cancel'] = $line[39];
472
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
473
            				    $values['registration'] = $line[0];
474
            				    $values['base'] = null;
475
            				    $values['owner'] = $line[4];
476
            				    $values['date_first_reg'] = null;
477
					    $values['cancel'] = '';
478
					} elseif ($country == 'CC') {
479
            				    $values['registration'] = $line[0];
480
            				    $values['base'] = null;
481
            				    $values['owner'] = $line[6];
482
            				    $values['date_first_reg'] = null;
483
					    $values['cancel'] = '';
484
					} elseif ($country == 'HJ') {
485
            				    $values['registration'] = $line[0];
486
            				    $values['base'] = null;
487
            				    $values['owner'] = $line[8];
488
            				    if ($line[7] == '') $values['date_first_reg'] = null;
489
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
490
					    $values['cancel'] = '';
491
					} elseif ($country == 'PP') {
492
            				    $values['registration'] = $line[0];
493
            				    $values['base'] = null;
494
            				    $values['owner'] = $line[4];
495
            				    if ($line[6] == '') $values['date_first_reg'] = null;
496
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
497
					    $values['cancel'] = $line[7];
498
					} elseif ($country == 'E7') {
499
            				    $values['registration'] = $line[0];
500
            				    $values['base'] = null;
501
            				    $values['owner'] = $line[4];
502
            				    if ($line[5] == '') $values['date_first_reg'] = null;
503
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
504
					    $values['cancel'] = '';
505
					} elseif ($country == '8Q') {
506
            				    $values['registration'] = $line[0];
507
            				    $values['base'] = null;
508
            				    $values['owner'] = $line[3];
509
            				    if ($line[7] == '') $values['date_first_reg'] = null;
510
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
511
					    $values['cancel'] = '';
512
					} elseif ($country == 'ZK') {
513
            				    $values['registration'] = $line[0];
514
            				    $values['base'] = null;
515
            				    $values['owner'] = $line[3];
516
            				    $values['date_first_reg'] = null;
517
					    $values['cancel'] = '';
518
					    $values['modes'] = $line[5];
519
					    $values['icao'] = $line[9];
520
					} elseif ($country == 'M') {
521
            				    $values['registration'] = $line[0];
522
            				    $values['base'] = null;
523
            				    $values['owner'] = $line[6];
524
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
525
					    $values['cancel'] = date("Y-m-d",strtotime($line[8]));
526
					    $values['modes'] = $line[4];
527
					    $values['icao'] = $line[10];
528
					} elseif ($country == 'OY') {
529
            				    $values['registration'] = $line[0];
530
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[4]));
531
					    $values['modes'] = $line[5];
532
					    $values['icao'] = $line[6];
533
					} elseif ($country == 'PH') {
534
            				    $values['registration'] = $line[0];
535
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[3]));
536
					    $values['modes'] = $line[4];
537
					    $values['icao'] = $line[5];
538
					} elseif ($country == 'OM' || $country == 'TF') {
539
            				    $values['registration'] = $line[0];
540
            				    $values['base'] = null;
541
            				    $values['owner'] = $line[3];
542
            				    $values['date_first_reg'] = null;
543
					    $values['cancel'] = '';
544
					}
545
					if (isset($values['cancel']) && $values['cancel'] == '' && $values['registration'] != null && isset($values['owner'])) {
546
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
547
						$sth_dest->execute($query_dest_values);
548
					}
549
					if ($globalMasterSource && $values['registration'] != null && isset($values['modes']) && $values['modes'] != '') {
550
						$modescountry = $Spotter->countryFromAircraftRegistration($values['registration']);
551
						$query_modes_values = array(':registration' => $values['registration'],':modes' => $values['modes'],':modescountry' => $modescountry,':icaotypecode' => $values['icao'],':source' => $database_file);
552
						$sth_modes->execute($query_modes_values);
553
					}
554
				}
555
				if ($globalTransaction) $Connection->db->commit();
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...
556
			} catch(PDOException $e) {
557
				return "error : ".$e->getMessage();
558
			}
559
		}
560
		return '';
561
	}
562
563
	/*
564
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
565
	*/
566
	public static function update_airports() {
567
		global $tmp_dir, $globalTransaction, $globalDebug;
568
569
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
570
		$db = sparql_connect('http://dbpedia.org/sparql');
0 ignored issues
show
Unused Code introduced by
$db is not used, you could remove the assignment.

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

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

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

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

Loading history...
571
		$query = '
572
		    PREFIX dbo: <http://dbpedia.org/ontology/>
573
		    PREFIX dbp: <http://dbpedia.org/property/>
574
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
575
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
576
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
577
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
578
		    FROM <http://dbpedia.org>
579
		    WHERE {
580
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
581
582
			OPTIONAL {
583
			    ?airport dbo:icaoLocationIdentifier ?icao .
584
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
585
			}
586
587
			OPTIONAL {
588
			    ?airport dbo:iataLocationIdentifier ?iata .
589
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
590
			}
591
592
			OPTIONAL {
593
			    ?airport dbo:locationIdentifier ?lid .
594
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
595
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
596
			    OPTIONAL {
597
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
598
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
599
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
600
			    }
601
			    FILTER (!bound(?other_icao))
602
			}
603
604
			OPTIONAL {
605
			    ?airport dbo:faaLocationIdentifier ?faa .
606
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
607
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
608
			    OPTIONAL {
609
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
610
				?airport_x dbo:iataLocationIdentifier ?other_iata .
611
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
612
			    }
613
			    FILTER (!bound(?other_iata))
614
			}
615
616
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
617
	
618
			OPTIONAL {
619
			    ?airport rdfs:label ?name
620
			    FILTER (lang(?name) = "en")
621
			}
622
    
623
			OPTIONAL {
624
			    ?airport foaf:homepage ?homepage
625
			}
626
		    
627
			OPTIONAL {
628
			    ?airport dbp:coordinatesRegion ?country
629
			}
630
    
631
			OPTIONAL {
632
			    ?airport dbp:type ?type
633
			}
634
			
635
			OPTIONAL {
636
			    ?airport dbo:elevation ?altitude
637
			}
638
			OPTIONAL {
639
			    ?airport dbp:image ?image
640
			}
641
642
			{
643
			    ?airport geo:lat ?latitude .
644
			    ?airport geo:long ?longitude .
645
			    FILTER (datatype(?latitude) = xsd:float)
646
			    FILTER (datatype(?longitude) = xsd:float)
647
			} UNION {
648
			    ?airport geo:lat ?latitude .
649
			    ?airport geo:long ?longitude .
650
			    FILTER (datatype(?latitude) = xsd:double)
651
			    FILTER (datatype(?longitude) = xsd:double)
652
			    OPTIONAL {
653
				?airport geo:lat ?lat_f .
654
				?airport geo:long ?long_f .
655
				FILTER (datatype(?lat_f) = xsd:float)
656
				FILTER (datatype(?long_f) = xsd:float)
657
			    }
658
			    FILTER (!bound(?lat_f) && !bound(?long_f))
659
			}
660
661
		    }
662
		    ORDER BY ?airport
663
		';
664
		$result = sparql_query($query);
665
  
666
		/*
667
		$query = 'TRUNCATE TABLE airport';
668
		try {
669
			$Connection = new Connection();
670
			$sth = $Connection->db->prepare($query);
671
                        $sth->execute();
672
                } catch(PDOException $e) {
673
                        return "error : ".$e->getMessage();
674
                }
675
                */
676
                /*
677
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
678
		try {
679
			$Connection = new Connection();
680
			$sth = $Connection->db->prepare($query);
681
                        $sth->execute();
682
                } catch(PDOException $e) {
683
                        return "error : ".$e->getMessage();
684
                }
685
                */
686
687
		$query_dest = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image_thumb,image)
688
		    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
689
		$Connection = new Connection();
690
		$sth_dest = $Connection->db->prepare($query_dest);
691
		if ($globalTransaction) $Connection->db->beginTransaction();
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...
692
  
693
		$i = 0;
694
		while($row = sparql_fetch_array($result))
695
		{
696
			if ($i >= 1) {
697
			//print_r($row);
698
			if (!isset($row['iata'])) $row['iata'] = '';
699
			if (!isset($row['icao'])) $row['icao'] = '';
700
			if (!isset($row['type'])) $row['type'] = '';
701
			if (!isset($row['altitude'])) $row['altitude'] = '';
702
			if (isset($row['city_bis'])) {
703
				$row['city'] = $row['city_bis'];
704
			}
705
			if (!isset($row['city'])) $row['city'] = '';
706
			if (!isset($row['country'])) $row['country'] = '';
707
			if (!isset($row['homepage'])) $row['homepage'] = '';
708
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
709
			if (!isset($row['name'])) continue;
710
			if (!isset($row['image'])) {
711
				$row['image'] = '';
712
				$row['image_thumb'] = '';
713
			} else {
714
				$image = str_replace(' ','_',$row['image']);
715
				$digest = md5($image);
716
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
717
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
718
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
719
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
720
			}
721
			
722
			$country = explode('-',$row['country']);
723
			$row['country'] = $country[0];
724
			
725
			$row['type'] = trim($row['type']);
726
			if ($row['type'] == 'Military: Naval Auxiliary Air Station' || $row['type'] == 'http://dbpedia.org/resource/Naval_air_station' || $row['type'] == 'Military: Naval Air Station' || $row['type'] == 'Military Northern Fleet' || $row['type'] == 'Military and industrial' || $row['type'] == 'Military: Royal Air Force station' || $row['type'] == 'http://dbpedia.org/resource/Military_airbase' || $row['type'] == 'Military: Naval air station' || preg_match('/air base/i',$row['name'])) {
727
				$row['type'] = 'military';
728
			} elseif ($row['type'] == 'http://dbpedia.org/resource/Airport' || $row['type'] == 'Civil' || $row['type'] == 'Public use' || $row['type'] == 'Public' || $row['type'] == 'http://dbpedia.org/resource/Civilian' || $row['type'] == 'Public, Civilian' || $row['type'] == 'Public / Military' || $row['type'] == 'Private & Civilian' || $row['type'] == 'Civilian and Military' || $row['type'] == 'Public/military' || $row['type'] == 'Active With Few Facilities' || $row['type'] == '?ivilian' || $row['type'] == 'Civil/Military' || $row['type'] == 'NA' || $row['type'] == 'Public/Military') {
729
				$row['type'] = 'small_airport';
730
			}
731
			
732
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
733
			$query_dest_values = array(':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => round($row['altitude']),':type' => $row['type'],':city' => $row['city'],':country' => $row['country'],':home_link' => $row['homepage'],':wikipedia_link' => $row['wikipedia_page'],':image' => $row['image'],':image_thumb' => $row['image_thumb']);
734
			//print_r($query_dest_values);
735
			
736
			if ($row['icao'] != '') {
737
				try {
738
					$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
739
					$sth->execute(array(':icao' => $row['icao']));
740
				} catch(PDOException $e) {
741
					return "error : ".$e->getMessage();
742
				}
743
					if ($sth->fetchColumn() > 0) {
744
						// Update ?
745
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
746
						try {
747
							$sth = $Connection->db->prepare($query);
748
							$sth->execute(array(':icao' => $row['icao'],':type' => $row['type']));
749
						} catch(PDOException $e) {
750
							return "error : ".$e->getMessage();
751
						}
752
						echo $row['icao'].' : '.$row['type']."\n";
753
					} else {
754
						try {
755
							$sth_dest->execute($query_dest_values);
756
						} catch(PDOException $e) {
757
							return "error : ".$e->getMessage();
758
						}
759
					}
760
				}
761
			}
762
763
			$i++;
764
		}
765
		if ($globalTransaction) $Connection->db->commit();
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...
766
		/*
767
		echo "Delete duplicate rows...\n";
768
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
769
		try {
770
			$Connection = new Connection();
771
			$sth = $Connection->db->prepare($query);
772
                        $sth->execute();
773
                } catch(PDOException $e) {
774
                        return "error : ".$e->getMessage();
775
                }
776
                */
777
778
779
		/*
780
		if ($globalDebug) echo "Insert Not available Airport...\n";
781
		$query = "INSERT INTO airport (airport_id,name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link,image,image_thumb)
782
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
783
		$query_values = array(':airport_id' => $i, ':name' => 'Not available',':iata' => 'NA',':icao' => 'NA',':latitude' => '0',':longitude' => '0',':altitude' => '0',':type' => 'NA',':city' => 'N/A',':country' => 'N/A',':home_link' => '',':wikipedia_link' => '',':image' => '',':image_thumb' => '');
784
		try {
785
			$Connection = new Connection();
786
			$sth = $Connection->db->prepare($query);
787
                        $sth->execute($query_values);
788
                } catch(PDOException $e) {
789
                        return "error : ".$e->getMessage();
790
                }
791
                */
792
		$i++;
793
/*
794
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
795
		try {
796
			$Connection = new Connection();
797
			$sth = $Connection->db->prepare($query);
798
                        $sth->execute();
799
                } catch(PDOException $e) {
800
                        return "error : ".$e->getMessage();
801
                }
802
*/
803
                
804
		echo "Download data from ourairports.com...\n";
805
		$delimiter = ',';
806
		$out_file = $tmp_dir.'airports.csv';
807
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
808
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
809
		echo "Add data from ourairports.com...\n";
810
811
		$header = NULL;
812
		if (($handle = fopen($out_file, 'r')) !== FALSE)
813
		{
814
			$Connection = new Connection();
815
			//$Connection->db->beginTransaction();
816
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
817
			{
818
				if(!$header) $header = $row;
819
				else {
820
					$data = array();
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

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

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

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

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

Loading history...
821
					$data = array_combine($header, $row);
822
					try {
823
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE icao = :icao');
824
						$sth->execute(array(':icao' => $data['ident']));
825
					} catch(PDOException $e) {
826
						return "error : ".$e->getMessage();
827
					}
828
					if ($sth->fetchColumn() > 0) {
829
						$query = 'UPDATE airport SET type = :type WHERE icao = :icao';
830
						try {
831
							$sth = $Connection->db->prepare($query);
832
							$sth->execute(array(':icao' => $data['ident'],':type' => $data['type']));
833
						} catch(PDOException $e) {
834
							return "error : ".$e->getMessage();
835
						}
836
					} else {
837
						if ($data['gps_code'] == $data['ident']) {
838
						$query = "INSERT INTO airport (name,city,country,iata,icao,latitude,longitude,altitude,type,home_link,wikipedia_link)
839
						    VALUES (:name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
840
						$query_values = array(':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => round($data['elevation_ft']),':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
841
						try {
842
							$sth = $Connection->db->prepare($query);
843
							$sth->execute($query_values);
844
						} catch(PDOException $e) {
845
							return "error : ".$e->getMessage();
846
						}
847
						$i++;
848
						}
849
					}
850
				}
851
			}
852
			fclose($handle);
853
			//$Connection->db->commit();
854
		}
855
		
856
		
857
		echo "Download data from another free database...\n";
858
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
859
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
860
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
861
		update_db::unzip($out_file);
862
		$header = NULL;
863
		echo "Add data from another free database...\n";
864
		$delimiter = ':';
865
		$Connection = new Connection();
866
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
867
		{
868
			//$Connection->db->beginTransaction();
869
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
870
			{
871
				if(!$header) $header = $row;
872
				else {
873
					$data = $row;
874
875
					$query = 'UPDATE airport SET city = :city, country = :country WHERE icao = :icao';
876
					try {
877
						$sth = $Connection->db->prepare($query);
878
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
879
					} catch(PDOException $e) {
880
						return "error : ".$e->getMessage();
881
					}
882
				}
883
			}
884
			fclose($handle);
885
			//$Connection->db->commit();
886
		}
887
888
		echo "Put type military for all air base";
889
		$Connection = new Connection();
890
		try {
891
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE name LIKE '%Air Base%'");
892
			$sth->execute();
893
		} catch(PDOException $e) {
894
			return "error : ".$e->getMessage();
895
		}
896
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
897
			$query2 = 'UPDATE airport SET type = :type WHERE icao = :icao';
898
			try {
899
				$sth2 = $Connection->db->prepare($query2);
900
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
901
			} catch(PDOException $e) {
902
				return "error : ".$e->getMessage();
903
			}
904
		}
905
		return "success";
906
	}
907
	
908
	public static function translation() {
909
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
910
		global $tmp_dir, $globalTransaction;
911
		$Spotter = new Spotter();
912
		//$out_file = $tmp_dir.'translation.zip';
913
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
914
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
915
		
916
		//$query = 'TRUNCATE TABLE translation';
917
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
918
		try {
919
			$Connection = new Connection();
920
			$sth = $Connection->db->prepare($query);
921
                        $sth->execute(array(':source' => 'translation.csv'));
922
                } catch(PDOException $e) {
923
                        return "error : ".$e->getMessage();
924
                }
925
926
		
927
		//update_db::unzip($out_file);
928
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

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

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

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

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

Loading history...
929
		$delimiter = ';';
930
		$Connection = new Connection();
931
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
932
		{
933
			$i = 0;
934
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
935
			//$Connection->db->beginTransaction();
936
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
937
			{
938
				$i++;
939
				if($i > 12) {
940
					$data = $row;
941
					$operator = $data[2];
942
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
943
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
944
                                                //echo substr($operator, 0, 2)."\n";;
945
                                                if (count($airline_array) > 0) {
946
							//print_r($airline_array);
947
							$operator = $airline_array[0]['icao'].substr($operator,2);
948
                                                }
949
                                        }
950
					
951
					$operator_correct = $data[3];
952
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
953
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
954
                                                if (count($airline_array) > 0) {
955
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
956
                                            	}
957
                                        }
958
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
959
					try {
960
						$sth = $Connection->db->prepare($query);
961
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
962
					} catch(PDOException $e) {
963
						return "error : ".$e->getMessage();
964
					}
965
				}
966
			}
967
			fclose($handle);
968
			//$Connection->db->commit();
969
		}
970
		return '';
971
        }
972
	
973
	public static function translation_fam() {
974
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
975
		global $tmp_dir, $globalTransaction;
976
		$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...
977
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
978
		try {
979
			$Connection = new Connection();
980
			$sth = $Connection->db->prepare($query);
981
                        $sth->execute(array(':source' => 'website_fam'));
982
                } catch(PDOException $e) {
983
                        return "error : ".$e->getMessage();
984
                }
985
986
		
987
		//update_db::unzip($out_file);
988
		$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...
989
		$delimiter = "\t";
990
		$Connection = new Connection();
991
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
992
		{
993
			$i = 0;
994
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
995
			//$Connection->db->beginTransaction();
996
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
997
			{
998
				if ($i > 0) {
999
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
1000
					try {
1001
						$sth = $Connection->db->prepare($query);
1002
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
1003
					} catch(PDOException $e) {
1004
						return "error : ".$e->getMessage();
1005
					}
1006
				}
1007
				$i++;
1008
			}
1009
			fclose($handle);
1010
			//$Connection->db->commit();
1011
		}
1012
		return '';
1013
        }
1014
1015
	/*
1016
	* This function use FAA public data.
1017
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
1018
	*/
1019
	public static function modes_faa() {
1020
		global $tmp_dir, $globalTransaction, $globalDebug;
1021
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1022
		try {
1023
			$Connection = new Connection();
1024
			$sth = $Connection->db->prepare($query);
1025
                        $sth->execute(array(':source' => 'website_faa'));
1026
                } catch(PDOException $e) {
1027
                        return "error : ".$e->getMessage();
1028
                }
1029
1030
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1031
		try {
1032
			$Connection = new Connection();
1033
			$sth = $Connection->db->prepare($query);
1034
                        $sth->execute(array(':source' => 'website_faa'));
1035
                } catch(PDOException $e) {
1036
                        return "error : ".$e->getMessage();
1037
                }
1038
1039
		$delimiter = ",";
1040
		$mfr = array();
1041
		$Connection = new Connection();
1042
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1043
		{
1044
			$i = 0;
1045
			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...
1046
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1047
			{
1048
				if ($i > 0) {
1049
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1050
					try {
1051
						$sths = $Connection->db->prepare($query_search);
1052
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1053
					} catch(PDOException $e) {
1054
						return "error s : ".$e->getMessage();
1055
					}
1056
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1057
					if (!empty($result_search)) {
1058
						if ($globalDebug) echo '.';
1059
							//if ($globalDBdriver == 'mysql') {
1060
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1061
							//} else {
1062
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1063
							//}
1064
						try {
1065
							$sthi = $Connection->db->prepare($queryi);
1066
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1067
						} catch(PDOException $e) {
1068
							return "error u : ".$e->getMessage();
1069
						}
1070
					} else {
1071
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1072
						try {
1073
							$sthsm = $Connection->db->prepare($query_search_mfr);
1074
							$sthsm->execute(array(':mfr' => $data[2]));
1075
						} catch(PDOException $e) {
1076
							return "error mfr : ".$e->getMessage();
1077
						}
1078
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1079
						if (!empty($result_search_mfr)) {
1080
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1081
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1082
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1083
							try {
1084
								$sthf = $Connection->db->prepare($queryf);
1085
								$sthf->execute(array(':FirstCreated' => $data[16],':LastModified' => $data[15],':ModeS' => $data[33],':ModeSCountry' => $data[14], ':Registration' => 'N'.$data[0],':ICAOTypeCode' => $result_search_mfr[0]['icao'],':source' => 'website_faa'));
1086
							} catch(PDOException $e) {
1087
								return "error f : ".$e->getMessage();
1088
							}
1089
						}
1090
					}
1091
					if (strtotime($data[29]) > time()) {
1092
						if ($globalDebug) echo 'i';
1093
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1094
						try {
1095
							$sth = $Connection->db->prepare($query);
1096
							$sth->execute(array(':registration' => 'N'.$data[0],':base' => $data[9],':owner' => ucwords(strtolower($data[6])),':date_first_reg' => date('Y-m-d',strtotime($data[23])), ':source' => 'website_faa'));
1097
						} catch(PDOException $e) {
1098
							return "error i : ".$e->getMessage();
1099
						}
1100
					}
1101
				}
1102
				if ($i % 90 == 0) {
1103
					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...
1104
					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...
1105
				}
1106
				$i++;
1107
			}
1108
			fclose($handle);
1109
			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...
1110
		}
1111
		print_r($mfr);
1112
		return '';
1113
        }
1114
	public static function modes_fam() {
1115
		global $tmp_dir, $globalTransaction;
1116
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1117
		try {
1118
			$Connection = new Connection();
1119
			$sth = $Connection->db->prepare($query);
1120
                        $sth->execute(array(':source' => 'website_fam'));
1121
                } catch(PDOException $e) {
1122
                        return "error : ".$e->getMessage();
1123
                }
1124
1125
		
1126
		//update_db::unzip($out_file);
1127
		$delimiter = "\t";
1128
		$Connection = new Connection();
1129
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1130
		{
1131
			$i = 0;
1132
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1133
			//$Connection->db->beginTransaction();
1134
			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...
1135
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1136
			{
1137
				if ($i > 0) {
1138
					if ($data[1] == 'NULL') $data[1] = $data[0];
1139
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1140
					try {
1141
						$sth = $Connection->db->prepare($query);
1142
						$sth->execute(array(':FirstCreated' => $data[0],':LastModified' => $data[1],':ModeS' => $data[2],':ModeSCountry' => $data[3], ':Registration' => $data[4],':ICAOTypeCode' => $data[5],':type_flight' => $data[6],':source' => 'website_fam'));
1143
					} catch(PDOException $e) {
1144
						return "error : ".$e->getMessage();
1145
					}
1146
				}
1147
				$i++;
1148
			}
1149
			fclose($handle);
1150
			if ($globalTransaction) $Connection->db->commit();
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...
1151
		}
1152
		return '';
1153
        }
1154
        
1155
	public static function owner_fam() {
1156
		global $tmp_dir, $globalTransaction;
1157
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1158
		try {
1159
			$Connection = new Connection();
1160
			$sth = $Connection->db->prepare($query);
1161
                        $sth->execute(array(':source' => 'website_fam'));
1162
                } catch(PDOException $e) {
1163
                        return "error : ".$e->getMessage();
1164
                }
1165
1166
		$delimiter = "\t";
1167
		$Connection = new Connection();
1168
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1169
		{
1170
			$i = 0;
1171
			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...
1172
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1173
			{
1174
				if ($i > 0) {
1175
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1176
					try {
1177
						$sth = $Connection->db->prepare($query);
1178
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1179
					} catch(PDOException $e) {
1180
						print_r($data);
1181
						return "error : ".$e->getMessage();
1182
					}
1183
				}
1184
				$i++;
1185
			}
1186
			fclose($handle);
1187
			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...
1188
		}
1189
		return '';
1190
        }
1191
1192
	public static function routes_fam() {
1193
		global $tmp_dir, $globalTransaction, $globalDebug;
1194
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1195
		try {
1196
			$Connection = new Connection();
1197
			$sth = $Connection->db->prepare($query);
1198
			$sth->execute(array(':source' => 'website_fam'));
1199
		} catch(PDOException $e) {
1200
			return "error : ".$e->getMessage();
1201
		}
1202
		$delimiter = "\t";
1203
		$Connection = new Connection();
1204
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1205
		{
1206
			$i = 0;
1207
			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...
1208
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1209
			{
1210
				if ($i > 0) {
1211
					$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)';
1212
					try {
1213
						$sth = $Connection->db->prepare($query);
1214
						$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'));
1215
					} catch(PDOException $e) {
1216
						if ($globalDebug) echo "error: ".$e->getMessage()." - data: ".implode(',',$data);
1217
					}
1218
				}
1219
				$i++;
1220
			}
1221
			fclose($handle);
1222
			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...
1223
		}
1224
		return '';
1225
        }
1226
1227
	public static function marine_identity_fam() {
1228
		global $tmp_dir, $globalTransaction;
1229
		$query = "TRUNCATE TABLE marine_identity";
1230
		try {
1231
			$Connection = new Connection();
1232
			$sth = $Connection->db->prepare($query);
1233
                        $sth->execute();
1234
                } catch(PDOException $e) {
1235
                        return "error : ".$e->getMessage();
1236
                }
1237
1238
		
1239
		//update_db::unzip($out_file);
1240
		$delimiter = "\t";
1241
		$Connection = new Connection();
1242
		if (($handle = fopen($tmp_dir.'marine_identity.tsv', 'r')) !== FALSE)
1243
		{
1244
			$i = 0;
1245
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1246
			//$Connection->db->beginTransaction();
1247
			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...
1248
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1249
			{
1250
				if ($i > 0) {
1251
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1252
					$query = 'INSERT INTO marine_identity (mmsi,imo,call_sign,ship_name,length,gross_tonnage,dead_weight,width,country,engine_power,type) VALUES (:mmsi,:imo,:call_sign,:ship_name,:length,:gross_tonnage,:dead_weight,:width,:country,:engine_power,:type)';
1253
					try {
1254
						$sth = $Connection->db->prepare($query);
1255
						$sth->execute(array(':mmsi' => $data[0],':imo' => $data[1],':call_sign' => $data[2],':ship_name' => $data[3], ':length' => $data[4],':gross_tonnage' => $data[5],':dead_weight' => $data[6],':width' => $data[7],':country' => $data[8],':engine_power' => $data[9],':type' => $data[10]));
1256
					} catch(PDOException $e) {
1257
						return "error : ".$e->getMessage();
1258
					}
1259
				}
1260
				$i++;
1261
			}
1262
			fclose($handle);
1263
			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...
1264
		}
1265
		return '';
1266
        }
1267
1268
	public static function banned_fam() {
1269
		global $tmp_dir, $globalTransaction;
1270
		$query = "UPDATE airlines SET ban_eu = 0";
1271
		try {
1272
			$Connection = new Connection();
1273
			$sth = $Connection->db->prepare($query);
1274
			$sth->execute();
1275
		} catch(PDOException $e) {
1276
			return "error : ".$e->getMessage();
1277
		}
1278
1279
		$Connection = new Connection();
1280
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1281
		{
1282
			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...
1283
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1284
			{
1285
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1286
				if ($data[0] != '') {
1287
					$icao = $data[0];
1288
					try {
1289
						$sth = $Connection->db->prepare($query);
1290
						$sth->execute(array(':icao' => $icao));
1291
					} catch(PDOException $e) {
1292
						return "error : ".$e->getMessage();
1293
					}
1294
				}
1295
			}
1296
			fclose($handle);
1297
			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...
1298
		}
1299
		return '';
1300
        }
1301
1302
	public static function tle($filename,$tletype) {
1303
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1304
		global $tmp_dir, $globalTransaction;
1305
		//$Spotter = new Spotter();
1306
		
1307
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1308
		try {
1309
			$Connection = new Connection();
1310
			$sth = $Connection->db->prepare($query);
1311
                        $sth->execute(array(':source' => $filename));
1312
                } catch(PDOException $e) {
1313
                        return "error : ".$e->getMessage();
1314
                }
1315
		
1316
		$Connection = new Connection();
1317
		if (($handle = fopen($filename, 'r')) !== FALSE)
1318
		{
1319
			$i = 0;
1320
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1321
			//$Connection->db->beginTransaction();
1322
			$dbdata = array();
1323
			while (($data = fgets($handle, 1000)) !== FALSE)
1324
			{
1325
				if ($i == 0) {
1326
					$dbdata['name'] = trim($data);
1327
					$i++;
1328
				} elseif ($i == 1) {
1329
					$dbdata['tle1'] = trim($data);
1330
					$i++;
1331
				} elseif ($i == 2) {
1332
					$dbdata['tle2'] = trim($data);
1333
					//print_r($dbdata);
1334
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1335
					try {
1336
						$sth = $Connection->db->prepare($query);
1337
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1338
					} catch(PDOException $e) {
1339
						return "error : ".$e->getMessage();
1340
					}
1341
1342
					$i = 0;
1343
				}
1344
			}
1345
			fclose($handle);
1346
			//$Connection->db->commit();
1347
		}
1348
		return '';
1349
        }
1350
1351
	/**
1352
        * Convert a HTML table to an array
1353
        * @param String $data HTML page
1354
        * @return Array array of the tables in HTML page
1355
        */
1356
        private static function table2array($data) {
1357
                $html = str_get_html($data);
1358
                $tabledata=array();
1359
                foreach($html->find('tr') as $element)
1360
                {
1361
                        $td = array();
1362
                        foreach( $element->find('th') as $row)
1363
                        {
1364
                                $td [] = trim($row->plaintext);
1365
                        }
1366
                        $td=array_filter($td);
1367
                        $tabledata[] = $td;
1368
1369
                        $td = array();
1370
                        $tdi = array();
1371
                        foreach( $element->find('td') as $row)
1372
                        {
1373
                                $td [] = trim($row->plaintext);
1374
                                $tdi [] = trim($row->innertext);
1375
                        }
1376
                        $td=array_filter($td);
1377
                        $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...
1378
                    //    $tabledata[]=array_merge($td,$tdi);
1379
                        $tabledata[]=$td;
1380
                }
1381
                return(array_filter($tabledata));
1382
        }
1383
1384
       /**
1385
        * Get data from form result
1386
        * @param String $url form URL
1387
        * @return String the result
1388
        */
1389
        private static function getData($url) {
1390
                $ch = curl_init();
1391
                curl_setopt($ch, CURLOPT_URL, $url);
1392
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1393
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1394
                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');
1395
                return curl_exec($ch);
1396
        }
1397
/*
1398
	public static function waypoints() {
1399
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1400
		$table = update_db::table2array($data);
1401
//		print_r($table);
1402
		$query = 'TRUNCATE TABLE waypoints';
1403
		try {
1404
			$Connection = new Connection();
1405
			$sth = $Connection->db->prepare($query);
1406
                        $sth->execute();
1407
                } catch(PDOException $e) {
1408
                        return "error : ".$e->getMessage();
1409
                }
1410
1411
		$query_dest = 'INSERT INTO waypoints (ident,latitude,longitude,control,usage) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1412
		$Connection = new Connection();
1413
		$sth_dest = $Connection->db->prepare($query_dest);
1414
		$Connection->db->beginTransaction();
1415
                foreach ($table as $row) {
1416
            		if ($row[0] != 'Ident') {
1417
				$ident = $row[0];
1418
				$latitude = $row[2];
1419
				$longitude = $row[3];
1420
				$control = $row[4];
1421
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1422
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1423
				try {
1424
					$sth_dest->execute($query_dest_values);
1425
				} catch(PDOException $e) {
1426
					return "error : ".$e->getMessage();
1427
				}
1428
			}
1429
                }
1430
		$Connection->db->commit();
1431
1432
	}
1433
*/
1434
	public static function waypoints($filename) {
1435
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1436
		global $tmp_dir, $globalTransaction;
1437
		//$Spotter = new Spotter();
1438
		//$out_file = $tmp_dir.'translation.zip';
1439
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1440
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1441
		$Connection = new Connection();
1442
		//update_db::unzip($out_file);
1443
		$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...
1444
		$delimiter = ' ';
1445
		if (($handle = fopen($filename, 'r')) !== FALSE)
1446
		{
1447
			$i = 0;
1448
			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...
1449
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1450
			{
1451
				$i++;
1452
				if($i > 3 && count($row) > 2) {
1453
					$data = array_values(array_filter($row));
1454
					$cntdata = count($data);
1455
					if ($cntdata > 10) {
1456
						$value = $data[9];
1457
						
1458
						for ($i =10;$i < $cntdata;$i++) {
1459
							$value .= ' '.$data[$i];
1460
						}
1461
						$data[9] = $value;
1462
					}
1463
					//print_r($data);
1464
					if (count($data) > 9) {
1465
						$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)';
1466
						try {
1467
							$sth = $Connection->db->prepare($query);
1468
							$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]));
1469
						} catch(PDOException $e) {
1470
							return "error : ".$e->getMessage();
1471
						}
1472
					}
1473
				}
1474
			}
1475
			fclose($handle);
1476
			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...
1477
		}
1478
		return '';
1479
        }
1480
1481
	public static function ivao_airlines($filename) {
1482
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1483
		global $tmp_dir, $globalTransaction;
1484
		//$query = 'TRUNCATE TABLE airlines';
1485
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1486
		try {
1487
			$Connection = new Connection();
1488
			$sth = $Connection->db->prepare($query);
1489
                        $sth->execute();
1490
                } catch(PDOException $e) {
1491
                        return "error : ".$e->getMessage();
1492
                }
1493
1494
		$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...
1495
		$delimiter = ':';
1496
		$Connection = new Connection();
1497
		if (($handle = fopen($filename, 'r')) !== FALSE)
1498
		{
1499
			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...
1500
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1501
			{
1502
				if(count($row) > 1) {
1503
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1504
					try {
1505
						$sth = $Connection->db->prepare($query);
1506
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1507
					} catch(PDOException $e) {
1508
						return "error : ".$e->getMessage();
1509
					}
1510
				}
1511
			}
1512
			fclose($handle);
1513
			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...
1514
		}
1515
		return '';
1516
        }
1517
	
1518
	public static function update_airspace() {
1519
		global $tmp_dir, $globalDBdriver;
1520
		include_once('class.create_db.php');
1521
		$Connection = new Connection();
1522
		if ($Connection->tableExists('airspace')) {
1523
			$query = 'DROP TABLE airspace';
1524
			try {
1525
				$sth = $Connection->db->prepare($query);
1526
                    		$sth->execute();
1527
	                } catch(PDOException $e) {
1528
				return "error : ".$e->getMessage();
1529
	                }
1530
	        }
1531
1532
1533
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1534
		else {
1535
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1536
			$query = "CREATE EXTENSION postgis";
1537
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1538
			try {
1539
				$sth = $Connection->db->prepare($query);
1540
				$sth->execute();
1541
			} catch(PDOException $e) {
1542
				return "error : ".$e->getMessage();
1543
			}
1544
		}
1545
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1546
		return $error;
1547
	}
1548
1549
	public static function update_notam_fam() {
1550
		global $tmp_dir, $globalDebug;
1551
		include_once('class.create_db.php');
1552
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1553
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1554
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1555
		$error = '';
1556
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1557
			if ($globalDebug) echo "Gunzip...";
1558
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1559
			if ($globalDebug) echo "Add to DB...";
1560
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1561
			$NOTAM = new NOTAM();
1562
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1563
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1564
		if ($error != '') {
1565
			return $error;
1566
		} elseif ($globalDebug) echo "Done\n";
1567
		return '';
1568
	}
1569
1570
	public static function update_vatsim() {
1571
		global $tmp_dir;
1572
		include_once('class.create_db.php');
1573
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1574
		return $error;
1575
	}
1576
	
1577
	public static function update_countries() {
1578
		global $tmp_dir, $globalDBdriver;
1579
		include_once('class.create_db.php');
1580
		$Connection = new Connection();
1581
		if ($Connection->tableExists('countries')) {
1582
			$query = 'DROP TABLE countries';
1583
			try {
1584
				$sth = $Connection->db->prepare($query);
1585
            	        	$sth->execute();
1586
	                } catch(PDOException $e) {
1587
    	                	echo "error : ".$e->getMessage();
1588
	                }
1589
		}
1590
		if ($globalDBdriver == 'mysql') {
1591
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1592
		} else {
1593
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1594
		}
1595
		$error = create_db::import_file($tmp_dir.'countries.sql');
1596
		return $error;
1597
	}
1598
1599
	
1600
	public static function update_waypoints() {
1601
		global $tmp_dir;
1602
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1603
//		update_db::unzip($tmp_dir.'AptNav.zip');
1604
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1605
//		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');
1606
		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');
1607
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1608
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1609
		return $error;
1610
	}
1611
1612
	public static function update_ivao() {
1613
		global $tmp_dir, $globalDebug;
1614
		$Common = new Common();
1615
		$error = '';
1616
		//Direct download forbidden
1617
		//if ($globalDebug) echo "IVAO : Download...";
1618
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1619
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1620
			if ($globalDebug) echo "Unzip...";
1621
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1622
			if ($globalDebug) echo "Add to DB...";
1623
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1624
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1625
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1626
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1627
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1628
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1629
		if ($error != '') {
1630
			return $error;
1631
		} elseif ($globalDebug) echo "Done\n";
1632
		return '';
1633
	}
1634
1635
	public static function update_routes() {
1636
		global $tmp_dir, $globalDebug;
1637
		$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...
1638
		if ($globalDebug) echo "Routes : Download...";
1639
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1640
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1641
			if ($globalDebug) echo "Gunzip...";
1642
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1643
			if ($globalDebug) echo "Add to DB...";
1644
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1645
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1646
		if ($error != '') {
1647
			return $error;
1648
		} elseif ($globalDebug) echo "Done\n";
1649
		return '';
1650
	}
1651
	public static function update_oneworld() {
1652
		global $tmp_dir, $globalDebug;
1653
		$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...
1654
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1655
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1656
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1657
			if ($globalDebug) echo "Gunzip...";
1658
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1659
			if ($globalDebug) echo "Add to DB...";
1660
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1661
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1662
		if ($error != '') {
1663
			return $error;
1664
		} elseif ($globalDebug) echo "Done\n";
1665
		return '';
1666
	}
1667
	public static function update_skyteam() {
1668
		global $tmp_dir, $globalDebug;
1669
		$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...
1670
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1671
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1672
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1673
			if ($globalDebug) echo "Gunzip...";
1674
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1675
			if ($globalDebug) echo "Add to DB...";
1676
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1677
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1678
		if ($error != '') {
1679
			return $error;
1680
		} elseif ($globalDebug) echo "Done\n";
1681
		return '';
1682
	}
1683
	public static function update_ModeS() {
1684
		global $tmp_dir, $globalDebug;
1685
/*
1686
		if ($globalDebug) echo "Modes : Download...";
1687
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1688
		if ($globalDebug) echo "Unzip...";
1689
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1690
		if ($globalDebug) echo "Add to DB...";
1691
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1692
		if ($error != true) {
1693
			echo $error;
1694
			exit;
1695
		} elseif ($globalDebug) echo "Done\n";
1696
*/
1697
		if ($globalDebug) echo "Modes : Download...";
1698
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1699
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1700
1701
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1702
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1703
			if ($globalDebug) echo "Unzip...";
1704
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1705
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1706
			if ($globalDebug) echo "Add to DB...";
1707
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1708
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1709
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1710
		if ($error != '') {
1711
			return $error;
1712
		} elseif ($globalDebug) echo "Done\n";
1713
		return '';
1714
	}
1715
1716
	public static function update_ModeS_faa() {
1717
		global $tmp_dir, $globalDebug;
1718
		if ($globalDebug) echo "Modes FAA: Download...";
1719
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
1720
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
1721
			if ($globalDebug) echo "Unzip...";
1722
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
1723
			if ($globalDebug) echo "Add to DB...";
1724
			$error = update_db::modes_faa();
1725
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
1726
		if ($error != '') {
1727
			return $error;
1728
		} elseif ($globalDebug) echo "Done\n";
1729
		return '';
1730
	}
1731
1732
	public static function update_ModeS_flarm() {
1733
		global $tmp_dir, $globalDebug;
1734
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1735
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1736
		if (file_exists($tmp_dir.'data.fln')) {
1737
			if ($globalDebug) echo "Add to DB...";
1738
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1739
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1740
		if ($error != '') {
1741
			return $error;
1742
		} elseif ($globalDebug) echo "Done\n";
1743
		return '';
1744
	}
1745
1746
	public static function update_ModeS_ogn() {
1747
		global $tmp_dir, $globalDebug;
1748
		if ($globalDebug) echo "Modes OGN: Download...";
1749
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1750
		if (file_exists($tmp_dir.'ogn.csv')) {
1751
			if ($globalDebug) echo "Add to DB...";
1752
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1753
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1754
		if ($error != '') {
1755
			return $error;
1756
		} elseif ($globalDebug) echo "Done\n";
1757
		return '';
1758
	}
1759
1760
	public static function update_owner() {
1761
		global $tmp_dir, $globalDebug, $globalMasterSource;
1762
		
1763
		if ($globalDebug) echo "Owner France: Download...";
1764
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1765
		if (file_exists($tmp_dir.'owner_f.csv')) {
1766
			if ($globalDebug) echo "Add to DB...";
1767
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1768
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1769
		if ($error != '') {
1770
			return $error;
1771
		} elseif ($globalDebug) echo "Done\n";
1772
		
1773
		if ($globalDebug) echo "Owner Ireland: Download...";
1774
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1775
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1776
			if ($globalDebug) echo "Add to DB...";
1777
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1778
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1779
		if ($error != '') {
1780
			return $error;
1781
		} elseif ($globalDebug) echo "Done\n";
1782
		if ($globalDebug) echo "Owner Switzerland: Download...";
1783
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1784
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1785
			if ($globalDebug) echo "Add to DB...";
1786
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1787
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1788
		if ($error != '') {
1789
			return $error;
1790
		} elseif ($globalDebug) echo "Done\n";
1791
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1792
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1793
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1794
			if ($globalDebug) echo "Add to DB...";
1795
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1796
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1797
		if ($error != '') {
1798
			return $error;
1799
		} elseif ($globalDebug) echo "Done\n";
1800
		if ($globalDebug) echo "Owner Australia: Download...";
1801
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1802
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1803
			if ($globalDebug) echo "Add to DB...";
1804
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1805
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1806
		if ($error != '') {
1807
			return $error;
1808
		} elseif ($globalDebug) echo "Done\n";
1809
		if ($globalDebug) echo "Owner Austria: Download...";
1810
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1811
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1812
			if ($globalDebug) echo "Add to DB...";
1813
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1814
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1815
		if ($error != '') {
1816
			return $error;
1817
		} elseif ($globalDebug) echo "Done\n";
1818
		if ($globalDebug) echo "Owner Chile: Download...";
1819
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1820
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1821
			if ($globalDebug) echo "Add to DB...";
1822
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1823
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1824
		if ($error != '') {
1825
			return $error;
1826
		} elseif ($globalDebug) echo "Done\n";
1827
		if ($globalDebug) echo "Owner Colombia: Download...";
1828
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1829
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1830
			if ($globalDebug) echo "Add to DB...";
1831
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1832
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1833
		if ($error != '') {
1834
			return $error;
1835
		} elseif ($globalDebug) echo "Done\n";
1836
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1837
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1838
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1839
			if ($globalDebug) echo "Add to DB...";
1840
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1841
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1842
		if ($error != '') {
1843
			return $error;
1844
		} elseif ($globalDebug) echo "Done\n";
1845
		if ($globalDebug) echo "Owner Brazil: Download...";
1846
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1847
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1848
			if ($globalDebug) echo "Add to DB...";
1849
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1850
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1851
		if ($error != '') {
1852
			return $error;
1853
		} elseif ($globalDebug) echo "Done\n";
1854
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1855
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1856
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1857
			if ($globalDebug) echo "Add to DB...";
1858
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1859
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1860
		if ($error != '') {
1861
			return $error;
1862
		} elseif ($globalDebug) echo "Done\n";
1863
		if ($globalDebug) echo "Owner Croatia: Download...";
1864
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1865
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1866
			if ($globalDebug) echo "Add to DB...";
1867
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1868
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1869
		if ($error != '') {
1870
			return $error;
1871
		} elseif ($globalDebug) echo "Done\n";
1872
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1873
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1874
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1875
			if ($globalDebug) echo "Add to DB...";
1876
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1877
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1878
		if ($error != '') {
1879
			return $error;
1880
		} elseif ($globalDebug) echo "Done\n";
1881
		if ($globalDebug) echo "Owner Maldives: Download...";
1882
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1883
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1884
			if ($globalDebug) echo "Add to DB...";
1885
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1886
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1887
		if ($error != '') {
1888
			return $error;
1889
		} elseif ($globalDebug) echo "Done\n";
1890
		if ($globalDebug) echo "Owner New Zealand: Download...";
1891
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1892
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1893
			if ($globalDebug) echo "Add to DB...";
1894
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1895
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1896
		if ($error != '') {
1897
			return $error;
1898
		} elseif ($globalDebug) echo "Done\n";
1899
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1900
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1901
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1902
			if ($globalDebug) echo "Add to DB...";
1903
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1904
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1905
		if ($error != '') {
1906
			return $error;
1907
		} elseif ($globalDebug) echo "Done\n";
1908
		if ($globalDebug) echo "Owner Slovakia: Download...";
1909
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1910
		if (file_exists($tmp_dir.'owner_om.csv')) {
1911
			if ($globalDebug) echo "Add to DB...";
1912
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1913
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1914
		if ($error != '') {
1915
			return $error;
1916
		} elseif ($globalDebug) echo "Done\n";
1917
		if ($globalDebug) echo "Owner Ecuador: Download...";
1918
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1919
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1920
			if ($globalDebug) echo "Add to DB...";
1921
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1922
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1923
		if ($error != '') {
1924
			return $error;
1925
		} elseif ($globalDebug) echo "Done\n";
1926
		if ($globalDebug) echo "Owner Iceland: Download...";
1927
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1928
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1929
			if ($globalDebug) echo "Add to DB...";
1930
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1931
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1932
		if ($error != '') {
1933
			return $error;
1934
		} elseif ($globalDebug) echo "Done\n";
1935
		if ($globalDebug) echo "Owner Isle of Man: Download...";
1936
		update_db::download('http://antonakis.co.uk/registers/IsleOfMan.txt',$tmp_dir.'owner_m.csv');
1937
		if (file_exists($tmp_dir.'owner_m.csv')) {
1938
			if ($globalDebug) echo "Add to DB...";
1939
			$error = update_db::retrieve_owner($tmp_dir.'owner_m.csv','M');
1940
		} else $error = "File ".$tmp_dir.'owner_m.csv'." doesn't exist. Download failed.";
1941
		if ($error != '') {
1942
			return $error;
1943
		} elseif ($globalDebug) echo "Done\n";
1944
		if ($globalMasterSource) {
1945
			if ($globalDebug) echo "ModeS Netherlands: Download...";
1946
			update_db::download('http://antonakis.co.uk/registers/Netherlands.txt',$tmp_dir.'owner_ph.csv');
1947
			if (file_exists($tmp_dir.'owner_ph.csv')) {
1948
				if ($globalDebug) echo "Add to DB...";
1949
				$error = update_db::retrieve_owner($tmp_dir.'owner_ph.csv','PH');
1950
			} else $error = "File ".$tmp_dir.'owner_ph.csv'." doesn't exist. Download failed.";
1951
			if ($error != '') {
1952
				return $error;
1953
			} elseif ($globalDebug) echo "Done\n";
1954
			if ($globalDebug) echo "ModeS Denmark: Download...";
1955
			update_db::download('http://antonakis.co.uk/registers/Denmark.txt',$tmp_dir.'owner_oy.csv');
1956
			if (file_exists($tmp_dir.'owner_oy.csv')) {
1957
				if ($globalDebug) echo "Add to DB...";
1958
				$error = update_db::retrieve_owner($tmp_dir.'owner_oy.csv','OY');
1959
			} else $error = "File ".$tmp_dir.'owner_oy.csv'." doesn't exist. Download failed.";
1960
			if ($error != '') {
1961
				return $error;
1962
			} elseif ($globalDebug) echo "Done\n";
1963
		} elseif ($globalDebug) echo "Done\n";
1964
		return '';
1965
	}
1966
1967
	public static function update_translation() {
1968
		global $tmp_dir, $globalDebug;
1969
		$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...
1970
		if ($globalDebug) echo "Translation : Download...";
1971
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1972
		if (file_exists($tmp_dir.'translation.zip')) {
1973
			if ($globalDebug) echo "Unzip...";
1974
			update_db::unzip($tmp_dir.'translation.zip');
1975
			if ($globalDebug) echo "Add to DB...";
1976
			$error = update_db::translation();
1977
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1978
		if ($error != '') {
1979
			return $error;
1980
		} elseif ($globalDebug) echo "Done\n";
1981
		return '';
1982
	}
1983
1984
	public static function update_translation_fam() {
1985
		global $tmp_dir, $globalDebug;
1986
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1987
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1988
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1989
			if ($globalDebug) echo "Gunzip...";
1990
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1991
			if ($globalDebug) echo "Add to DB...";
1992
			$error = update_db::translation_fam();
1993
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1994
		if ($error != '') {
1995
			return $error;
1996
		} elseif ($globalDebug) echo "Done\n";
1997
		return '';
1998
	}
1999
	public static function update_ModeS_fam() {
2000
		global $tmp_dir, $globalDebug;
2001
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
2002
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
2003
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
2004
			if ($globalDebug) echo "Gunzip...";
2005
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
2006
			if ($globalDebug) echo "Add to DB...";
2007
			$error = update_db::modes_fam();
2008
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
2009
		if ($error != '') {
2010
			return $error;
2011
		} elseif ($globalDebug) echo "Done\n";
2012
		return '';
2013
	}
2014
	public static function update_owner_fam() {
2015
		global $tmp_dir, $globalDebug, $globalOwner;
2016
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
2017
		if ($globalOwner === TRUE) {
2018
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
2019
		} else {
2020
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
2021
		}
2022
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
2023
			if ($globalDebug) echo "Gunzip...";
2024
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
2025
			if ($globalDebug) echo "Add to DB...";
2026
			$error = update_db::owner_fam();
2027
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
2028
		if ($error != '') {
2029
			return $error;
2030
		} elseif ($globalDebug) echo "Done\n";
2031
		return '';
2032
	}
2033
	public static function update_routes_fam() {
2034
		global $tmp_dir, $globalDebug;
2035
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
2036
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
2037
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
2038
			if ($globalDebug) echo "Gunzip...";
2039
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
2040
			if ($globalDebug) echo "Add to DB...";
2041
			$error = update_db::routes_fam();
2042
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
2043
		if ($error != '') {
2044
			return $error;
2045
		} elseif ($globalDebug) echo "Done\n";
2046
		return '';
2047
	}
2048
	public static function update_marine_identity_fam() {
2049
		global $tmp_dir, $globalDebug;
2050
		update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz.md5',$tmp_dir.'marine_identity.tsv.gz.md5');
2051
		if (file_exists($tmp_dir.'marine_identity.tsv.gz.md5')) {
2052
			$marine_identity_md5_file = explode(' ',file_get_contents($tmp_dir.'marine_identity.tsv.gz.md5'));
2053
			$marine_identity_md5 = $marine_identity_md5_file[0];
2054
			if (!update_db::check_marine_identity_version($marine_identity_md5)) {
2055
				if ($globalDebug) echo "Marine identity from FlightAirMap website : Download...";
2056
				update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz',$tmp_dir.'marine_identity.tsv.gz');
2057
				if (file_exists($tmp_dir.'marine_identity.tsv.gz')) {
2058
					if ($globalDebug) echo "Gunzip...";
2059
					update_db::gunzip($tmp_dir.'marine_identity.tsv.gz');
2060
					if ($globalDebug) echo "Add to DB...";
2061
					$error = update_db::marine_identity_fam();
2062
				} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." doesn't exist. Download failed.";
2063
				if ($error != '') {
2064
					return $error;
2065
				} elseif ($globalDebug) {
2066
					update_db::insert_marine_identity_version($marine_identity_md5);
2067
					echo "Done\n";
2068
				}
2069
			}
2070
		}
2071
		return '';
2072
	}
2073
	public static function update_banned_fam() {
2074
		global $tmp_dir, $globalDebug;
2075
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
2076
		update_db::download('http://data.flightairmap.fr/data/ban-eu.csv',$tmp_dir.'ban_eu.csv');
2077
		if (file_exists($tmp_dir.'ban_eu.csv')) {
2078
			//if ($globalDebug) echo "Gunzip...";
2079
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
2080
			if ($globalDebug) echo "Add to DB...";
2081
			$error = update_db::banned_fam();
2082
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
2083
		if ($error != '') {
2084
			return $error;
2085
		} elseif ($globalDebug) echo "Done\n";
2086
		return '';
2087
	}
2088
2089
	public static function update_airspace_fam() {
2090
		global $tmp_dir, $globalDebug, $globalDBdriver;
2091
		include_once('class.create_db.php');
2092
		$error = '';
2093
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
2094
		if ($globalDBdriver == 'mysql') {
2095
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2096
		} else {
2097
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2098
		}
2099
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
2100
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
2101
			$airspace_md5 = $airspace_md5_file[0];
2102
			if (!update_db::check_airspace_version($airspace_md5)) {
2103
				if ($globalDBdriver == 'mysql') {
2104
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
2105
				} else {
2106
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
2107
				}
2108
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
2109
					if ($globalDebug) echo "Gunzip...";
2110
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
2111
					if ($globalDebug) echo "Add to DB...";
2112
					$Connection = new Connection();
2113
					if ($Connection->tableExists('airspace')) {
2114
						$query = 'DROP TABLE airspace';
2115
						try {
2116
							$sth = $Connection->db->prepare($query);
2117
    	    	    					$sth->execute();
2118
			            		} catch(PDOException $e) {
2119
							return "error : ".$e->getMessage();
2120
		            			}
2121
		    			}
2122
					$error = create_db::import_file($tmp_dir.'airspace.sql');
2123
					update_db::insert_airspace_version($airspace_md5);
2124
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
2125
			}
2126
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
2127
		if ($error != '') {
2128
			return $error;
2129
		} elseif ($globalDebug) echo "Done\n";
2130
		return '';
2131
	}
2132
2133
	public static function update_geoid_fam() {
2134
		global $tmp_dir, $globalDebug, $globalGeoidSource;
2135
		$error = '';
2136
		if ($globalDebug) echo "Geoid from FlightAirMap website : Download...";
2137
		update_db::download('http://data.flightairmap.fr/data/geoid/'.$globalGeoidSource.'.pgm.gz.md5',$tmp_dir.$globalGeoidSource.'.pgm.gz.md5');
2138
		if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz.md5')) {
2139
			$geoid_md5_file = explode(' ',file_get_contents($tmp_dir.$globalGeoidSource.'.pgm.gz.md5'));
2140
			$geoid_md5 = $geoid_md5_file[0];
2141
			if (!update_db::check_geoid_version($geoid_md5)) {
2142
				update_db::download('http://data.flightairmap.fr/data/geoid/'.$globalGeoidSource.'.pgm.gz',$tmp_dir.$globalGeoidSource.'.pgm.gz');
2143
				if (file_exists($tmp_dir.$globalGeoidSource.'.pgm.gz')) {
2144
					if ($globalDebug) echo "Gunzip...";
2145
					update_db::gunzip($tmp_dir.$globalGeoidSource.'.pgm.gz',dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm');
2146
					if (file_exists(dirname(__FILE__).'/../data/'.$globalGeoidSource.'.pgm')) {
2147
						update_db::insert_geoid_version($geoid_md5);
2148
					}
2149
				} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz'." doesn't exist. Download failed.";
2150
			}
2151
		} else $error = "File ".$tmp_dir.$globalGeoidSource.'.pgm.gz.md5'." doesn't exist. Download failed.";
2152
		if ($error != '') {
2153
			return $error;
2154
		} elseif ($globalDebug) echo "Done\n";
2155
		return '';
2156
	}
2157
2158
	public static function update_tle() {
2159
		global $tmp_dir, $globalDebug;
2160
		if ($globalDebug) echo "Download TLE : Download...";
2161
		$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',
2162
		'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',
2163
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
2164
		foreach ($alltle as $filename) {
2165
			if ($globalDebug) echo "downloading ".$filename.'...';
2166
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
2167
			if (file_exists($tmp_dir.$filename)) {
2168
				if ($globalDebug) echo "Add to DB ".$filename."...";
2169
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
2170
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
2171
			if ($error != '') {
2172
				echo $error."\n";
2173
			} elseif ($globalDebug) echo "Done\n";
2174
		}
2175
		return '';
2176
	}
2177
2178
	public static function update_models() {
2179
		global $tmp_dir, $globalDebug;
2180
		$error = '';
2181
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2182
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2183
		if (file_exists($tmp_dir.'models.md5sum')) {
2184
			if ($globalDebug) echo "Check files...\n";
2185
			$newmodelsdb = array();
2186
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2187
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2188
					$model = trim($row[2]);
2189
					$newmodelsdb[$model] = trim($row[0]);
2190
				}
2191
			}
2192
			$modelsdb = array();
2193
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2194
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2195
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2196
						$model = trim($row[2]);
2197
						$modelsdb[$model] = trim($row[0]);
2198
					}
2199
				}
2200
			}
2201
			$diff = array_diff($newmodelsdb,$modelsdb);
2202
			foreach ($diff as $key => $value) {
2203
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2204
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2205
				
2206
			}
2207
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2208
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2209
		if ($error != '') {
2210
			return $error;
2211
		} elseif ($globalDebug) echo "Done\n";
2212
		return '';
2213
	}
2214
2215
	public static function update_space_models() {
2216
		global $tmp_dir, $globalDebug;
2217
		$error = '';
2218
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2219
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2220
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2221
			if ($globalDebug) echo "Check files...\n";
2222
			$newmodelsdb = array();
2223
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2224
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2225
					$model = trim($row[2]);
2226
					$newmodelsdb[$model] = trim($row[0]);
2227
				}
2228
			}
2229
			$modelsdb = array();
2230
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2231
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2232
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2233
						$model = trim($row[2]);
2234
						$modelsdb[$model] = trim($row[0]);
2235
					}
2236
				}
2237
			}
2238
			$diff = array_diff($newmodelsdb,$modelsdb);
2239
			foreach ($diff as $key => $value) {
2240
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2241
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2242
				
2243
			}
2244
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2245
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2246
		if ($error != '') {
2247
			return $error;
2248
		} elseif ($globalDebug) echo "Done\n";
2249
		return '';
2250
	}
2251
2252
	public static function update_vehicules_models() {
2253
		global $tmp_dir, $globalDebug;
2254
		$error = '';
2255
		if ($globalDebug) echo "Vehicules models from FlightAirMap website : Download...";
2256
		update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',$tmp_dir.'vehicules_models.md5sum');
2257
		if (file_exists($tmp_dir.'vehicules_models.md5sum')) {
2258
			if ($globalDebug) echo "Check files...\n";
2259
			$newmodelsdb = array();
2260
			if (($handle = fopen($tmp_dir.'vehicules_models.md5sum','r')) !== FALSE) {
2261
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2262
					$model = trim($row[2]);
2263
					$newmodelsdb[$model] = trim($row[0]);
2264
				}
2265
			}
2266
			$modelsdb = array();
2267
			if (file_exists(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum')) {
2268
				if (($handle = fopen(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum','r')) !== FALSE) {
2269
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2270
						$model = trim($row[2]);
2271
						$modelsdb[$model] = trim($row[0]);
2272
					}
2273
				}
2274
			}
2275
			$diff = array_diff($newmodelsdb,$modelsdb);
2276
			foreach ($diff as $key => $value) {
2277
				if ($globalDebug) echo 'Downloading vehicules model '.$key.' ...'."\n";
2278
				update_db::download('http://data.flightairmap.fr/data/models/vehicules/'.$key,dirname(__FILE__).'/../models/vehicules/'.$key);
2279
				
2280
			}
2281
			update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum');
2282
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2283
		if ($error != '') {
2284
			return $error;
2285
		} elseif ($globalDebug) echo "Done\n";
2286
		return '';
2287
	}
2288
2289
	public static function update_aircraft() {
2290
		global $tmp_dir, $globalDebug;
2291
		date_default_timezone_set('UTC');
2292
		//$error = '';
2293
		/*
2294
		if ($globalDebug) echo "Aircrafts : Download...";
2295
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2296
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2297
		//$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);
2298
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2299
//		echo strlen($data_req);
2300
		echo $data;
2301
		*/
2302
		if (file_exists($tmp_dir.'aircrafts.html')) {
2303
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2304
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2305
		    $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...
2306
		    //echo $result;
2307
		    //var_dump(str_get_html($result));
2308
		    //print_r(self::table2array($result));
2309
		}
2310
2311
	}
2312
	
2313
	public static function update_notam() {
2314
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2315
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2316
		$Common = new Common();
2317
		date_default_timezone_set('UTC');
2318
		$query = 'TRUNCATE TABLE notam';
2319
		try {
2320
			$Connection = new Connection();
2321
			$sth = $Connection->db->prepare($query);
2322
                        $sth->execute();
2323
                } catch(PDOException $e) {
2324
                        return "error : ".$e->getMessage();
2325
                }
2326
2327
		$error = '';
2328
		if ($globalDebug) echo "Notam : Download...";
2329
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2330
		if (file_exists($tmp_dir.'notam.rss')) {
2331
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2332
			foreach ($notams['channel']['item'] as $notam) {
2333
				$title = explode(':',$notam['title']);
2334
				$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...
2335
				unset($title[0]);
2336
				$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...
2337
				$description = strip_tags($notam['description'],'<pre>');
2338
				preg_match(':^(.*?)<pre>:',$description,$match);
2339
				$q = explode('/',$match[1]);
2340
				$data['fir'] = $q[0];
2341
				$data['code'] = $q[1];
2342
				$ifrvfr = $q[2];
2343
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2344
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2345
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2346
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2347
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2348
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2349
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2350
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2351
				//$data['scope'] = $q[4];
2352
				$data['lower_limit'] = $q[5];
2353
				$data['upper_limit'] = $q[6];
2354
				$latlonrad = $q[7];
2355
				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...
2356
				$latitude = $Common->convertDec($las,'latitude');
2357
				$longitude = $Common->convertDec($lns,'longitude');
2358
				if ($lac == 'S') $latitude = '-'.$latitude;
2359
				if ($lnc == 'W') $longitude = '-'.$longitude;
2360
				$data['center_latitude'] = $latitude;
2361
				$data['center_longitude'] = $longitude;
2362
				$data['radius'] = intval($radius);
2363
				
2364
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2365
				$data['text'] = $match[1];
2366
				preg_match(':</pre>(.*?)$:',$description,$match);
2367
				$fromto = $match[1];
2368
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2369
				$fromall = trim($match[1]);
2370
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2371
				$from = trim($match[1]);
2372
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2373
				preg_match('#TO:(.*?)$#',$fromto,$match);
2374
				$toall = trim($match[1]);
2375
				if (!preg_match(':Permanent:',$toall)) {
2376
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2377
					$to = trim($match[1]);
2378
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2379
					$data['permanent'] = 0;
2380
				} else {
2381
				    $data['date_end'] = NULL;
2382
				    $data['permanent'] = 1;
2383
				}
2384
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2385
				$NOTAM = new NOTAM();
2386
				$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']);
2387
				unset($data);
2388
			} 
2389
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2390
		if ($error != '') {
2391
			return $error;
2392
		} elseif ($globalDebug) echo "Done\n";
2393
		return '';
2394
	}
2395
	
2396
	public static function create_airspace() {
2397
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2398
		$Connection = new Connection();
2399
		if ($Connection->tableExists('airspace')) {
2400
			if ($globalDBdriver == 'mysql') {
2401
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2402
			} else {
2403
				$query = 'DROP TABLE airspace';
2404
			}
2405
			try {
2406
				$Connection = new Connection();
2407
				$sth = $Connection->db->prepare($query);
2408
				$sth->execute();
2409
			} catch(PDOException $e) {
2410
				return "error : ".$e->getMessage();
2411
			}
2412
		}
2413
		$Common = new Common();
2414
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2415
		$airspace_json = json_decode($airspace_lst,true);
2416
		foreach ($airspace_json['records'] as $airspace) {
2417
			if ($globalDebug) echo $airspace['name']."...\n";
2418
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2419
			if (file_exists($tmp_dir.$airspace['name'])) {
2420
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2421
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2422
				if ($globalDBdriver == 'mysql') {
2423
					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'].'"');
2424
				} else {
2425
					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'].'"');
2426
				}
2427
			}
2428
		}
2429
	}
2430
	
2431
	public static function fix_icaotype() {
2432
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
2433
		$Spotter = new Spotter();
2434
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
2435
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
2436
			try {
2437
				$Connection = new Connection();
2438
				$sth = $Connection->db->prepare($query);
2439
				$sth->execute(array(':new' => $new, ':old' => $old));
2440
			} catch(PDOException $e) {
2441
				return "error : ".$e->getMessage();
2442
			}
2443
		}
2444
	}
2445
2446
	public static function check_last_update() {
2447
		global $globalDBdriver;
2448
		if ($globalDBdriver == 'mysql') {
2449
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2450
		} else {
2451
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2452
		}
2453
		try {
2454
			$Connection = new Connection();
2455
			$sth = $Connection->db->prepare($query);
2456
                        $sth->execute();
2457
                } catch(PDOException $e) {
2458
                        return "error : ".$e->getMessage();
2459
                }
2460
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2461
                if ($row['nb'] > 0) return false;
2462
                else return true;
2463
	}
2464
2465
	public static function insert_last_update() {
2466
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2467
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2468
		try {
2469
			$Connection = new Connection();
2470
			$sth = $Connection->db->prepare($query);
2471
                        $sth->execute();
2472
                } catch(PDOException $e) {
2473
                        return "error : ".$e->getMessage();
2474
                }
2475
	}
2476
2477
	public static function check_airspace_version($version) {
2478
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2479
		try {
2480
			$Connection = new Connection();
2481
			$sth = $Connection->db->prepare($query);
2482
                        $sth->execute(array(':version' => $version));
2483
                } catch(PDOException $e) {
2484
                        return "error : ".$e->getMessage();
2485
                }
2486
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2487
                if ($row['nb'] > 0) return true;
2488
                else return false;
2489
	}
2490
2491
	public static function check_geoid_version($version) {
2492
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'geoid_version' AND value = :version";
2493
		try {
2494
			$Connection = new Connection();
2495
			$sth = $Connection->db->prepare($query);
2496
                        $sth->execute(array(':version' => $version));
2497
                } catch(PDOException $e) {
2498
                        return "error : ".$e->getMessage();
2499
                }
2500
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2501
                if ($row['nb'] > 0) return true;
2502
                else return false;
2503
	}
2504
2505
	public static function check_marine_identity_version($version) {
2506
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'marine_identity_version' AND value = :version";
2507
		try {
2508
			$Connection = new Connection();
2509
			$sth = $Connection->db->prepare($query);
2510
                        $sth->execute(array(':version' => $version));
2511
                } catch(PDOException $e) {
2512
                        return "error : ".$e->getMessage();
2513
                }
2514
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2515
                if ($row['nb'] > 0) return true;
2516
                else return false;
2517
	}
2518
2519
2520
	public static function insert_airspace_version($version) {
2521
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2522
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2523
		try {
2524
			$Connection = new Connection();
2525
			$sth = $Connection->db->prepare($query);
2526
			$sth->execute(array(':version' => $version));
2527
		} catch(PDOException $e) {
2528
			return "error : ".$e->getMessage();
2529
		}
2530
	}
2531
	
2532
	public static function insert_geoid_version($version) {
2533
		$query = "DELETE FROM config WHERE name = 'geoid_version';
2534
			INSERT INTO config (name,value) VALUES ('geoid_version',:version);";
2535
		try {
2536
			$Connection = new Connection();
2537
			$sth = $Connection->db->prepare($query);
2538
                        $sth->execute(array(':version' => $version));
2539
                } catch(PDOException $e) {
2540
                        return "error : ".$e->getMessage();
2541
                }
2542
	}
2543
2544
	public static function insert_marine_identity_version($version) {
2545
		$query = "DELETE FROM config WHERE name = 'marine_identity_version';
2546
			INSERT INTO config (name,value) VALUES ('marine_identity_version',:version);";
2547
		try {
2548
			$Connection = new Connection();
2549
			$sth = $Connection->db->prepare($query);
2550
                        $sth->execute(array(':version' => $version));
2551
                } catch(PDOException $e) {
2552
                        return "error : ".$e->getMessage();
2553
                }
2554
	}
2555
2556
	public static function check_last_notam_update() {
2557
		global $globalDBdriver;
2558
		if ($globalDBdriver == 'mysql') {
2559
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2560
		} else {
2561
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2562
		}
2563
		try {
2564
			$Connection = new Connection();
2565
			$sth = $Connection->db->prepare($query);
2566
                        $sth->execute();
2567
                } catch(PDOException $e) {
2568
                        return "error : ".$e->getMessage();
2569
                }
2570
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2571
                if ($row['nb'] > 0) return false;
2572
                else return true;
2573
	}
2574
2575
	public static function insert_last_notam_update() {
2576
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2577
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2578
		try {
2579
			$Connection = new Connection();
2580
			$sth = $Connection->db->prepare($query);
2581
                        $sth->execute();
2582
                } catch(PDOException $e) {
2583
                        return "error : ".$e->getMessage();
2584
                }
2585
	}
2586
2587
	public static function check_last_airspace_update() {
2588
		global $globalDBdriver;
2589
		if ($globalDBdriver == 'mysql') {
2590
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2591
		} else {
2592
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2593
		}
2594
		try {
2595
			$Connection = new Connection();
2596
			$sth = $Connection->db->prepare($query);
2597
                        $sth->execute();
2598
                } catch(PDOException $e) {
2599
                        return "error : ".$e->getMessage();
2600
                }
2601
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2602
                if ($row['nb'] > 0) return false;
2603
                else return true;
2604
	}
2605
2606
	public static function insert_last_airspace_update() {
2607
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2608
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2609
		try {
2610
			$Connection = new Connection();
2611
			$sth = $Connection->db->prepare($query);
2612
                        $sth->execute();
2613
                } catch(PDOException $e) {
2614
                        return "error : ".$e->getMessage();
2615
                }
2616
	}
2617
2618
	public static function check_last_geoid_update() {
2619
		global $globalDBdriver;
2620
		if ($globalDBdriver == 'mysql') {
2621
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2622
		} else {
2623
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_geoid' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2624
		}
2625
		try {
2626
			$Connection = new Connection();
2627
			$sth = $Connection->db->prepare($query);
2628
                        $sth->execute();
2629
                } catch(PDOException $e) {
2630
                        return "error : ".$e->getMessage();
2631
                }
2632
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2633
                if ($row['nb'] > 0) return false;
2634
                else return true;
2635
	}
2636
2637
	public static function insert_last_geoid_update() {
2638
		$query = "DELETE FROM config WHERE name = 'last_update_geoid';
2639
			INSERT INTO config (name,value) VALUES ('last_update_geoid',NOW());";
2640
		try {
2641
			$Connection = new Connection();
2642
			$sth = $Connection->db->prepare($query);
2643
                        $sth->execute();
2644
                } catch(PDOException $e) {
2645
                        return "error : ".$e->getMessage();
2646
                }
2647
	}
2648
2649
	public static function check_last_owner_update() {
2650
		global $globalDBdriver;
2651
		if ($globalDBdriver == 'mysql') {
2652
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2653
		} else {
2654
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2655
		}
2656
		try {
2657
			$Connection = new Connection();
2658
			$sth = $Connection->db->prepare($query);
2659
                        $sth->execute();
2660
                } catch(PDOException $e) {
2661
                        return "error : ".$e->getMessage();
2662
                }
2663
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2664
                if ($row['nb'] > 0) return false;
2665
                else return true;
2666
	}
2667
2668
	public static function insert_last_owner_update() {
2669
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2670
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2671
		try {
2672
			$Connection = new Connection();
2673
			$sth = $Connection->db->prepare($query);
2674
                        $sth->execute();
2675
                } catch(PDOException $e) {
2676
                        return "error : ".$e->getMessage();
2677
                }
2678
	}
2679
	public static function check_last_schedules_update() {
2680
		global $globalDBdriver;
2681
		if ($globalDBdriver == 'mysql') {
2682
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2683
		} else {
2684
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2685
		}
2686
		try {
2687
			$Connection = new Connection();
2688
			$sth = $Connection->db->prepare($query);
2689
                        $sth->execute();
2690
                } catch(PDOException $e) {
2691
                        return "error : ".$e->getMessage();
2692
                }
2693
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2694
                if ($row['nb'] > 0) return false;
2695
                else return true;
2696
	}
2697
2698
	public static function insert_last_schedules_update() {
2699
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2700
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2701
		try {
2702
			$Connection = new Connection();
2703
			$sth = $Connection->db->prepare($query);
2704
                        $sth->execute();
2705
                } catch(PDOException $e) {
2706
                        return "error : ".$e->getMessage();
2707
                }
2708
	}
2709
	public static function check_last_tle_update() {
2710
		global $globalDBdriver;
2711
		if ($globalDBdriver == 'mysql') {
2712
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2713
		} else {
2714
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2715
		}
2716
		try {
2717
			$Connection = new Connection();
2718
			$sth = $Connection->db->prepare($query);
2719
                        $sth->execute();
2720
                } catch(PDOException $e) {
2721
                        return "error : ".$e->getMessage();
2722
                }
2723
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2724
                if ($row['nb'] > 0) return false;
2725
                else return true;
2726
	}
2727
2728
	public static function insert_last_tle_update() {
2729
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2730
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2731
		try {
2732
			$Connection = new Connection();
2733
			$sth = $Connection->db->prepare($query);
2734
                        $sth->execute();
2735
                } catch(PDOException $e) {
2736
                        return "error : ".$e->getMessage();
2737
                }
2738
	}
2739
	public static function check_last_marine_identity_update() {
2740
		global $globalDBdriver;
2741
		if ($globalDBdriver == 'mysql') {
2742
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2743
		} else {
2744
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2745
		}
2746
		try {
2747
			$Connection = new Connection();
2748
			$sth = $Connection->db->prepare($query);
2749
                        $sth->execute();
2750
                } catch(PDOException $e) {
2751
                        return "error : ".$e->getMessage();
2752
                }
2753
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2754
                if ($row['nb'] > 0) return false;
2755
                else return true;
2756
	}
2757
2758
	public static function insert_last_marine_identity_update() {
2759
		$query = "DELETE FROM config WHERE name = 'last_update_marine_identity';
2760
			INSERT INTO config (name,value) VALUES ('last_update_marine_identity',NOW());";
2761
		try {
2762
			$Connection = new Connection();
2763
			$sth = $Connection->db->prepare($query);
2764
                        $sth->execute();
2765
                } catch(PDOException $e) {
2766
                        return "error : ".$e->getMessage();
2767
                }
2768
	}
2769
	public static function delete_duplicatemodes() {
2770
		global $globalDBdriver;
2771
		if ($globalDBdriver == 'mysql') {
2772
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
2773
		} else {
2774
			$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'";
2775
		}
2776
		try {
2777
			$Connection = new Connection();
2778
			$sth = $Connection->db->prepare($query);
2779
                        $sth->execute();
2780
                } catch(PDOException $e) {
2781
                        return "error : ".$e->getMessage();
2782
                }
2783
	}
2784
	public static function delete_duplicateowner() {
2785
		global $globalDBdriver;
2786
		if ($globalDBdriver == 'mysql') {
2787
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
2788
		} else {
2789
			$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)";
2790
		}
2791
		try {
2792
			$Connection = new Connection();
2793
			$sth = $Connection->db->prepare($query);
2794
                        $sth->execute();
2795
                } catch(PDOException $e) {
2796
                        return "error : ".$e->getMessage();
2797
                }
2798
	}
2799
	
2800
	public static function update_all() {
2801
		global $globalMasterServer, $globalMasterSource;
2802
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2803
			if (isset($globalMasterSource) && $globalMasterSource) {
2804
				echo update_db::update_routes();
2805
				echo update_db::update_translation();
2806
				//echo update_db::update_notam_fam();
2807
				echo update_db::update_ModeS();
2808
				//echo update_db::update_ModeS_flarm();
2809
				echo update_db::update_ModeS_ogn();
2810
				echo update_db::update_ModeS_faa();
2811
				echo update_db::fix_icaotype();
2812
				echo update_db::update_banned_fam();
2813
				//echo update_db::delete_duplicatemodes();
2814
			} else {
2815
				//echo update_db::update_routes();
2816
				echo update_db::update_routes_fam();
2817
				echo update_db::update_translation();
2818
				echo update_db::update_translation_fam();
2819
				//echo update_db::update_notam_fam();
2820
				//echo update_db::update_ModeS();
2821
				echo update_db::update_ModeS_fam();
2822
				//echo update_db::update_ModeS_flarm();
2823
				echo update_db::update_ModeS_ogn();
2824
				//echo update_db::delete_duplicatemodes();
2825
				echo update_db::update_banned_fam();
2826
			}
2827
		}
2828
	}
2829
}
2830
2831
//echo update_db::update_airports();
2832
//echo update_db::translation();
2833
//echo update_db::update_waypoints();
2834
//echo update_db::update_airspace();
2835
//echo update_db::update_notam();
2836
//echo update_db::update_ivao();
2837
//echo update_db::update_ModeS_flarm();
2838
//echo update_db::update_ModeS_ogn();
2839
//echo update_db::update_aircraft();
2840
//$update_db = new update_db();
2841
//echo update_db::update_owner();
2842
//update_db::update_translation_fam();
2843
//echo update_db::update_routes();
2844
//update_db::update_models();
2845
//echo $update_db::update_skyteam();
2846
//echo $update_db::update_tle();
2847
//echo update_db::update_notam_fam();
2848
//echo update_db::create_airspace();
2849
//echo update_db::update_ModeS();
2850
//echo update_db::update_ModeS_fam();
2851
//echo update_db::update_routes_fam();
2852
//echo update_db::update_ModeS_faa();
2853
//echo update_db::update_banned_fam();
2854
//echo update_db::modes_faa();
2855
//echo update_db::update_owner_fam();
2856
//echo update_db::delete_duplicateowner();
2857
//echo update_db::fix_icaotype();
2858
?>
2859