Completed
Push — master ( 057712...43b720 )
by Yannick
10:00
created

update_db::check_geoid_version()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 5
nop 1
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
//require_once('libs/simple_html_dom.php');
3
require(dirname(__FILE__).'/../require/settings.php');
4
require_once(dirname(__FILE__).'/../require/class.Common.php');
5
require_once(dirname(__FILE__).'/../require/class.Connection.php');
6
7
$tmp_dir = dirname(__FILE__).'/tmp/';
8
//$globalDebug = true;
9
//$globalTransaction = true;
10
class update_db {
11
	public static $db_sqlite;
12
13
	public static function download($url, $file, $referer = '') {
14
		//$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
		$query = 'TRUNCATE TABLE airport';
667
		try {
668
			$Connection = new Connection();
669
			$sth = $Connection->db->prepare($query);
670
                        $sth->execute();
671
                } catch(PDOException $e) {
672
                        return "error : ".$e->getMessage();
673
                }
674
675
676
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
677
		try {
678
			$Connection = new Connection();
679
			$sth = $Connection->db->prepare($query);
680
                        $sth->execute();
681
                } catch(PDOException $e) {
682
                        return "error : ".$e->getMessage();
683
                }
684
685
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
686
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
687
		$Connection = new Connection();
688
		$sth_dest = $Connection->db->prepare($query_dest);
689
		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...
690
  
691
		$i = 0;
692
		while($row = sparql_fetch_array($result))
693
		{
694
			if ($i >= 1) {
695
			//print_r($row);
696
			if (!isset($row['iata'])) $row['iata'] = '';
697
			if (!isset($row['icao'])) $row['icao'] = '';
698
			if (!isset($row['type'])) $row['type'] = '';
699
			if (!isset($row['altitude'])) $row['altitude'] = '';
700
			if (isset($row['city_bis'])) {
701
				$row['city'] = $row['city_bis'];
702
			}
703
			if (!isset($row['city'])) $row['city'] = '';
704
			if (!isset($row['country'])) $row['country'] = '';
705
			if (!isset($row['homepage'])) $row['homepage'] = '';
706
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
707
			if (!isset($row['name'])) continue;
708
			if (!isset($row['image'])) {
709
				$row['image'] = '';
710
				$row['image_thumb'] = '';
711
			} else {
712
				$image = str_replace(' ','_',$row['image']);
713
				$digest = md5($image);
714
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
715
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
716
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
717
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
718
			}
719
			
720
			$country = explode('-',$row['country']);
721
			$row['country'] = $country[0];
722
			
723
			$row['type'] = trim($row['type']);
724
			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'])) {
725
				$row['type'] = 'Military';
726
			} 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') {
727
				$row['type'] = 'small_airport';
728
			}
729
			
730
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
731
			$query_dest_values = array(':airport_id' => $i, ':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => $row['altitude'],':type' => $row['type'],':city' => $row['city'],':country' => $row['country'],':home_link' => $row['homepage'],':wikipedia_link' => $row['wikipedia_page'],':image' => $row['image'],':image_thumb' => $row['image_thumb']);
732
			//print_r($query_dest_values);
733
			
734
			try {
735
				$sth_dest->execute($query_dest_values);
736
			} catch(PDOException $e) {
737
				return "error : ".$e->getMessage();
738
			}
739
			}
740
741
			$i++;
742
		}
743
		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...
744
		echo "Delete duplicate rows...\n";
745
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
746
		try {
747
			$Connection = new Connection();
748
			$sth = $Connection->db->prepare($query);
749
                        $sth->execute();
750
                } catch(PDOException $e) {
751
                        return "error : ".$e->getMessage();
752
                }
753
754
755
		if ($globalDebug) echo "Insert Not available Airport...\n";
756
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
757
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
758
		$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' => '');
759
		try {
760
			$Connection = new Connection();
761
			$sth = $Connection->db->prepare($query);
762
                        $sth->execute($query_values);
763
                } catch(PDOException $e) {
764
                        return "error : ".$e->getMessage();
765
                }
766
		$i++;
767
/*
768
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
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
		echo "Download data from ourairports.com...\n";
779
		$delimiter = ',';
780
		$out_file = $tmp_dir.'airports.csv';
781
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
782
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
783
		echo "Add data from ourairports.com...\n";
784
785
		$header = NULL;
786
		if (($handle = fopen($out_file, 'r')) !== FALSE)
787
		{
788
			$Connection = new Connection();
789
			//$Connection->db->beginTransaction();
790
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
791
			{
792
				if(!$header) $header = $row;
793
				else {
794
					$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...
795
					$data = array_combine($header, $row);
796
					try {
797
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
798
						$sth->execute(array(':icao' => $data['gps_code']));
799
					} catch(PDOException $e) {
800
						return "error : ".$e->getMessage();
801
					}
802
					if ($sth->fetchColumn() > 0) {
803
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
804
						try {
805
							$sth = $Connection->db->prepare($query);
806
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
807
						} catch(PDOException $e) {
808
							return "error : ".$e->getMessage();
809
						}
810
					} else {
811
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
812
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
813
						$query_values = array(':airport_id' => $i, ':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => $data['elevation_ft'],':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
814
						try {
815
							$sth = $Connection->db->prepare($query);
816
							$sth->execute($query_values);
817
						} catch(PDOException $e) {
818
							return "error : ".$e->getMessage();
819
						}
820
						$i++;
821
					}
822
				}
823
			}
824
			fclose($handle);
825
			//$Connection->db->commit();
826
		}
827
828
		echo "Download data from another free database...\n";
829
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
830
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
831
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
832
		update_db::unzip($out_file);
833
		$header = NULL;
834
		echo "Add data from another free database...\n";
835
		$delimiter = ':';
836
		$Connection = new Connection();
837
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
838
		{
839
			//$Connection->db->beginTransaction();
840
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
841
			{
842
				if(!$header) $header = $row;
843
				else {
844
					$data = $row;
845
846
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
847
					try {
848
						$sth = $Connection->db->prepare($query);
849
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
850
					} catch(PDOException $e) {
851
						return "error : ".$e->getMessage();
852
					}
853
				}
854
			}
855
			fclose($handle);
856
			//$Connection->db->commit();
857
		}
858
859
		echo "Put type military for all air base";
860
		$Connection = new Connection();
861
		try {
862
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
863
			$sth->execute();
864
		} catch(PDOException $e) {
865
			return "error : ".$e->getMessage();
866
		}
867
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
868
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
869
			try {
870
				$sth2 = $Connection->db->prepare($query2);
871
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
872
			} catch(PDOException $e) {
873
				return "error : ".$e->getMessage();
874
			}
875
		}
876
877
878
879
                return "success";
880
	}
881
	
882
	public static function translation() {
883
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
884
		global $tmp_dir, $globalTransaction;
885
		$Spotter = new Spotter();
886
		//$out_file = $tmp_dir.'translation.zip';
887
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
888
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
889
		
890
		//$query = 'TRUNCATE TABLE translation';
891
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
892
		try {
893
			$Connection = new Connection();
894
			$sth = $Connection->db->prepare($query);
895
                        $sth->execute(array(':source' => 'translation.csv'));
896
                } catch(PDOException $e) {
897
                        return "error : ".$e->getMessage();
898
                }
899
900
		
901
		//update_db::unzip($out_file);
902
		$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...
903
		$delimiter = ';';
904
		$Connection = new Connection();
905
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
906
		{
907
			$i = 0;
908
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
909
			//$Connection->db->beginTransaction();
910
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
911
			{
912
				$i++;
913
				if($i > 12) {
914
					$data = $row;
915
					$operator = $data[2];
916
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
917
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
918
                                                //echo substr($operator, 0, 2)."\n";;
919
                                                if (count($airline_array) > 0) {
920
							//print_r($airline_array);
921
							$operator = $airline_array[0]['icao'].substr($operator,2);
922
                                                }
923
                                        }
924
					
925
					$operator_correct = $data[3];
926
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
927
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
928
                                                if (count($airline_array) > 0) {
929
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
930
                                            	}
931
                                        }
932
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
933
					try {
934
						$sth = $Connection->db->prepare($query);
935
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
936
					} catch(PDOException $e) {
937
						return "error : ".$e->getMessage();
938
					}
939
				}
940
			}
941
			fclose($handle);
942
			//$Connection->db->commit();
943
		}
944
		return '';
945
        }
946
	
947
	public static function translation_fam() {
948
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
949
		global $tmp_dir, $globalTransaction;
950
		$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...
951
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
952
		try {
953
			$Connection = new Connection();
954
			$sth = $Connection->db->prepare($query);
955
                        $sth->execute(array(':source' => 'website_fam'));
956
                } catch(PDOException $e) {
957
                        return "error : ".$e->getMessage();
958
                }
959
960
		
961
		//update_db::unzip($out_file);
962
		$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...
963
		$delimiter = "\t";
964
		$Connection = new Connection();
965
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
966
		{
967
			$i = 0;
968
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
969
			//$Connection->db->beginTransaction();
970
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
971
			{
972
				if ($i > 0) {
973
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
974
					try {
975
						$sth = $Connection->db->prepare($query);
976
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
977
					} catch(PDOException $e) {
978
						return "error : ".$e->getMessage();
979
					}
980
				}
981
				$i++;
982
			}
983
			fclose($handle);
984
			//$Connection->db->commit();
985
		}
986
		return '';
987
        }
988
989
	/*
990
	* This function use FAA public data.
991
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
992
	*/
993
	public static function modes_faa() {
994
		global $tmp_dir, $globalTransaction, $globalDebug;
995
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
996
		try {
997
			$Connection = new Connection();
998
			$sth = $Connection->db->prepare($query);
999
                        $sth->execute(array(':source' => 'website_faa'));
1000
                } catch(PDOException $e) {
1001
                        return "error : ".$e->getMessage();
1002
                }
1003
1004
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1005
		try {
1006
			$Connection = new Connection();
1007
			$sth = $Connection->db->prepare($query);
1008
                        $sth->execute(array(':source' => 'website_faa'));
1009
                } catch(PDOException $e) {
1010
                        return "error : ".$e->getMessage();
1011
                }
1012
1013
		$delimiter = ",";
1014
		$mfr = array();
1015
		$Connection = new Connection();
1016
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1017
		{
1018
			$i = 0;
1019
			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...
1020
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1021
			{
1022
				if ($i > 0) {
1023
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1024
					try {
1025
						$sths = $Connection->db->prepare($query_search);
1026
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1027
					} catch(PDOException $e) {
1028
						return "error s : ".$e->getMessage();
1029
					}
1030
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1031
					if (!empty($result_search)) {
1032
						if ($globalDebug) echo '.';
1033
							//if ($globalDBdriver == 'mysql') {
1034
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1035
							//} else {
1036
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1037
							//}
1038
						try {
1039
							$sthi = $Connection->db->prepare($queryi);
1040
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1041
						} catch(PDOException $e) {
1042
							return "error u : ".$e->getMessage();
1043
						}
1044
					} else {
1045
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1046
						try {
1047
							$sthsm = $Connection->db->prepare($query_search_mfr);
1048
							$sthsm->execute(array(':mfr' => $data[2]));
1049
						} catch(PDOException $e) {
1050
							return "error mfr : ".$e->getMessage();
1051
						}
1052
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1053
						if (!empty($result_search_mfr)) {
1054
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1055
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1056
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1057
							try {
1058
								$sthf = $Connection->db->prepare($queryf);
1059
								$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'));
1060
							} catch(PDOException $e) {
1061
								return "error f : ".$e->getMessage();
1062
							}
1063
						}
1064
					}
1065
					if (strtotime($data[29]) > time()) {
1066
						if ($globalDebug) echo 'i';
1067
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1068
						try {
1069
							$sth = $Connection->db->prepare($query);
1070
							$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'));
1071
						} catch(PDOException $e) {
1072
							return "error i : ".$e->getMessage();
1073
						}
1074
					}
1075
				}
1076
				if ($i % 90 == 0) {
1077
					if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

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