Completed
Push — master ( 06e80e...0e7c7f )
by Yannick
13:07
created

update_db::update_routes()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 16
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 30
nop 0
dl 0
loc 16
rs 8.2222
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
            				$aircraft_name = $line[2];
360
            				// Check if we can find ICAO, else set it to GLID
361
            				$aircraft_name_split = explode(' ',$aircraft_name);
362
            				$search_more = '';
363
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
364
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
365
            				$sth_search = $Connection->db->prepare($query_search);
366
					try {
367
                                    		$sth_search->execute();
368
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
369
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
370
					} catch(PDOException $e) {
371
						return "error : ".$e->getMessage();
372
					}
373
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
374
					// Add data to db
375
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
376
						//$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']);
377
						$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');
378
						//print_r($query_dest_values);
379
						$sth_dest->execute($query_dest_values);
380
					}
381
				}
382
				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...
383
			} catch(PDOException $e) {
384
				return "error : ".$e->getMessage();
385
			}
386
		}
387
388
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
389
		try {
390
			$Connection = new Connection();
391
			$sth = $Connection->db->prepare($query);
392
                        $sth->execute(array(':source' => $database_file));
393
                } catch(PDOException $e) {
394
                        return "error : ".$e->getMessage();
395
                }
396
		return '';
397
	}
398
399
	public static function retrieve_owner($database_file,$country = 'F') {
400
		global $globalTransaction, $globalMasterSource;
401
		//$query = 'TRUNCATE TABLE aircraft_modes';
402
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source; DELETE FROM aircraft_modes WHERE Source = :source;";
403
		try {
404
			$Connection = new Connection();
405
			$sth = $Connection->db->prepare($query);
406
                        $sth->execute(array(':source' => $database_file));
407
                } catch(PDOException $e) {
408
                        return "error : ".$e->getMessage();
409
                }
410
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
411
		$Spotter = new Spotter();
412
		if ($fh = fopen($database_file,"r")) {
413
			//$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)';
414
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
415
		        $query_modes = 'INSERT INTO aircraft_modes (ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:modes,:modescountry,:registration,:icaotypecode,:source)';
416
		        
417
			$Connection = new Connection();
418
			$sth_dest = $Connection->db->prepare($query_dest);
419
			$sth_modes = $Connection->db->prepare($query_modes);
420
			try {
421
				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...
422
				$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...
423
            			while (!feof($fh)) {
424
            				$line = fgetcsv($fh,9999,',','"');
425
            				$values = array();
426
            				//print_r($line);
427
            				if ($country == 'F') {
428
            				    $values['registration'] = $line[0];
429
            				    $values['base'] = $line[4];
430
            				    $values['owner'] = $line[5];
431
            				    if ($line[6] == '') $values['date_first_reg'] = null;
432
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
433
					    $values['cancel'] = $line[7];
434
					} elseif ($country == 'EI') {
435
					    // TODO : add modeS & reg to aircraft_modes
436
            				    $values['registration'] = $line[0];
437
            				    $values['base'] = $line[3];
438
            				    $values['owner'] = $line[2];
439
            				    if ($line[1] == '') $values['date_first_reg'] = null;
440
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
441
					    $values['cancel'] = '';
442
					    $values['modes'] = $line[7];
443
					    $values['icao'] = $line[8];
444
					    
445
					} elseif ($country == 'HB') {
446
					    // TODO : add modeS & reg to aircraft_modes
447
            				    $values['registration'] = $line[0];
448
            				    $values['base'] = null;
449
            				    $values['owner'] = $line[5];
450
            				    $values['date_first_reg'] = null;
451
					    $values['cancel'] = '';
452
					    $values['modes'] = $line[4];
453
					    $values['icao'] = $line[7];
454
					} elseif ($country == 'OK') {
455
					    // TODO : add modeS & reg to aircraft_modes
456
            				    $values['registration'] = $line[3];
457
            				    $values['base'] = null;
458
            				    $values['owner'] = $line[5];
459
            				    if ($line[18] == '') $values['date_first_reg'] = null;
460
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
461
					    $values['cancel'] = '';
462
					} elseif ($country == 'VH') {
463
					    // TODO : add modeS & reg to aircraft_modes
464
            				    $values['registration'] = $line[0];
465
            				    $values['base'] = null;
466
            				    $values['owner'] = $line[12];
467
            				    if ($line[28] == '') $values['date_first_reg'] = null;
468
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
469
470
					    $values['cancel'] = $line[39];
471
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
472
            				    $values['registration'] = $line[0];
473
            				    $values['base'] = null;
474
            				    $values['owner'] = $line[4];
475
            				    $values['date_first_reg'] = null;
476
					    $values['cancel'] = '';
477
					} elseif ($country == 'CC') {
478
            				    $values['registration'] = $line[0];
479
            				    $values['base'] = null;
480
            				    $values['owner'] = $line[6];
481
            				    $values['date_first_reg'] = null;
482
					    $values['cancel'] = '';
483
					} elseif ($country == 'HJ') {
484
            				    $values['registration'] = $line[0];
485
            				    $values['base'] = null;
486
            				    $values['owner'] = $line[8];
487
            				    if ($line[7] == '') $values['date_first_reg'] = null;
488
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
489
					    $values['cancel'] = '';
490
					} elseif ($country == 'PP') {
491
            				    $values['registration'] = $line[0];
492
            				    $values['base'] = null;
493
            				    $values['owner'] = $line[4];
494
            				    if ($line[6] == '') $values['date_first_reg'] = null;
495
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
496
					    $values['cancel'] = $line[7];
497
					} elseif ($country == 'E7') {
498
            				    $values['registration'] = $line[0];
499
            				    $values['base'] = null;
500
            				    $values['owner'] = $line[4];
501
            				    if ($line[5] == '') $values['date_first_reg'] = null;
502
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
503
					    $values['cancel'] = '';
504
					} elseif ($country == '8Q') {
505
            				    $values['registration'] = $line[0];
506
            				    $values['base'] = null;
507
            				    $values['owner'] = $line[3];
508
            				    if ($line[7] == '') $values['date_first_reg'] = null;
509
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
510
					    $values['cancel'] = '';
511
					} elseif ($country == 'ZK') {
512
            				    $values['registration'] = $line[0];
513
            				    $values['base'] = null;
514
            				    $values['owner'] = $line[3];
515
            				    $values['date_first_reg'] = null;
516
					    $values['cancel'] = '';
517
					    $values['modes'] = $line[5];
518
					    $values['icao'] = $line[9];
519
					} elseif ($country == 'M') {
520
            				    $values['registration'] = $line[0];
521
            				    $values['base'] = null;
522
            				    $values['owner'] = $line[6];
523
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
524
					    $values['cancel'] = date("Y-m-d",strtotime($line[8]));
525
					    $values['modes'] = $line[4];
526
					    $values['icao'] = $line[10];
527
					} elseif ($country == 'OY') {
528
            				    $values['registration'] = $line[0];
529
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[4]));
530
					    $values['modes'] = $line[5];
531
					    $values['icao'] = $line[6];
532
					} elseif ($country == 'PH') {
533
            				    $values['registration'] = $line[0];
534
            				    $values['date_first_reg'] = date("Y-m-d",strtotime($line[3]));
535
					    $values['modes'] = $line[4];
536
					    $values['icao'] = $line[5];
537
					} elseif ($country == 'OM' || $country == 'TF') {
538
            				    $values['registration'] = $line[0];
539
            				    $values['base'] = null;
540
            				    $values['owner'] = $line[3];
541
            				    $values['date_first_reg'] = null;
542
					    $values['cancel'] = '';
543
					}
544
					if (isset($values['cancel']) && $values['cancel'] == '' && $values['registration'] != null && isset($values['owner'])) {
545
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
546
						$sth_dest->execute($query_dest_values);
547
					}
548
					if ($globalMasterSource && $values['registration'] != null && isset($values['modes']) && $values['modes'] != '') {
549
						$modescountry = $Spotter->countryFromAircraftRegistration($values['registration']);
550
						$query_modes_values = array(':registration' => $values['registration'],':modes' => $values['modes'],':modescountry' => $modescountry,':icaotypecode' => $values['icao'],':source' => $database_file);
551
						$sth_modes->execute($query_modes_values);
552
					}
553
				}
554
				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...
555
			} catch(PDOException $e) {
556
				return "error : ".$e->getMessage();
557
			}
558
		}
559
		return '';
560
	}
561
562
	/*
563
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
564
	*/
