Completed
Push — master ( 649c27...efcf4c )
by Yannick
23:43
created

update_db::table2array()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 18
nc 5
nop 1
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
1
<?php
2
//require_once('libs/simple_html_dom.php');
3
require(dirname(__FILE__).'/../require/settings.php');
4
require_once(dirname(__FILE__).'/../require/class.Common.php');
5
require_once(dirname(__FILE__).'/../require/class.Connection.php');
6
7
$tmp_dir = dirname(__FILE__).'/tmp/';
8
//$globalDebug = true;
9
//$globalTransaction = true;
10
class update_db {
11
	public static $db_sqlite;
12
13
	public static function 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();
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();
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();
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();
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();
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();
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();
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();
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();
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();
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();
351
				$tmp = fgetcsv($fh,9999,',',"'");
0 ignored issues
show
Unused Code introduced by
$tmp is not used, you could remove the assignment.

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

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

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

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

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

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
929
		$delimiter = ';';
930
		$Connection = new Connection();
931
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
932
		{
933
			$i = 0;
934
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
935
			//$Connection->db->beginTransaction();
936
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
937
			{
938
				$i++;
939
				if($i > 12) {
940
					$data = $row;
941
					$operator = $data[2];
942
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
943
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
944
                                                //echo substr($operator, 0, 2)."\n";;
945
                                                if (count($airline_array) > 0) {
946
							//print_r($airline_array);
947
							$operator = $airline_array[0]['icao'].substr($operator,2);
948
                                                }
949
                                        }
950
					
951
					$operator_correct = $data[3];
952
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
953
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
954
                                                if (count($airline_array) > 0) {
955
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
956
                                            	}
957
                                        }
958
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
959
					try {
960
						$sth = $Connection->db->prepare($query);
961
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
962
					} catch(PDOException $e) {
963
						return "error : ".$e->getMessage();
964
					}
965
				}
966
			}
967
			fclose($handle);
968
			//$Connection->db->commit();
969
		}
970
		return '';
971
        }
972
	
973
	public static function translation_fam() {
974
		global $tmp_dir, $globalTransaction;
975
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
976
		try {
977
			$Connection = new Connection();
978
			$sth = $Connection->db->prepare($query);
979
			$sth->execute(array(':source' => 'website_fam'));
980
		} catch(PDOException $e) {
981
			return "error : ".$e->getMessage();
982
		}
983
		//update_db::unzip($out_file);
984
		$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...
985
		$delimiter = "\t";
986
		$Connection = new Connection();
987
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
988
		{
989
			$i = 0;
990
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
991
			//$Connection->db->beginTransaction();
992
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
993
			{
994
				if ($i > 0) {
995
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
996
					try {
997
						$sth = $Connection->db->prepare($query);
998
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
999
					} catch(PDOException $e) {
1000
						return "error : ".$e->getMessage();
1001
					}
1002
				}
1003
				$i++;
1004
			}
1005
			fclose($handle);
1006
			//$Connection->db->commit();
1007
		}
1008
		return '';
1009
        }
1010
1011
	/*
1012
	* This function use FAA public data.
1013
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
1014
	*/
1015
	public static function modes_faa() {
1016
		global $tmp_dir, $globalTransaction, $globalDebug;
1017
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1018
		try {
1019
			$Connection = new Connection();
1020
			$sth = $Connection->db->prepare($query);
1021
                        $sth->execute(array(':source' => 'website_faa'));
1022
                } catch(PDOException $e) {
1023
                        return "error : ".$e->getMessage();
1024
                }
1025
1026
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1027
		try {
1028
			$Connection = new Connection();
1029
			$sth = $Connection->db->prepare($query);
1030
                        $sth->execute(array(':source' => 'website_faa'));
1031
                } catch(PDOException $e) {
1032
                        return "error : ".$e->getMessage();
1033
                }
1034
1035
		$delimiter = ",";
1036
		$mfr = array();
0 ignored issues
show
Unused Code introduced by
$mfr is not used, you could remove the assignment.

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

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

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

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

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