565
	public static function update_airports() {
566
		global $tmp_dir, $globalTransaction, $globalDebug;
567
568
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
569
		$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...
570
		$query = '
571
		    PREFIX dbo: <http://dbpedia.org/ontology/>
572
		    PREFIX dbp: <http://dbpedia.org/property/>
573
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
574
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
575
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
576
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
577
		    FROM <http://dbpedia.org>
578
		    WHERE {
579
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
580
581
			OPTIONAL {
582
			    ?airport dbo:icaoLocationIdentifier ?icao .
583
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
584
			}
585
586
			OPTIONAL {
587
			    ?airport dbo:iataLocationIdentifier ?iata .
588
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
589
			}
590
591
			OPTIONAL {
592
			    ?airport dbo:locationIdentifier ?lid .
593
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
594
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
595
			    OPTIONAL {
596
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
597
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
598
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
599
			    }
600
			    FILTER (!bound(?other_icao))
601
			}
602
603
			OPTIONAL {
604
			    ?airport dbo:faaLocationIdentifier ?faa .
605
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
606
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
607
			    OPTIONAL {
608
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
609
				?airport_x dbo:iataLocationIdentifier ?other_iata .
610
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
611
			    }
612
			    FILTER (!bound(?other_iata))
613
			}
614
615
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
616
	
617
			OPTIONAL {
618
			    ?airport rdfs:label ?name
619
			    FILTER (lang(?name) = "en")
620
			}
621
    
622
			OPTIONAL {
623
			    ?airport foaf:homepage ?homepage
624
			}
625
		    
626
			OPTIONAL {
627
			    ?airport dbp:coordinatesRegion ?country
628
			}
629
    
630
			OPTIONAL {
631
			    ?airport dbp:type ?type
632
			}
633
			
634
			OPTIONAL {
635
			    ?airport dbo:elevation ?altitude
636
			}
637
			OPTIONAL {
638
			    ?airport dbp:image ?image
639
			}
640
641
			{
642
			    ?airport geo:lat ?latitude .
643
			    ?airport geo:long ?longitude .
644
			    FILTER (datatype(?latitude) = xsd:float)
645
			    FILTER (datatype(?longitude) = xsd:float)
646
			} UNION {
647
			    ?airport geo:lat ?latitude .
648
			    ?airport geo:long ?longitude .
649
			    FILTER (datatype(?latitude) = xsd:double)
650
			    FILTER (datatype(?longitude) = xsd:double)
651
			    OPTIONAL {
652
				?airport geo:lat ?lat_f .
653
				?airport geo:long ?long_f .
654
				FILTER (datatype(?lat_f) = xsd:float)
655
				FILTER (datatype(?long_f) = xsd:float)
656
			    }
657
			    FILTER (!bound(?lat_f) && !bound(?long_f))
658
			}
659
660
		    }
661
		    ORDER BY ?airport
662
		';
663
		$result = sparql_query($query);
664
  
665
		$query = 'TRUNCATE TABLE airport';
666
		try {
667
			$Connection = new Connection();
668
			$sth = $Connection->db->prepare($query);
669
                        $sth->execute();
670
                } catch(PDOException $e) {
671
                        return "error : ".$e->getMessage();
672
                }
673
674
675
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
676
		try {
677
			$Connection = new Connection();
678
			$sth = $Connection->db->prepare($query);
679
                        $sth->execute();
680
                } catch(PDOException $e) {
681
                        return "error : ".$e->getMessage();
682
                }
683
684
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
685
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
686
		$Connection = new Connection();
687
		$sth_dest = $Connection->db->prepare($query_dest);
688
		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...
689
  
690
		$i = 0;
691
		while($row = sparql_fetch_array($result))
692
		{
693
			if ($i >= 1) {
694
			//print_r($row);
695
			if (!isset($row['iata'])) $row['iata'] = '';
696
			if (!isset($row['icao'])) $row['icao'] = '';
697
			if (!isset($row['type'])) $row['type'] = '';
698
			if (!isset($row['altitude'])) $row['altitude'] = '';
699
			if (isset($row['city_bis'])) {
700
				$row['city'] = $row['city_bis'];
701
			}
702
			if (!isset($row['city'])) $row['city'] = '';
703
			if (!isset($row['country'])) $row['country'] = '';
704
			if (!isset($row['homepage'])) $row['homepage'] = '';
705
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
706
			if (!isset($row['name'])) continue;
707
			if (!isset($row['image'])) {
708
				$row['image'] = '';
709
				$row['image_thumb'] = '';
710
			} else {
711
				$image = str_replace(' ','_',$row['image']);
712
				$digest = md5($image);
713
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
714
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
715
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
716
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
717
			}
718
			
719
			$country = explode('-',$row['country']);
720
			$row['country'] = $country[0];
721
			
722
			$row['type'] = trim($row['type']);
723
			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'])) {
724
				$row['type'] = 'Military';
725
			} 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') {
726
				$row['type'] = 'small_airport';
727
			}
728
			
729
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
730
			$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']);
731
			//print_r($query_dest_values);
732
			
733
			try {
734
				$sth_dest->execute($query_dest_values);
735
			} catch(PDOException $e) {
736
				return "error : ".$e->getMessage();
737
			}
738
			}
739
740
			$i++;
741
		}
742
		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...
743
		echo "Delete duplicate rows...\n";
744
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
745
		try {
746
			$Connection = new Connection();
747
			$sth = $Connection->db->prepare($query);
748
                        $sth->execute();
749
                } catch(PDOException $e) {
750
                        return "error : ".$e->getMessage();
751
                }
752
753
754
		if ($globalDebug) echo "Insert Not available Airport...\n";
755
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
756
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
757
		$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' => '');
758
		try {
759
			$Connection = new Connection();
760
			$sth = $Connection->db->prepare($query);
761
                        $sth->execute($query_values);
762
                } catch(PDOException $e) {
763
                        return "error : ".$e->getMessage();
764
                }
765
		$i++;
766
/*
767
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
768
		try {
769
			$Connection = new Connection();
770
			$sth = $Connection->db->prepare($query);
771
                        $sth->execute();
772
                } catch(PDOException $e) {
773
                        return "error : ".$e->getMessage();
774
                }
775
*/
776
777
		echo "Download data from ourairports.com...\n";
778
		$delimiter = ',';
779
		$out_file = $tmp_dir.'airports.csv';
780
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
781
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
782
		echo "Add data from ourairports.com...\n";
783
784
		$header = NULL;
785
		if (($handle = fopen($out_file, 'r')) !== FALSE)
786
		{
787
			$Connection = new Connection();
788
			//$Connection->db->beginTransaction();
789
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
790
			{
791
				if(!$header) $header = $row;
792
				else {
793
					$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...
794
					$data = array_combine($header, $row);
795
					try {
796
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
797
						$sth->execute(array(':icao' => $data['gps_code']));
798
					} catch(PDOException $e) {
799
						return "error : ".$e->getMessage();
800
					}
801
					if ($sth->fetchColumn() > 0) {
802
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
803
						try {
804
							$sth = $Connection->db->prepare($query);
805
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
806
						} catch(PDOException $e) {
807
							return "error : ".$e->getMessage();
808
						}
809
					} else {
810
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
811
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
812
						$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']);
813
						try {
814
							$sth = $Connection->db->prepare($query);
815
							$sth->execute($query_values);
816
						} catch(PDOException $e) {
817
							return "error : ".$e->getMessage();
818
						}
819
						$i++;
820
					}
821
				}
822
			}
823
			fclose($handle);
824
			//$Connection->db->commit();
825
		}
826
827
		echo "Download data from another free database...\n";
828
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
829
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
830
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
831
		update_db::unzip($out_file);
832
		$header = NULL;
833
		echo "Add data from another free database...\n";
834
		$delimiter = ':';
835
		$Connection = new Connection();
836
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
837
		{
838
			//$Connection->db->beginTransaction();
839
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
840
			{
841
				if(!$header) $header = $row;
842
				else {
843
					$data = $row;
844
845
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
846
					try {
847
						$sth = $Connection->db->prepare($query);
848
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
849
					} catch(PDOException $e) {
850
						return "error : ".$e->getMessage();
851
					}
852
				}
853
			}
854
			fclose($handle);
855
			//$Connection->db->commit();
856
		}
857
858
		echo "Put type military for all air base";
859
		$Connection = new Connection();
860
		try {
861
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
862
			$sth->execute();
863
		} catch(PDOException $e) {
864
			return "error : ".$e->getMessage();
865
		}
866
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
867
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
868
			try {
869
				$sth2 = $Connection->db->prepare($query2);
870
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
871
			} catch(PDOException $e) {
872
				return "error : ".$e->getMessage();
873
			}
874
		}
875
876
877
878
                return "success";
879
	}
880
	
881
	public static function translation() {
882
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
883
		global $tmp_dir, $globalTransaction;
884
		$Spotter = new Spotter();
885
		//$out_file = $tmp_dir.'translation.zip';
886
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
887
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
888
		
889
		//$query = 'TRUNCATE TABLE translation';
890
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
891
		try {
892
			$Connection = new Connection();
893
			$sth = $Connection->db->prepare($query);
894
                        $sth->execute(array(':source' => 'translation.csv'));
895
                } catch(PDOException $e) {
896
                        return "error : ".$e->getMessage();
897
                }
898
899
		
900
		//update_db::unzip($out_file);
901
		$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...
902
		$delimiter = ';';
903
		$Connection = new Connection();
904
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
905
		{
906
			$i = 0;
907
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
908
			//$Connection->db->beginTransaction();
909
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
910
			{
911
				$i++;
912
				if($i > 12) {
913
					$data = $row;
914
					$operator = $data[2];
915
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
916
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
917
                                                //echo substr($operator, 0, 2)."\n";;
918
                                                if (count($airline_array) > 0) {
919
							//print_r($airline_array);
920
							$operator = $airline_array[0]['icao'].substr($operator,2);
921
                                                }
922
                                        }
923
					
924
					$operator_correct = $data[3];
925
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
926
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
927
                                                if (count($airline_array) > 0) {
928
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
929
                                            	}
930
                                        }
931
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
932
					try {
933
						$sth = $Connection->db->prepare($query);
934
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
935
					} catch(PDOException $e) {
936
						return "error : ".$e->getMessage();
937
					}
938
				}
939
			}
940
			fclose($handle);
941
			//$Connection->db->commit();
942
		}
943
		return '';
944
        }
945
	
946
	public static function translation_fam() {
947
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
948
		global $tmp_dir, $globalTransaction;
949
		$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...
950
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
951
		try {
952
			$Connection = new Connection();
953
			$sth = $Connection->db->prepare($query);
954
                        $sth->execute(array(':source' => 'website_fam'));
955
                } catch(PDOException $e) {
956
                        return "error : ".$e->getMessage();
957
                }
958
959
		
960
		//update_db::unzip($out_file);
961
		$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...
962
		$delimiter = "\t";
963
		$Connection = new Connection();
964
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
965
		{
966
			$i = 0;
967
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
968
			//$Connection->db->beginTransaction();
969
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
970
			{
971
				if ($i > 0) {
972
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
973
					try {
974
						$sth = $Connection->db->prepare($query);
975
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
976
					} catch(PDOException $e) {
977
						return "error : ".$e->getMessage();
978
					}
979
				}
980
				$i++;
981
			}
982
			fclose($handle);
983
			//$Connection->db->commit();
984
		}
985
		return '';
986
        }
987
988
	/*
989
	* This function use FAA public data.
990
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
991
	*/
992
	public static function modes_faa() {
993
		global $tmp_dir, $globalTransaction, $globalDebug;
994
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
995
		try {
996
			$Connection = new Connection();
997
			$sth = $Connection->db->prepare($query);
998
                        $sth->execute(array(':source' => 'website_faa'));
999
                } catch(PDOException $e) {
1000
                        return "error : ".$e->getMessage();
1001
                }
1002
1003
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1004
		try {
1005
			$Connection = new Connection();
1006
			$sth = $Connection->db->prepare($query);
1007
                        $sth->execute(array(':source' => 'website_faa'));
1008
                } catch(PDOException $e) {
1009
                        return "error : ".$e->getMessage();
1010
                }
1011
1012
		$delimiter = ",";
1013
		$mfr = array();
1014
		$Connection = new Connection();
1015
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
1016
		{
1017
			$i = 0;
1018
			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...
1019
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1020
			{
1021
				if ($i > 0) {
1022
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
1023
					try {
1024
						$sths = $Connection->db->prepare($query_search);
1025
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
1026
					} catch(PDOException $e) {
1027
						return "error s : ".$e->getMessage();
1028
					}
1029
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
1030
					if (!empty($result_search)) {
1031
						if ($globalDebug) echo '.';
1032
							//if ($globalDBdriver == 'mysql') {
1033
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
1034
							//} else {
1035
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
1036
							//}
1037
						try {
1038
							$sthi = $Connection->db->prepare($queryi);
1039
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1040
						} catch(PDOException $e) {
1041
							return "error u : ".$e->getMessage();
1042
						}
1043
					} else {
1044
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1045
						try {
1046
							$sthsm = $Connection->db->prepare($query_search_mfr);
1047
							$sthsm->execute(array(':mfr' => $data[2]));
1048
						} catch(PDOException $e) {
1049
							return "error mfr : ".$e->getMessage();
1050
						}
1051
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1052
						if (!empty($result_search_mfr)) {
1053
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1054
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1055
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1056
							try {
1057
								$sthf = $Connection->db->prepare($queryf);
1058
								$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'));
1059
							} catch(PDOException $e) {
1060
								return "error f : ".$e->getMessage();
1061
							}
1062
						}
1063
					}
1064
					if (strtotime($data[29]) > time()) {
1065
						if ($globalDebug) echo 'i';
1066
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1067
						try {
1068
							$sth = $Connection->db->prepare($query);
1069
							$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'));
1070
						} catch(PDOException $e) {
1071
							return "error i : ".$e->getMessage();
1072
						}
1073
					}
1074
				}
1075
				if ($i % 90 == 0) {
1076
					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...
1077
					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...
1078
				}
1079
				$i++;
1080
			}
1081
			fclose($handle);
1082
			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...
1083
		}
1084
		print_r($mfr);
1085
		return '';
1086
        }
1087
	public static function modes_fam() {
1088
		global $tmp_dir, $globalTransaction;
1089
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1090
		try {
1091
			$Connection = new Connection();
1092
			$sth = $Connection->db->prepare($query);
1093
                        $sth->execute(array(':source' => 'website_fam'));
1094
                } catch(PDOException $e) {
1095
                        return "error : ".$e->getMessage();
1096
                }
1097
1098
		
1099
		//update_db::unzip($out_file);
1100
		$delimiter = "\t";
1101
		$Connection = new Connection();
1102
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1103
		{
1104
			$i = 0;
1105
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1106
			//$Connection->db->beginTransaction();
1107
			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...
1108
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1109
			{
1110
				if ($i > 0) {
1111
					if ($data[1] == 'NULL') $data[1] = $data[0];
1112
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1113
					try {
1114
						$sth = $Connection->db->prepare($query);
1115
						$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'));
1116
					} catch(PDOException $e) {
1117
						return "error : ".$e->getMessage();
1118
					}
1119
				}
1120
				$i++;
1121
			}
1122
			fclose($handle);
1123
			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...
1124
		}
1125
		return '';
1126
        }
1127
        
1128
	public static function owner_fam() {
1129
		global $tmp_dir, $globalTransaction;
1130
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1131
		try {
1132
			$Connection = new Connection();
1133
			$sth = $Connection->db->prepare($query);
1134
                        $sth->execute(array(':source' => 'website_fam'));
1135
                } catch(PDOException $e) {
1136
                        return "error : ".$e->getMessage();
1137
                }
1138
1139
		$delimiter = "\t";
1140
		$Connection = new Connection();
1141
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1142
		{
1143
			$i = 0;
1144
			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...
1145
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1146
			{
1147
				if ($i > 0) {
1148
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1149
					try {
1150
						$sth = $Connection->db->prepare($query);
1151
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1152
					} catch(PDOException $e) {
1153
						print_r($data);
1154
						return "error : ".$e->getMessage();
1155
					}
1156
				}
1157
				$i++;
1158
			}
1159
			fclose($handle);
1160
			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...
1161
		}
1162
		return '';
1163
        }
1164
1165
	public static function routes_fam() {
1166
		global $tmp_dir, $globalTransaction;
1167
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1168
		try {
1169
			$Connection = new Connection();
1170
			$sth = $Connection->db->prepare($query);
1171
                        $sth->execute(array(':source' => 'website_fam'));
1172
                } catch(PDOException $e) {
1173
                        return "error : ".$e->getMessage();
1174
                }
1175
1176
		
1177
		//update_db::unzip($out_file);
1178
		$delimiter = "\t";
1179
		$Connection = new Connection();
1180
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1181
		{
1182
			$i = 0;
1183
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1184
			//$Connection->db->beginTransaction();
1185
			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...
1186
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1187
			{
1188
				if ($i > 0) {
1189
					$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)';
1190
					try {
1191
						$sth = $Connection->db->prepare($query);
1192
						$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'));
1193
					} catch(PDOException $e) {
1194
						return "error : ".$e->getMessage();
1195
					}
1196
				}
1197
				$i++;
1198
			}
1199
			fclose($handle);
1200
			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...
1201
		}
1202
		return '';
1203
        }
1204
1205
	public static function marine_identity_fam() {
1206
		global $tmp_dir, $globalTransaction;
1207
		$query = "TRUNCATE TABLE marine_identity";
1208
		try {
1209
			$Connection = new Connection();
1210
			$sth = $Connection->db->prepare($query);
1211
                        $sth->execute();
1212
                } catch(PDOException $e) {
1213
                        return "error : ".$e->getMessage();
1214
                }
1215
1216
		
1217
		//update_db::unzip($out_file);
1218
		$delimiter = "\t";
1219
		$Connection = new Connection();
1220
		if (($handle = fopen($tmp_dir.'marine_identity.tsv', 'r')) !== FALSE)
1221
		{
1222
			$i = 0;
1223
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1224
			//$Connection->db->beginTransaction();
1225
			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...
1226
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1227
			{
1228
				if ($i > 0) {
1229
					$data = array_map(function($v) { return $v === 'NULL' ? NULL : $v; },$data);
1230
					$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)';
1231
					try {
1232
						$sth = $Connection->db->prepare($query);
1233
						$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]));
1234
					} catch(PDOException $e) {
1235
						return "error : ".$e->getMessage();
1236
					}
1237
				}
1238
				$i++;
1239
			}
1240
			fclose($handle);
1241
			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...
1242
		}
1243
		return '';
1244
        }
1245
1246
	public static function banned_fam() {
1247
		global $tmp_dir, $globalTransaction;
1248
		$query = "UPDATE airlines SET ban_eu = 0";
1249
		try {
1250
			$Connection = new Connection();
1251
			$sth = $Connection->db->prepare($query);
1252
			$sth->execute();
1253
		} catch(PDOException $e) {
1254
			return "error : ".$e->getMessage();
1255
		}
1256
1257
		$Connection = new Connection();
1258
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1259
		{
1260
			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...
1261
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1262
			{
1263
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1264
				if ($data[0] != '') {
1265
					$icao = $data[0];
1266
					try {
1267
						$sth = $Connection->db->prepare($query);
1268
						$sth->execute(array(':icao' => $icao));
1269
					} catch(PDOException $e) {
1270
						return "error : ".$e->getMessage();
1271
					}
1272
				}
1273
			}
1274
			fclose($handle);
1275
			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...
1276
		}
1277
		return '';
1278
        }
1279
1280
	public static function tle($filename,$tletype) {
1281
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1282
		global $tmp_dir, $globalTransaction;
1283
		//$Spotter = new Spotter();
1284
		
1285
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1286
		try {
1287
			$Connection = new Connection();
1288
			$sth = $Connection->db->prepare($query);
1289
                        $sth->execute(array(':source' => $filename));
1290
                } catch(PDOException $e) {
1291
                        return "error : ".$e->getMessage();
1292
                }
1293
		
1294
		$Connection = new Connection();
1295
		if (($handle = fopen($filename, 'r')) !== FALSE)
1296
		{
1297
			$i = 0;
1298
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1299
			//$Connection->db->beginTransaction();
1300
			$dbdata = array();
1301
			while (($data = fgets($handle, 1000)) !== FALSE)
1302
			{
1303
				if ($i == 0) {
1304
					$dbdata['name'] = trim($data);
1305
					$i++;
1306
				} elseif ($i == 1) {
1307
					$dbdata['tle1'] = trim($data);
1308
					$i++;
1309
				} elseif ($i == 2) {
1310
					$dbdata['tle2'] = trim($data);
1311
					//print_r($dbdata);
1312
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1313
					try {
1314
						$sth = $Connection->db->prepare($query);
1315
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1316
					} catch(PDOException $e) {
1317
						return "error : ".$e->getMessage();
1318
					}
1319
1320
					$i = 0;
1321
				}
1322
			}
1323
			fclose($handle);
1324
			//$Connection->db->commit();
1325
		}
1326
		return '';
1327
        }
1328
1329
	/**
1330
        * Convert a HTML table to an array
1331
        * @param String $data HTML page
1332
        * @return Array array of the tables in HTML page
1333
        */
1334
        private static function table2array($data) {
1335
                $html = str_get_html($data);
1336
                $tabledata=array();
1337
                foreach($html->find('tr') as $element)
1338
                {
1339
                        $td = array();
1340
                        foreach( $element->find('th') as $row)
1341
                        {
1342
                                $td [] = trim($row->plaintext);
1343
                        }
1344
                        $td=array_filter($td);
1345
                        $tabledata[] = $td;
1346
1347
                        $td = array();
1348
                        $tdi = array();
1349
                        foreach( $element->find('td') as $row)
1350
                        {
1351
                                $td [] = trim($row->plaintext);
1352
                                $tdi [] = trim($row->innertext);
1353
                        }
1354
                        $td=array_filter($td);
1355
                        $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...
1356
                    //    $tabledata[]=array_merge($td,$tdi);
1357
                        $tabledata[]=$td;
1358
                }
1359
                return(array_filter($tabledata));
1360
        }
1361
1362
       /**
1363
        * Get data from form result
1364
        * @param String $url form URL
1365
        * @return String the result
1366
        */
1367
        private static function getData($url) {
1368
                $ch = curl_init();
1369
                curl_setopt($ch, CURLOPT_URL, $url);
1370
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1371
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1372
                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');
1373
                return curl_exec($ch);
1374
        }
1375
/*
1376
	public static function waypoints() {
1377
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1378
		$table = update_db::table2array($data);
1379
//		print_r($table);
1380
		$query = 'TRUNCATE TABLE waypoints';
1381
		try {
1382
			$Connection = new Connection();
1383
			$sth = $Connection->db->prepare($query);
1384
                        $sth->execute();
1385
                } catch(PDOException $e) {
1386
                        return "error : ".$e->getMessage();
1387
                }
1388
1389
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1390
		$Connection = new Connection();
1391
		$sth_dest = $Connection->db->prepare($query_dest);
1392
		$Connection->db->beginTransaction();
1393
                foreach ($table as $row) {
1394
            		if ($row[0] != 'Ident') {
1395
				$ident = $row[0];
1396
				$latitude = $row[2];
1397
				$longitude = $row[3];
1398
				$control = $row[4];
1399
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1400
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1401
				try {
1402
					$sth_dest->execute($query_dest_values);
1403
				} catch(PDOException $e) {
1404
					return "error : ".$e->getMessage();
1405
				}
1406
			}
1407
                }
1408
		$Connection->db->commit();
1409
1410
	}
1411
*/
1412
	public static function waypoints($filename) {
1413
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1414
		global $tmp_dir, $globalTransaction;
1415
		//$Spotter = new Spotter();
1416
		//$out_file = $tmp_dir.'translation.zip';
1417
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1418
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1419
		$Connection = new Connection();
1420
		//update_db::unzip($out_file);
1421
		$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...
1422
		$delimiter = ' ';
1423
		if (($handle = fopen($filename, 'r')) !== FALSE)
1424
		{
1425
			$i = 0;
1426
			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...
1427
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1428
			{
1429
				$i++;
1430
				if($i > 3 && count($row) > 2) {
1431
					$data = array_values(array_filter($row));
1432
					$cntdata = count($data);
1433
					if ($cntdata > 10) {
1434
						$value = $data[9];
1435
						
1436
						for ($i =10;$i < $cntdata;$i++) {
1437
							$value .= ' '.$data[$i];
1438
						}
1439
						$data[9] = $value;
1440
					}
1441
					//print_r($data);
1442
					if (count($data) > 9) {
1443
						$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)';
1444
						try {
1445
							$sth = $Connection->db->prepare($query);
1446
							$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]));
1447
						} catch(PDOException $e) {
1448
							return "error : ".$e->getMessage();
1449
						}
1450
					}
1451
				}
1452
			}
1453
			fclose($handle);
1454
			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...
1455
		}
1456
		return '';
1457
        }
1458
1459
	public static function ivao_airlines($filename) {
1460
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1461
		global $tmp_dir, $globalTransaction;
1462
		//$query = 'TRUNCATE TABLE airlines';
1463
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1464
		try {
1465
			$Connection = new Connection();
1466
			$sth = $Connection->db->prepare($query);
1467
                        $sth->execute();
1468
                } catch(PDOException $e) {
1469
                        return "error : ".$e->getMessage();
1470
                }
1471
1472
		$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...
1473
		$delimiter = ':';
1474
		$Connection = new Connection();
1475
		if (($handle = fopen($filename, 'r')) !== FALSE)
1476
		{
1477
			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...
1478
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1479
			{
1480
				if(count($row) > 1) {
1481
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1482
					try {
1483
						$sth = $Connection->db->prepare($query);
1484
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1485
					} catch(PDOException $e) {
1486
						return "error : ".$e->getMessage();
1487
					}
1488
				}
1489
			}
1490
			fclose($handle);
1491
			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...
1492
		}
1493
		return '';
1494
        }
1495
	
1496
	public static function update_airspace() {
1497
		global $tmp_dir, $globalDBdriver;
1498
		include_once('class.create_db.php');
1499
		$Connection = new Connection();
1500
		if ($Connection->tableExists('airspace')) {
1501
			$query = 'DROP TABLE airspace';
1502
			try {
1503
				$sth = $Connection->db->prepare($query);
1504
                    		$sth->execute();
1505
	                } catch(PDOException $e) {
1506
				return "error : ".$e->getMessage();
1507
	                }
1508
	        }
1509
1510
1511
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1512
		else {
1513
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1514
			$query = "CREATE EXTENSION postgis";
1515
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1516
			try {
1517
				$sth = $Connection->db->prepare($query);
1518
				$sth->execute();
1519
			} catch(PDOException $e) {
1520
				return "error : ".$e->getMessage();
1521
			}
1522
		}
1523
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1524
		return $error;
1525
	}
1526
1527
	public static function update_notam_fam() {
1528
		global $tmp_dir, $globalDebug;
1529
		include_once('class.create_db.php');
1530
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1531
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1532
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1533
		$error = '';
1534
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1535
			if ($globalDebug) echo "Gunzip...";
1536
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1537
			if ($globalDebug) echo "Add to DB...";
1538
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1539
			$NOTAM = new NOTAM();
1540
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1541
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1542
		if ($error != '') {
1543
			return $error;
1544
		} elseif ($globalDebug) echo "Done\n";
1545
		return '';
1546
	}
1547
1548
	public static function update_vatsim() {
1549
		global $tmp_dir;
1550
		include_once('class.create_db.php');
1551
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1552
		return $error;
1553
	}
1554
	
1555
	public static function update_countries() {
1556
		global $tmp_dir, $globalDBdriver;
1557
		include_once('class.create_db.php');
1558
		$Connection = new Connection();
1559
		if ($Connection->tableExists('countries')) {
1560
			$query = 'DROP TABLE countries';
1561
			try {
1562
				$sth = $Connection->db->prepare($query);
1563
            	        	$sth->execute();
1564
	                } catch(PDOException $e) {
1565
    	                	echo "error : ".$e->getMessage();
1566
	                }
1567
		}
1568
		if ($globalDBdriver == 'mysql') {
1569
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1570
		} else {
1571
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1572
		}
1573
		$error = create_db::import_file($tmp_dir.'countries.sql');
1574
		return $error;
1575
	}
1576
1577
	
1578
	public static function update_waypoints() {
1579
		global $tmp_dir;
1580
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1581
//		update_db::unzip($tmp_dir.'AptNav.zip');
1582
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1583
//		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');
1584
		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');
1585
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1586
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1587
		return $error;
1588
	}
1589
1590
	public static function update_ivao() {
1591
		global $tmp_dir, $globalDebug;
1592
		$Common = new Common();
1593
		$error = '';
1594
		//Direct download forbidden
1595
		//if ($globalDebug) echo "IVAO : Download...";
1596
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1597
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1598
			if ($globalDebug) echo "Unzip...";
1599
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1600
			if ($globalDebug) echo "Add to DB...";
1601
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1602
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1603
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1604
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1605
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1606
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1607
		if ($error != '') {
1608
			return $error;
1609
		} elseif ($globalDebug) echo "Done\n";
1610
		return '';
1611
	}
1612
1613
	public static function update_routes() {
1614
		global $tmp_dir, $globalDebug;
1615
		$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...
1616
		if ($globalDebug) echo "Routes : Download...";
1617
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1618
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1619
			if ($globalDebug) echo "Gunzip...";
1620
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1621
			if ($globalDebug) echo "Add to DB...";
1622
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1623
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1624
		if ($error != '') {
1625
			return $error;
1626
		} elseif ($globalDebug) echo "Done\n";
1627
		return '';
1628
	}
1629
	public static function update_oneworld() {
1630
		global $tmp_dir, $globalDebug;
1631
		$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...
1632
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1633
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1634
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1635
			if ($globalDebug) echo "Gunzip...";
1636
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1637
			if ($globalDebug) echo "Add to DB...";
1638
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1639
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1640
		if ($error != '') {
1641
			return $error;
1642
		} elseif ($globalDebug) echo "Done\n";
1643
		return '';
1644
	}
1645
	public static function update_skyteam() {
1646
		global $tmp_dir, $globalDebug;
1647
		$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...
1648
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1649
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1650
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1651
			if ($globalDebug) echo "Gunzip...";
1652
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1653
			if ($globalDebug) echo "Add to DB...";
1654
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1655
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1656
		if ($error != '') {
1657
			return $error;
1658
		} elseif ($globalDebug) echo "Done\n";
1659
		return '';
1660
	}
1661
	public static function update_ModeS() {
1662
		global $tmp_dir, $globalDebug;
1663
/*
1664
		if ($globalDebug) echo "Modes : Download...";
1665
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1666
		if ($globalDebug) echo "Unzip...";
1667
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1668
		if ($globalDebug) echo "Add to DB...";
1669
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1670
		if ($error != true) {
1671
			echo $error;
1672
			exit;
1673
		} elseif ($globalDebug) echo "Done\n";
1674
*/
1675
		if ($globalDebug) echo "Modes : Download...";
1676
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1677
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1678
1679
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1680
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1681
			if ($globalDebug) echo "Unzip...";
1682
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1683
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1684
			if ($globalDebug) echo "Add to DB...";
1685
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1686
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1687
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1688
		if ($error != '') {
1689
			return $error;
1690
		} elseif ($globalDebug) echo "Done\n";
1691
		return '';
1692
	}
1693
1694
	public static function update_ModeS_faa() {
1695
		global $tmp_dir, $globalDebug;
1696
		if ($globalDebug) echo "Modes FAA: Download...";
1697
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
1698
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
1699
			if ($globalDebug) echo "Unzip...";
1700
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
1701
			if ($globalDebug) echo "Add to DB...";
1702
			$error = update_db::modes_faa();
1703
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
1704
		if ($error != '') {
1705
			return $error;
1706
		} elseif ($globalDebug) echo "Done\n";
1707
		return '';
1708
	}
1709
1710
	public static function update_ModeS_flarm() {
1711
		global $tmp_dir, $globalDebug;
1712
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1713
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1714
		if (file_exists($tmp_dir.'data.fln')) {
1715
			if ($globalDebug) echo "Add to DB...";
1716
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1717
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1718
		if ($error != '') {
1719
			return $error;
1720
		} elseif ($globalDebug) echo "Done\n";
1721
		return '';
1722
	}
1723
1724
	public static function update_ModeS_ogn() {
1725
		global $tmp_dir, $globalDebug;
1726
		if ($globalDebug) echo "Modes OGN: Download...";
1727
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1728
		if (file_exists($tmp_dir.'ogn.csv')) {
1729
			if ($globalDebug) echo "Add to DB...";
1730
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1731
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1732
		if ($error != '') {
1733
			return $error;
1734
		} elseif ($globalDebug) echo "Done\n";
1735
		return '';
1736
	}
1737
1738
	public static function update_owner() {
1739
		global $tmp_dir, $globalDebug, $globalMasterSource;
1740
		
1741
		if ($globalDebug) echo "Owner France: Download...";
1742
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1743
		if (file_exists($tmp_dir.'owner_f.csv')) {
1744
			if ($globalDebug) echo "Add to DB...";
1745
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1746
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1747
		if ($error != '') {
1748
			return $error;
1749
		} elseif ($globalDebug) echo "Done\n";
1750
		
1751
		if ($globalDebug) echo "Owner Ireland: Download...";
1752
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1753
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1754
			if ($globalDebug) echo "Add to DB...";
1755
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1756
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1757
		if ($error != '') {
1758
			return $error;
1759
		} elseif ($globalDebug) echo "Done\n";
1760
		if ($globalDebug) echo "Owner Switzerland: Download...";
1761
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1762
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1763
			if ($globalDebug) echo "Add to DB...";
1764
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1765
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1766
		if ($error != '') {
1767
			return $error;
1768
		} elseif ($globalDebug) echo "Done\n";
1769
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1770
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1771
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1772
			if ($globalDebug) echo "Add to DB...";
1773
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1774
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1775
		if ($error != '') {
1776
			return $error;
1777
		} elseif ($globalDebug) echo "Done\n";
1778
		if ($globalDebug) echo "Owner Australia: Download...";
1779
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1780
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1781
			if ($globalDebug) echo "Add to DB...";
1782
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1783
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1784
		if ($error != '') {
1785
			return $error;
1786
		} elseif ($globalDebug) echo "Done\n";
1787
		if ($globalDebug) echo "Owner Austria: Download...";
1788
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1789
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1790
			if ($globalDebug) echo "Add to DB...";
1791
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1792
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1793
		if ($error != '') {
1794
			return $error;
1795
		} elseif ($globalDebug) echo "Done\n";
1796
		if ($globalDebug) echo "Owner Chile: Download...";
1797
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1798
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1799
			if ($globalDebug) echo "Add to DB...";
1800
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1801
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1802
		if ($error != '') {
1803
			return $error;
1804
		} elseif ($globalDebug) echo "Done\n";
1805
		if ($globalDebug) echo "Owner Colombia: Download...";
1806
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1807
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1808
			if ($globalDebug) echo "Add to DB...";
1809
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1810
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1811
		if ($error != '') {
1812
			return $error;
1813
		} elseif ($globalDebug) echo "Done\n";
1814
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1815
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1816
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1817
			if ($globalDebug) echo "Add to DB...";
1818
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1819
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1820
		if ($error != '') {
1821
			return $error;
1822
		} elseif ($globalDebug) echo "Done\n";
1823
		if ($globalDebug) echo "Owner Brazil: Download...";
1824
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1825
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1826
			if ($globalDebug) echo "Add to DB...";
1827
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1828
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1829
		if ($error != '') {
1830
			return $error;
1831
		} elseif ($globalDebug) echo "Done\n";
1832
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1833
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1834
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1835
			if ($globalDebug) echo "Add to DB...";
1836
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1837
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1838
		if ($error != '') {
1839
			return $error;
1840
		} elseif ($globalDebug) echo "Done\n";
1841
		if ($globalDebug) echo "Owner Croatia: Download...";
1842
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1843
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1844
			if ($globalDebug) echo "Add to DB...";
1845
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1846
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1847
		if ($error != '') {
1848
			return $error;
1849
		} elseif ($globalDebug) echo "Done\n";
1850
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1851
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1852
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1853
			if ($globalDebug) echo "Add to DB...";
1854
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1855
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1856
		if ($error != '') {
1857
			return $error;
1858
		} elseif ($globalDebug) echo "Done\n";
1859
		if ($globalDebug) echo "Owner Maldives: Download...";
1860
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1861
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1862
			if ($globalDebug) echo "Add to DB...";
1863
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1864
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1865
		if ($error != '') {
1866
			return $error;
1867
		} elseif ($globalDebug) echo "Done\n";
1868
		if ($globalDebug) echo "Owner New Zealand: Download...";
1869
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1870
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1871
			if ($globalDebug) echo "Add to DB...";
1872
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1873
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1874
		if ($error != '') {
1875
			return $error;
1876
		} elseif ($globalDebug) echo "Done\n";
1877
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1878
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1879
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1880
			if ($globalDebug) echo "Add to DB...";
1881
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1882
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1883
		if ($error != '') {
1884
			return $error;
1885
		} elseif ($globalDebug) echo "Done\n";
1886
		if ($globalDebug) echo "Owner Slovakia: Download...";
1887
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1888
		if (file_exists($tmp_dir.'owner_om.csv')) {
1889
			if ($globalDebug) echo "Add to DB...";
1890
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1891
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1892
		if ($error != '') {
1893
			return $error;
1894
		} elseif ($globalDebug) echo "Done\n";
1895
		if ($globalDebug) echo "Owner Ecuador: Download...";
1896
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1897
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1898
			if ($globalDebug) echo "Add to DB...";
1899
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1900
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1901
		if ($error != '') {
1902
			return $error;
1903
		} elseif ($globalDebug) echo "Done\n";
1904
		if ($globalDebug) echo "Owner Iceland: Download...";
1905
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1906
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1907
			if ($globalDebug) echo "Add to DB...";
1908
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1909
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1910
		if ($error != '') {
1911
			return $error;
1912
		} elseif ($globalDebug) echo "Done\n";
1913
		if ($globalDebug) echo "Owner Isle of Man: Download...";
1914
		update_db::download('http://antonakis.co.uk/registers/IsleOfMan.txt',$tmp_dir.'owner_m.csv');
1915
		if (file_exists($tmp_dir.'owner_m.csv')) {
1916
			if ($globalDebug) echo "Add to DB...";
1917
			$error = update_db::retrieve_owner($tmp_dir.'owner_m.csv','M');
1918
		} else $error = "File ".$tmp_dir.'owner_m.csv'." doesn't exist. Download failed.";
1919
		if ($error != '') {
1920
			return $error;
1921
		} elseif ($globalDebug) echo "Done\n";
1922
		if ($globalMasterSource) {
1923
			if ($globalDebug) echo "ModeS Netherlands: Download...";
1924
			update_db::download('http://antonakis.co.uk/registers/Netherlands.txt',$tmp_dir.'owner_ph.csv');
1925
			if (file_exists($tmp_dir.'owner_ph.csv')) {
1926
				if ($globalDebug) echo "Add to DB...";
1927
				$error = update_db::retrieve_owner($tmp_dir.'owner_ph.csv','PH');
1928
			} else $error = "File ".$tmp_dir.'owner_ph.csv'." doesn't exist. Download failed.";
1929
			if ($error != '') {
1930
				return $error;
1931
			} elseif ($globalDebug) echo "Done\n";
1932
			if ($globalDebug) echo "ModeS Denmark: Download...";
1933
			update_db::download('http://antonakis.co.uk/registers/Denmark.txt',$tmp_dir.'owner_oy.csv');
1934
			if (file_exists($tmp_dir.'owner_oy.csv')) {
1935
				if ($globalDebug) echo "Add to DB...";
1936
				$error = update_db::retrieve_owner($tmp_dir.'owner_oy.csv','OY');
1937
			} else $error = "File ".$tmp_dir.'owner_oy.csv'." doesn't exist. Download failed.";
1938
			if ($error != '') {
1939
				return $error;
1940
			} elseif ($globalDebug) echo "Done\n";
1941
		} elseif ($globalDebug) echo "Done\n";
1942
		return '';
1943
	}
1944
1945
	public static function update_translation() {
1946
		global $tmp_dir, $globalDebug;
1947
		$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...
1948
		if ($globalDebug) echo "Translation : Download...";
1949
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1950
		if (file_exists($tmp_dir.'translation.zip')) {
1951
			if ($globalDebug) echo "Unzip...";
1952
			update_db::unzip($tmp_dir.'translation.zip');
1953
			if ($globalDebug) echo "Add to DB...";
1954
			$error = update_db::translation();
1955
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1956
		if ($error != '') {
1957
			return $error;
1958
		} elseif ($globalDebug) echo "Done\n";
1959
		return '';
1960
	}
1961
1962
	public static function update_translation_fam() {
1963
		global $tmp_dir, $globalDebug;
1964
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1965
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1966
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1967
			if ($globalDebug) echo "Gunzip...";
1968
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1969
			if ($globalDebug) echo "Add to DB...";
1970
			$error = update_db::translation_fam();
1971
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1972
		if ($error != '') {
1973
			return $error;
1974
		} elseif ($globalDebug) echo "Done\n";
1975
		return '';
1976
	}
1977
	public static function update_ModeS_fam() {
1978
		global $tmp_dir, $globalDebug;
1979
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1980
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1981
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1982
			if ($globalDebug) echo "Gunzip...";
1983
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1984
			if ($globalDebug) echo "Add to DB...";
1985
			$error = update_db::modes_fam();
1986
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1987
		if ($error != '') {
1988
			return $error;
1989
		} elseif ($globalDebug) echo "Done\n";
1990
		return '';
1991
	}
1992
	public static function update_owner_fam() {
1993
		global $tmp_dir, $globalDebug, $globalOwner;
1994
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
1995
		if ($globalOwner === TRUE) {
1996
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
1997
		} else {
1998
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
1999
		}
2000
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
2001
			if ($globalDebug) echo "Gunzip...";
2002
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
2003
			if ($globalDebug) echo "Add to DB...";
2004
			$error = update_db::owner_fam();
2005
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
2006
		if ($error != '') {
2007
			return $error;
2008
		} elseif ($globalDebug) echo "Done\n";
2009
		return '';
2010
	}
2011
	public static function update_routes_fam() {
2012
		global $tmp_dir, $globalDebug;
2013
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
2014
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
2015
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
2016
			if ($globalDebug) echo "Gunzip...";
2017
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
2018
			if ($globalDebug) echo "Add to DB...";
2019
			$error = update_db::routes_fam();
2020
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
2021
		if ($error != '') {
2022
			return $error;
2023
		} elseif ($globalDebug) echo "Done\n";
2024
		return '';
2025
	}
2026
	public static function update_marine_identity_fam() {
2027
		global $tmp_dir, $globalDebug;
2028
		update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz.md5',$tmp_dir.'marine_identity.tsv.gz.md5');
2029
		if (file_exists($tmp_dir.'marine_identity.tsv.gz.md5')) {
2030
			$marine_identity_md5_file = explode(' ',file_get_contents($tmp_dir.'marine_identity.tsv.gz.md5'));
2031
			$marine_identity_md5 = $marine_identity_md5_file[0];
2032
			if (!update_db::check_marine_identity_version($marine_identity_md5)) {
2033
				if ($globalDebug) echo "Marine identity from FlightAirMap website : Download...";
2034
				update_db::download('http://data.flightairmap.fr/data/marine_identity.tsv.gz',$tmp_dir.'marine_identity.tsv.gz');
2035
				if (file_exists($tmp_dir.'marine_identity.tsv.gz')) {
2036
					if ($globalDebug) echo "Gunzip...";
2037
					update_db::gunzip($tmp_dir.'marine_identity.tsv.gz');
2038
					if ($globalDebug) echo "Add to DB...";
2039
					$error = update_db::marine_identity_fam();
2040
				} else $error = "File ".$tmp_dir.'marine_identity.tsv.gz'." doesn't exist. Download failed.";
2041
				if ($error != '') {
2042
					return $error;
2043
				} elseif ($globalDebug) {
2044
					update_db::insert_marine_identity_version($marine_identity_md5);
2045
					echo "Done\n";
2046
				}
2047
			}
2048
		}
2049
		return '';
2050
	}
2051
	public static function update_banned_fam() {
2052
		global $tmp_dir, $globalDebug;
2053
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
2054
		update_db::download('http://data.flightairmap.fr/data/ban-eu.csv',$tmp_dir.'ban_eu.csv');
2055
		if (file_exists($tmp_dir.'ban_eu.csv')) {
2056
			//if ($globalDebug) echo "Gunzip...";
2057
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
2058
			if ($globalDebug) echo "Add to DB...";
2059
			$error = update_db::banned_fam();
2060
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
2061
		if ($error != '') {
2062
			return $error;
2063
		} elseif ($globalDebug) echo "Done\n";
2064
		return '';
2065
	}
2066
2067
	public static function update_airspace_fam() {
2068
		global $tmp_dir, $globalDebug, $globalDBdriver;
2069
		include_once('class.create_db.php');
2070
		$error = '';
2071
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
2072
		if ($globalDBdriver == 'mysql') {
2073
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2074
		} else {
2075
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
2076
		}
2077
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
2078
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
2079
			$airspace_md5 = $airspace_md5_file[0];
2080
			if (!update_db::check_airspace_version($airspace_md5)) {
2081
				if ($globalDBdriver == 'mysql') {
2082
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
2083
				} else {
2084
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
2085
				}
2086
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
2087
					if ($globalDebug) echo "Gunzip...";
2088
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
2089
					if ($globalDebug) echo "Add to DB...";
2090
					$Connection = new Connection();
2091
					if ($Connection->tableExists('airspace')) {
2092
						$query = 'DROP TABLE airspace';
2093
						try {
2094
							$sth = $Connection->db->prepare($query);
2095
    	    	    					$sth->execute();
2096
			            		} catch(PDOException $e) {
2097
							return "error : ".$e->getMessage();
2098
		            			}
2099
		    			}
2100
					$error = create_db::import_file($tmp_dir.'airspace.sql');
2101
					update_db::insert_airspace_version($airspace_md5);
2102
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
2103
			}
2104
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
2105
		if ($error != '') {
2106
			return $error;
2107
		} elseif ($globalDebug) echo "Done\n";
2108
		return '';
2109
	}
2110
2111
	public static function update_tle() {
2112
		global $tmp_dir, $globalDebug;
2113
		if ($globalDebug) echo "Download TLE : Download...";
2114
		$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',
2115
		'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',
2116
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
2117
		foreach ($alltle as $filename) {
2118
			if ($globalDebug) echo "downloading ".$filename.'...';
2119
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
2120
			if (file_exists($tmp_dir.$filename)) {
2121
				if ($globalDebug) echo "Add to DB ".$filename."...";
2122
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
2123
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
2124
			if ($error != '') {
2125
				echo $error."\n";
2126
			} elseif ($globalDebug) echo "Done\n";
2127
		}
2128
		return '';
2129
	}
2130
2131
	public static function update_models() {
2132
		global $tmp_dir, $globalDebug;
2133
		$error = '';
2134
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2135
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2136
		if (file_exists($tmp_dir.'models.md5sum')) {
2137
			if ($globalDebug) echo "Check files...\n";
2138
			$newmodelsdb = array();
2139
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2140
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2141
					$model = trim($row[2]);
2142
					$newmodelsdb[$model] = trim($row[0]);
2143
				}
2144
			}
2145
			$modelsdb = array();
2146
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2147
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2148
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2149
						$model = trim($row[2]);
2150
						$modelsdb[$model] = trim($row[0]);
2151
					}
2152
				}
2153
			}
2154
			$diff = array_diff($newmodelsdb,$modelsdb);
2155
			foreach ($diff as $key => $value) {
2156
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2157
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2158
				
2159
			}
2160
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2161
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2162
		if ($error != '') {
2163
			return $error;
2164
		} elseif ($globalDebug) echo "Done\n";
2165
		return '';
2166
	}
2167
2168
	public static function update_space_models() {
2169
		global $tmp_dir, $globalDebug;
2170
		$error = '';
2171
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2172
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2173
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2174
			if ($globalDebug) echo "Check files...\n";
2175
			$newmodelsdb = array();
2176
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2177
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2178
					$model = trim($row[2]);
2179
					$newmodelsdb[$model] = trim($row[0]);
2180
				}
2181
			}
2182
			$modelsdb = array();
2183
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2184
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2185
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2186
						$model = trim($row[2]);
2187
						$modelsdb[$model] = trim($row[0]);
2188
					}
2189
				}
2190
			}
2191
			$diff = array_diff($newmodelsdb,$modelsdb);
2192
			foreach ($diff as $key => $value) {
2193
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2194
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2195
				
2196
			}
2197
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2198
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2199
		if ($error != '') {
2200
			return $error;
2201
		} elseif ($globalDebug) echo "Done\n";
2202
		return '';
2203
	}
2204
2205
	public static function update_vehicules_models() {
2206
		global $tmp_dir, $globalDebug;
2207
		$error = '';
2208
		if ($globalDebug) echo "Vehicules models from FlightAirMap website : Download...";
2209
		update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',$tmp_dir.'vehicules_models.md5sum');
2210
		if (file_exists($tmp_dir.'vehicules_models.md5sum')) {
2211
			if ($globalDebug) echo "Check files...\n";
2212
			$newmodelsdb = array();
2213
			if (($handle = fopen($tmp_dir.'vehicules_models.md5sum','r')) !== FALSE) {
2214
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2215
					$model = trim($row[2]);
2216
					$newmodelsdb[$model] = trim($row[0]);
2217
				}
2218
			}
2219
			$modelsdb = array();
2220
			if (file_exists(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum')) {
2221
				if (($handle = fopen(dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum','r')) !== FALSE) {
2222
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2223
						$model = trim($row[2]);
2224
						$modelsdb[$model] = trim($row[0]);
2225
					}
2226
				}
2227
			}
2228
			$diff = array_diff($newmodelsdb,$modelsdb);
2229
			foreach ($diff as $key => $value) {
2230
				if ($globalDebug) echo 'Downloading vehicules model '.$key.' ...'."\n";
2231
				update_db::download('http://data.flightairmap.fr/data/models/vehicules/'.$key,dirname(__FILE__).'/../models/vehicules/'.$key);
2232
				
2233
			}
2234
			update_db::download('http://data.flightairmap.fr/data/models/vehicules/vehicules_models.md5sum',dirname(__FILE__).'/../models/vehicules/vehicules_models.md5sum');
2235
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2236
		if ($error != '') {
2237
			return $error;
2238
		} elseif ($globalDebug) echo "Done\n";
2239
		return '';
2240
	}
2241
2242
	public static function update_aircraft() {
2243
		global $tmp_dir, $globalDebug;
2244
		date_default_timezone_set('UTC');
2245
		//$error = '';
2246
		/*
2247
		if ($globalDebug) echo "Aircrafts : Download...";
2248
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2249
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2250
		//$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);
2251
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2252
//		echo strlen($data_req);
2253
		echo $data;
2254
		*/
2255
		if (file_exists($tmp_dir.'aircrafts.html')) {
2256
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2257
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2258
		    $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...
2259
		    //echo $result;
2260
		    //var_dump(str_get_html($result));
2261
		    //print_r(self::table2array($result));
2262
		}
2263
2264
	}
2265
	
2266
	public static function update_notam() {
2267
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2268
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2269
		$Common = new Common();
2270
		date_default_timezone_set('UTC');
2271
		$query = 'TRUNCATE TABLE notam';
2272
		try {
2273
			$Connection = new Connection();
2274
			$sth = $Connection->db->prepare($query);
2275
                        $sth->execute();
2276
                } catch(PDOException $e) {
2277
                        return "error : ".$e->getMessage();
2278
                }
2279
2280
		$error = '';
2281
		if ($globalDebug) echo "Notam : Download...";
2282
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2283
		if (file_exists($tmp_dir.'notam.rss')) {
2284
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2285
			foreach ($notams['channel']['item'] as $notam) {
2286
				$title = explode(':',$notam['title']);
2287
				$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...
2288
				unset($title[0]);
2289
				$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...
2290
				$description = strip_tags($notam['description'],'<pre>');
2291
				preg_match(':^(.*?)<pre>:',$description,$match);
2292
				$q = explode('/',$match[1]);
2293
				$data['fir'] = $q[0];
2294
				$data['code'] = $q[1];
2295
				$ifrvfr = $q[2];
2296
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2297
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2298
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2299
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2300
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2301
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2302
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2303
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2304
				//$data['scope'] = $q[4];
2305
				$data['lower_limit'] = $q[5];
2306
				$data['upper_limit'] = $q[6];
2307
				$latlonrad = $q[7];
2308
				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...
2309
				$latitude = $Common->convertDec($las,'latitude');
2310
				$longitude = $Common->convertDec($lns,'longitude');
2311
				if ($lac == 'S') $latitude = '-'.$latitude;
2312
				if ($lnc == 'W') $longitude = '-'.$longitude;
2313
				$data['center_latitude'] = $latitude;
2314
				$data['center_longitude'] = $longitude;
2315
				$data['radius'] = intval($radius);
2316
				
2317
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2318
				$data['text'] = $match[1];
2319
				preg_match(':</pre>(.*?)$:',$description,$match);
2320
				$fromto = $match[1];
2321
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2322
				$fromall = trim($match[1]);
2323
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2324
				$from = trim($match[1]);
2325
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2326
				preg_match('#TO:(.*?)$#',$fromto,$match);
2327
				$toall = trim($match[1]);
2328
				if (!preg_match(':Permanent:',$toall)) {
2329
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2330
					$to = trim($match[1]);
2331
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2332
					$data['permanent'] = 0;
2333
				} else {
2334
				    $data['date_end'] = NULL;
2335
				    $data['permanent'] = 1;
2336
				}
2337
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2338
				$NOTAM = new NOTAM();
2339
				$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']);
2340
				unset($data);
2341
			} 
2342
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2343
		if ($error != '') {
2344
			return $error;
2345
		} elseif ($globalDebug) echo "Done\n";
2346
		return '';
2347
	}
2348
	
2349
	public static function create_airspace() {
2350
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2351
		$Connection = new Connection();
2352
		if ($Connection->tableExists('airspace')) {
2353
			if ($globalDBdriver == 'mysql') {
2354
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2355
			} else {
2356
				$query = 'DROP TABLE airspace';
2357
			}
2358
			try {
2359
				$Connection = new Connection();
2360
				$sth = $Connection->db->prepare($query);
2361
				$sth->execute();
2362
			} catch(PDOException $e) {
2363
				return "error : ".$e->getMessage();
2364
			}
2365
		}
2366
		$Common = new Common();
2367
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2368
		$airspace_json = json_decode($airspace_lst,true);
2369
		foreach ($airspace_json['records'] as $airspace) {
2370
			if ($globalDebug) echo $airspace['name']."...\n";
2371
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2372
			if (file_exists($tmp_dir.$airspace['name'])) {
2373
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2374
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2375
				if ($globalDBdriver == 'mysql') {
2376
					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'].'"');
2377
				} else {
2378
					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'].'"');
2379
				}
2380
			}
2381
		}
2382
	}
2383
	
2384
	public static function fix_icaotype() {
2385
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
2386
		$Spotter = new Spotter();
2387
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
2388
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
2389
			try {
2390
				$Connection = new Connection();
2391
				$sth = $Connection->db->prepare($query);
2392
				$sth->execute(array(':new' => $new, ':old' => $old));
2393
			} catch(PDOException $e) {
2394
				return "error : ".$e->getMessage();
2395
			}
2396
		}
2397
	}
2398
2399
	public static function check_last_update() {
2400
		global $globalDBdriver;
2401
		if ($globalDBdriver == 'mysql') {
2402
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2403
		} else {
2404
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2405
		}
2406
		try {
2407
			$Connection = new Connection();
2408
			$sth = $Connection->db->prepare($query);
2409
                        $sth->execute();
2410
                } catch(PDOException $e) {
2411
                        return "error : ".$e->getMessage();
2412
                }
2413
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2414
                if ($row['nb'] > 0) return false;
2415
                else return true;
2416
	}
2417
2418
	public static function insert_last_update() {
2419
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2420
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2421
		try {
2422
			$Connection = new Connection();
2423
			$sth = $Connection->db->prepare($query);
2424
                        $sth->execute();
2425
                } catch(PDOException $e) {
2426
                        return "error : ".$e->getMessage();
2427
                }
2428
	}
2429
2430
	public static function check_airspace_version($version) {
2431
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2432
		try {
2433
			$Connection = new Connection();
2434
			$sth = $Connection->db->prepare($query);
2435
                        $sth->execute(array(':version' => $version));
2436
                } catch(PDOException $e) {
2437
                        return "error : ".$e->getMessage();
2438
                }
2439
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2440
                if ($row['nb'] > 0) return true;
2441
                else return false;
2442
	}
2443
2444
	public static function check_marine_identity_version($version) {
2445
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'marine_identity_version' AND value = :version";
2446
		try {
2447
			$Connection = new Connection();
2448
			$sth = $Connection->db->prepare($query);
2449
                        $sth->execute(array(':version' => $version));
2450
                } catch(PDOException $e) {
2451
                        return "error : ".$e->getMessage();
2452
                }
2453
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2454
                if ($row['nb'] > 0) return true;
2455
                else return false;
2456
	}
2457
2458
2459
	public static function insert_airspace_version($version) {
2460
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2461
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2462
		try {
2463
			$Connection = new Connection();
2464
			$sth = $Connection->db->prepare($query);
2465
                        $sth->execute(array(':version' => $version));
2466
                } catch(PDOException $e) {
2467
                        return "error : ".$e->getMessage();
2468
                }
2469
	}
2470
2471
	public static function insert_marine_identity_version($version) {
2472
		$query = "DELETE FROM config WHERE name = 'marine_identity_version';
2473
			INSERT INTO config (name,value) VALUES ('marine_identity_version',:version);";
2474
		try {
2475
			$Connection = new Connection();
2476
			$sth = $Connection->db->prepare($query);
2477
                        $sth->execute(array(':version' => $version));
2478
                } catch(PDOException $e) {
2479
                        return "error : ".$e->getMessage();
2480
                }
2481
	}
2482
2483
	public static function check_last_notam_update() {
2484
		global $globalDBdriver;
2485
		if ($globalDBdriver == 'mysql') {
2486
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2487
		} else {
2488
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2489
		}
2490
		try {
2491
			$Connection = new Connection();
2492
			$sth = $Connection->db->prepare($query);
2493
                        $sth->execute();
2494
                } catch(PDOException $e) {
2495
                        return "error : ".$e->getMessage();
2496
                }
2497
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2498
                if ($row['nb'] > 0) return false;
2499
                else return true;
2500
	}
2501
2502
	public static function insert_last_notam_update() {
2503
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2504
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2505
		try {
2506
			$Connection = new Connection();
2507
			$sth = $Connection->db->prepare($query);
2508
                        $sth->execute();
2509
                } catch(PDOException $e) {
2510
                        return "error : ".$e->getMessage();
2511
                }
2512
	}
2513
	public static function check_last_airspace_update() {
2514
		global $globalDBdriver;
2515
		if ($globalDBdriver == 'mysql') {
2516
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2517
		} else {
2518
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2519
		}
2520
		try {
2521
			$Connection = new Connection();
2522
			$sth = $Connection->db->prepare($query);
2523
                        $sth->execute();
2524
                } catch(PDOException $e) {
2525
                        return "error : ".$e->getMessage();
2526
                }
2527
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2528
                if ($row['nb'] > 0) return false;
2529
                else return true;
2530
	}
2531
2532
	public static function insert_last_airspace_update() {
2533
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2534
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2535
		try {
2536
			$Connection = new Connection();
2537
			$sth = $Connection->db->prepare($query);
2538
                        $sth->execute();
2539
                } catch(PDOException $e) {
2540
                        return "error : ".$e->getMessage();
2541
                }
2542
	}
2543
2544
	public static function check_last_owner_update() {
2545
		global $globalDBdriver;
2546
		if ($globalDBdriver == 'mysql') {
2547
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2548
		} else {
2549
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2550
		}
2551
		try {
2552
			$Connection = new Connection();
2553
			$sth = $Connection->db->prepare($query);
2554
                        $sth->execute();
2555
                } catch(PDOException $e) {
2556
                        return "error : ".$e->getMessage();
2557
                }
2558
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2559
                if ($row['nb'] > 0) return false;
2560
                else return true;
2561
	}
2562
2563
	public static function insert_last_owner_update() {
2564
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2565
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2566
		try {
2567
			$Connection = new Connection();
2568
			$sth = $Connection->db->prepare($query);
2569
                        $sth->execute();
2570
                } catch(PDOException $e) {
2571
                        return "error : ".$e->getMessage();
2572
                }
2573
	}
2574
	public static function check_last_schedules_update() {
2575
		global $globalDBdriver;
2576
		if ($globalDBdriver == 'mysql') {
2577
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2578
		} else {
2579
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2580
		}
2581
		try {
2582
			$Connection = new Connection();
2583
			$sth = $Connection->db->prepare($query);
2584
                        $sth->execute();
2585
                } catch(PDOException $e) {
2586
                        return "error : ".$e->getMessage();
2587
                }
2588
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2589
                if ($row['nb'] > 0) return false;
2590
                else return true;
2591
	}
2592
2593
	public static function insert_last_schedules_update() {
2594
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2595
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2596
		try {
2597
			$Connection = new Connection();
2598
			$sth = $Connection->db->prepare($query);
2599
                        $sth->execute();
2600
                } catch(PDOException $e) {
2601
                        return "error : ".$e->getMessage();
2602
                }
2603
	}
2604
	public static function check_last_tle_update() {
2605
		global $globalDBdriver;
2606
		if ($globalDBdriver == 'mysql') {
2607
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2608
		} else {
2609
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2610
		}
2611
		try {
2612
			$Connection = new Connection();
2613
			$sth = $Connection->db->prepare($query);
2614
                        $sth->execute();
2615
                } catch(PDOException $e) {
2616
                        return "error : ".$e->getMessage();
2617
                }
2618
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2619
                if ($row['nb'] > 0) return false;
2620
                else return true;
2621
	}
2622
2623
	public static function insert_last_tle_update() {
2624
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2625
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2626
		try {
2627
			$Connection = new Connection();
2628
			$sth = $Connection->db->prepare($query);
2629
                        $sth->execute();
2630
                } catch(PDOException $e) {
2631
                        return "error : ".$e->getMessage();
2632
                }
2633
	}
2634
	public static function check_last_marine_identity_update() {
2635
		global $globalDBdriver;
2636
		if ($globalDBdriver == 'mysql') {
2637
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2638
		} else {
2639
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_marine_identity' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2640
		}
2641
		try {
2642
			$Connection = new Connection();
2643
			$sth = $Connection->db->prepare($query);
2644
                        $sth->execute();
2645
                } catch(PDOException $e) {
2646
                        return "error : ".$e->getMessage();
2647
                }
2648
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2649
                if ($row['nb'] > 0) return false;
2650
                else return true;
2651
	}
2652
2653
	public static function insert_last_marine_identity_update() {
2654
		$query = "DELETE FROM config WHERE name = 'last_update_marine_identity';
2655
			INSERT INTO config (name,value) VALUES ('last_update_marine_identity',NOW());";
2656
		try {
2657
			$Connection = new Connection();
2658
			$sth = $Connection->db->prepare($query);
2659
                        $sth->execute();
2660
                } catch(PDOException $e) {
2661
                        return "error : ".$e->getMessage();
2662
                }
2663
	}
2664
	public static function delete_duplicatemodes() {
2665
		global $globalDBdriver;
2666
		if ($globalDBdriver == 'mysql') {
2667
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
2668
		} else {
2669
			$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'";
2670
		}
2671
		try {
2672
			$Connection = new Connection();
2673
			$sth = $Connection->db->prepare($query);
2674
                        $sth->execute();
2675
                } catch(PDOException $e) {
2676
                        return "error : ".$e->getMessage();
2677
                }
2678
	}
2679
	public static function delete_duplicateowner() {
2680
		global $globalDBdriver;
2681
		if ($globalDBdriver == 'mysql') {
2682
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
2683
		} else {
2684
			$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)";
2685
		}
2686
		try {
2687
			$Connection = new Connection();
2688
			$sth = $Connection->db->prepare($query);
2689
                        $sth->execute();
2690
                } catch(PDOException $e) {
2691
                        return "error : ".$e->getMessage();
2692
                }
2693
	}
2694
	
2695
	public static function update_all() {
2696
		global $globalMasterServer, $globalMasterSource;
2697
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2698
			if (isset($globalMasterSource) && $globalMasterSource) {
2699
				echo update_db::update_routes();
2700
				echo update_db::update_translation();
2701
				//echo update_db::update_notam_fam();
2702
				echo update_db::update_ModeS();
2703
				//echo update_db::update_ModeS_flarm();
2704
				echo update_db::update_ModeS_ogn();
2705
				echo update_db::update_ModeS_faa();
2706
				echo update_db::fix_icaotype();
2707
				echo update_db::update_banned_fam();
2708
				//echo update_db::delete_duplicatemodes();
2709
			} else {
2710
				//echo update_db::update_routes();
2711
				echo update_db::update_routes_fam();
2712
				echo update_db::update_translation();
2713
				echo update_db::update_translation_fam();
2714
				//echo update_db::update_notam_fam();
2715
				//echo update_db::update_ModeS();
2716
				echo update_db::update_ModeS_fam();
2717
				//echo update_db::update_ModeS_flarm();
2718
				echo update_db::update_ModeS_ogn();
2719
				//echo update_db::delete_duplicatemodes();
2720
				echo update_db::update_banned_fam();
2721
			}
2722
		}
2723
	}
2724
}
2725
2726
//echo update_db::update_airports();
2727
//echo update_db::translation();
2728
//echo update_db::update_waypoints();
2729
//echo update_db::update_airspace();
2730
//echo update_db::update_notam();
2731
//echo update_db::update_ivao();
2732
//echo update_db::update_ModeS_flarm();
2733
//echo update_db::update_ModeS_ogn();
2734
//echo update_db::update_aircraft();
2735
//$update_db = new update_db();
2736
//echo update_db::update_owner();
2737
//update_db::update_translation_fam();
2738
//echo update_db::update_routes();
2739
//update_db::update_models();
2740
//echo $update_db::update_skyteam();
2741
//echo $update_db::update_tle();
2742
//echo update_db::update_notam_fam();
2743
//echo update_db::create_airspace();
2744
//echo update_db::update_ModeS();
2745
//echo update_db::update_ModeS_fam();
2746
//echo update_db::update_routes_fam();
2747
//echo update_db::update_ModeS_faa();
2748
//echo update_db::update_banned_fam();
2749
//echo update_db::modes_faa();
2750
//echo update_db::update_owner_fam();
2751
//echo update_db::delete_duplicateowner();
2752
//echo update_db::fix_icaotype();
2753
?>
2754