Completed
Push — master ( 19763d...b52f48 )
by Yannick
05:40
created

update_db::delete_duplicatemodes()   A

Complexity

Conditions 3
Paths 8

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
244
		} catch(PDOException $e) {
245
			return "error : ".$e->getMessage();
246
		}
247
248
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
249
		try {
250
			$Connection = new Connection();
251
			$sth = $Connection->db->prepare($query);
252
                        $sth->execute(array(':source' => $database_file));
253
                } catch(PDOException $e) {
254
                        return "error : ".$e->getMessage();
255
                }
256
		return '';
257
	}
258
259
	public static function retrieve_modes_flarmnet($database_file) {
260
		global $globalTransaction;
261
		$Common = new Common();
262
		//$query = 'TRUNCATE TABLE aircraft_modes';
263
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
264
		try {
265
			$Connection = new Connection();
266
			$sth = $Connection->db->prepare($query);
267
                        $sth->execute(array(':source' => $database_file));
268
                } catch(PDOException $e) {
269
                        return "error : ".$e->getMessage();
270
                }
271
		
272
		if ($fh = fopen($database_file,"r")) {
273
			//$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)';
274
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
275
		
276
			$Connection = new Connection();
277
			$sth_dest = $Connection->db->prepare($query_dest);
278
			try {
279
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
280
            			while (!feof($fh)) {
281
            				$values = array();
282
            				$line = $Common->hex2str(fgets($fh,9999));
283
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
284
            				$values['ModeS'] = substr($line,0,6);
285
            				$values['Registration'] = trim(substr($line,69,6));
286
            				$aircraft_name = trim(substr($line,48,6));
287
            				// Check if we can find ICAO, else set it to GLID
288
            				$aircraft_name_split = explode(' ',$aircraft_name);
289
            				$search_more = '';
290
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
291
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
292
            				$sth_search = $Connection->db->prepare($query_search);
293
					try {
294
                                    		$sth_search->execute();
295
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
296
	            				//if (count($result) > 0) {
297
	            				if (isset($result['icao']) && $result['icao'] != '') {
298
	            				    $values['ICAOTypeCode'] = $result['icao'];
299
	            				} 
300
					} catch(PDOException $e) {
301
						return "error : ".$e->getMessage();
302
					}
303
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
304
					// Add data to db
305
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000') {
306
						//$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']);
307
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
308
						//print_r($query_dest_values);
309
						$sth_dest->execute($query_dest_values);
310
					}
311
				}
312
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
313
			} catch(PDOException $e) {
314
				return "error : ".$e->getMessage();
315
			}
316
		}
317
318
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
319
		try {
320
			$Connection = new Connection();
321
			$sth = $Connection->db->prepare($query);
322
                        $sth->execute(array(':source' => $database_file));
323
                } catch(PDOException $e) {
324
                        return "error : ".$e->getMessage();
325
                }
326
		return '';
327
	}
328
329
	public static function retrieve_modes_ogn($database_file) {
330
		global $globalTransaction;
331
		//$query = 'TRUNCATE TABLE aircraft_modes';
332
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
333
		try {
334
			$Connection = new Connection();
335
			$sth = $Connection->db->prepare($query);
336
                        $sth->execute(array(':source' => $database_file));
337
                } catch(PDOException $e) {
338
                        return "error : ".$e->getMessage();
339
                }
340
		
341
		if ($fh = fopen($database_file,"r")) {
342
			//$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)';
343
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
344
		
345
			$Connection = new Connection();
346
			$sth_dest = $Connection->db->prepare($query_dest);
347
			try {
348
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
349
				$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...
350
            			while (!feof($fh)) {
351
            				$line = fgetcsv($fh,9999,',',"'");
352
            				
353
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
354
					//print_r($line);
355
            				$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...
356
            				$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...
357
            				$aircraft_name = $line[2];
358
            				// Check if we can find ICAO, else set it to GLID
359
            				$aircraft_name_split = explode(' ',$aircraft_name);
360
            				$search_more = '';
361
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
362
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
363
            				$sth_search = $Connection->db->prepare($query_search);
364
					try {
365
                                    		$sth_search->execute();
366
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
367
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
368
					} catch(PDOException $e) {
369
						return "error : ".$e->getMessage();
370
					}
371
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
372
					// Add data to db
373
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
374
						//$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']);
375
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
376
						//print_r($query_dest_values);
377
						$sth_dest->execute($query_dest_values);
378
					}
379
				}
380
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
381
			} catch(PDOException $e) {
382
				return "error : ".$e->getMessage();
383
			}
384
		}
385
386
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
387
		try {
388
			$Connection = new Connection();
389
			$sth = $Connection->db->prepare($query);
390
                        $sth->execute(array(':source' => $database_file));
391
                } catch(PDOException $e) {
392
                        return "error : ".$e->getMessage();
393
                }
394
		return '';
395
	}
396
397
	public static function retrieve_owner($database_file,$country = 'F') {
398
		global $globalTransaction;
399
		//$query = 'TRUNCATE TABLE aircraft_modes';
400
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
401
		try {
402
			$Connection = new Connection();
403
			$sth = $Connection->db->prepare($query);
404
                        $sth->execute(array(':source' => $database_file));
405
                } catch(PDOException $e) {
406
                        return "error : ".$e->getMessage();
407
                }
408
		
409
		if ($fh = fopen($database_file,"r")) {
410
			//$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)';
411
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
412
		
413
			$Connection = new Connection();
414
			$sth_dest = $Connection->db->prepare($query_dest);
415
			try {
416
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

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

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

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

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

Loading history...
648
  
649
		$i = 0;
650
		while($row = sparql_fetch_array($result))
651
		{
652
			if ($i >= 1) {
653
			//print_r($row);
654
			if (!isset($row['iata'])) $row['iata'] = '';
655
			if (!isset($row['icao'])) $row['icao'] = '';
656
			if (!isset($row['type'])) $row['type'] = '';
657
			if (!isset($row['altitude'])) $row['altitude'] = '';
658
			if (isset($row['city_bis'])) {
659
				$row['city'] = $row['city_bis'];
660
			}
661
			if (!isset($row['city'])) $row['city'] = '';
662
			if (!isset($row['country'])) $row['country'] = '';
663
			if (!isset($row['homepage'])) $row['homepage'] = '';
664
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
665
			if (!isset($row['name'])) continue;
666
			if (!isset($row['image'])) {
667
				$row['image'] = '';
668
				$row['image_thumb'] = '';
669
			} else {
670
				$image = str_replace(' ','_',$row['image']);
671
				$digest = md5($image);
672
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
673
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
674
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
675
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
676
			}
677
			
678
			$country = explode('-',$row['country']);
679
			$row['country'] = $country[0];
680
			
681
			$row['type'] = trim($row['type']);
682
			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'])) {
683
				$row['type'] = 'Military';
684
			} 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') {
685
				$row['type'] = 'small_airport';
686
			}
687
			
688
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
689
			$query_dest_values = array(':airport_id' => $i, ':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => $row['altitude'],':type' => $row['type'],':city' => $row['city'],':country' => $row['country'],':home_link' => $row['homepage'],':wikipedia_link' => $row['wikipedia_page'],':image' => $row['image'],':image_thumb' => $row['image_thumb']);
690
			//print_r($query_dest_values);
691
			
692
			try {
693
				$sth_dest->execute($query_dest_values);
694
			} catch(PDOException $e) {
695
				return "error : ".$e->getMessage();
696
			}
697
			}
698
699
			$i++;
700
		}
701
		if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
702
		echo "Delete duplicate rows...\n";
703
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
704
		try {
705
			$Connection = new Connection();
706
			$sth = $Connection->db->prepare($query);
707
                        $sth->execute();
708
                } catch(PDOException $e) {
709
                        return "error : ".$e->getMessage();
710
                }
711
712
713
		if ($globalDebug) echo "Insert Not available Airport...\n";
714
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
715
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
716
		$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' => '');
717
		try {
718
			$Connection = new Connection();
719
			$sth = $Connection->db->prepare($query);
720
                        $sth->execute($query_values);
721
                } catch(PDOException $e) {
722
                        return "error : ".$e->getMessage();
723
                }
724
		$i++;
725
/*
726
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
727
		try {
728
			$Connection = new Connection();
729
			$sth = $Connection->db->prepare($query);
730
                        $sth->execute();
731
                } catch(PDOException $e) {
732
                        return "error : ".$e->getMessage();
733
                }
734
*/
735
736
		echo "Download data from ourairports.com...\n";
737
		$delimiter = ',';
738
		$out_file = $tmp_dir.'airports.csv';
739
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
740
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
741
		echo "Add data from ourairports.com...\n";
742
743
		$header = NULL;
744
		if (($handle = fopen($out_file, 'r')) !== FALSE)
745
		{
746
			$Connection = new Connection();
747
			//$Connection->db->beginTransaction();
748
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
749
			{
750
				if(!$header) $header = $row;
751
				else {
752
					$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...
753
					$data = array_combine($header, $row);
754
					try {
755
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
756
						$sth->execute(array(':icao' => $data['gps_code']));
757
					} catch(PDOException $e) {
758
						return "error : ".$e->getMessage();
759
					}
760
					if ($sth->fetchColumn() > 0) {
761
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
762
						try {
763
							$sth = $Connection->db->prepare($query);
764
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
765
						} catch(PDOException $e) {
766
							return "error : ".$e->getMessage();
767
						}
768
					} else {
769
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
770
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
771
						$query_values = array(':airport_id' => $i, ':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => $data['elevation_ft'],':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
772
						try {
773
							$sth = $Connection->db->prepare($query);
774
							$sth->execute($query_values);
775
						} catch(PDOException $e) {
776
							return "error : ".$e->getMessage();
777
						}
778
						$i++;
779
					}
780
				}
781
			}
782
			fclose($handle);
783
			//$Connection->db->commit();
784
		}
785
786
		echo "Download data from another free database...\n";
787
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
788
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
789
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
790
		update_db::unzip($out_file);
791
		$header = NULL;
792
		echo "Add data from another free database...\n";
793
		$delimiter = ':';
794
		$Connection = new Connection();
795
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
796
		{
797
			//$Connection->db->beginTransaction();
798
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
799
			{
800
				if(!$header) $header = $row;
801
				else {
802
					$data = $row;
803
804
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
805
					try {
806
						$sth = $Connection->db->prepare($query);
807
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
808
					} catch(PDOException $e) {
809
						return "error : ".$e->getMessage();
810
					}
811
				}
812
			}
813
			fclose($handle);
814
			//$Connection->db->commit();
815
		}
816
817
		echo "Put type military for all air base";
818
		$Connection = new Connection();
819
		try {
820
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
821
			$sth->execute();
822
		} catch(PDOException $e) {
823
			return "error : ".$e->getMessage();
824
		}
825
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
826
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
827
			try {
828
				$sth2 = $Connection->db->prepare($query2);
829
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
830
			} catch(PDOException $e) {
831
				return "error : ".$e->getMessage();
832
			}
833
		}
834
835
836
837
                return "success";
838
	}
839
	
840
	public static function translation() {
841
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
842
		global $tmp_dir, $globalTransaction;
843
		$Spotter = new Spotter();
844
		//$out_file = $tmp_dir.'translation.zip';
845
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
846
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
847
		
848
		//$query = 'TRUNCATE TABLE translation';
849
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
850
		try {
851
			$Connection = new Connection();
852
			$sth = $Connection->db->prepare($query);
853
                        $sth->execute(array(':source' => 'translation.csv'));
854
                } catch(PDOException $e) {
855
                        return "error : ".$e->getMessage();
856
                }
857
858
		
859
		//update_db::unzip($out_file);
860
		$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...
861
		$delimiter = ';';
862
		$Connection = new Connection();
863
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
864
		{
865
			$i = 0;
866
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
867
			//$Connection->db->beginTransaction();
868
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
869
			{
870
				$i++;
871
				if($i > 12) {
872
					$data = $row;
873
					$operator = $data[2];
874
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
875
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
876
                                                //echo substr($operator, 0, 2)."\n";;
877
                                                if (count($airline_array) > 0) {
878
							//print_r($airline_array);
879
							$operator = $airline_array[0]['icao'].substr($operator,2);
880
                                                }
881
                                        }
882
					
883
					$operator_correct = $data[3];
884
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
885
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
886
                                                if (count($airline_array) > 0) {
887
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
888
                                            	}
889
                                        }
890
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
891
					try {
892
						$sth = $Connection->db->prepare($query);
893
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
894
					} catch(PDOException $e) {
895
						return "error : ".$e->getMessage();
896
					}
897
				}
898
			}
899
			fclose($handle);
900
			//$Connection->db->commit();
901
		}
902
		return '';
903
        }
904
	
905
	public static function translation_fam() {
906
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
907
		global $tmp_dir, $globalTransaction;
908
		$Spotter = new Spotter();
0 ignored issues
show
Unused Code introduced by
$Spotter is not used, you could remove the assignment.

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

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

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

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

Loading history...
909
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
910
		try {
911
			$Connection = new Connection();
912
			$sth = $Connection->db->prepare($query);
913
                        $sth->execute(array(':source' => 'website_fam'));
914
                } catch(PDOException $e) {
915
                        return "error : ".$e->getMessage();
916
                }
917
918
		
919
		//update_db::unzip($out_file);
920
		$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...
921
		$delimiter = "\t";
922
		$Connection = new Connection();
923
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
924
		{
925
			$i = 0;
926
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
927
			//$Connection->db->beginTransaction();
928
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
929
			{
930
				if ($i > 0) {
931
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
932
					try {
933
						$sth = $Connection->db->prepare($query);
934
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
935
					} catch(PDOException $e) {
936
						return "error : ".$e->getMessage();
937
					}
938
				}
939
				$i++;
940
			}
941
			fclose($handle);
942
			//$Connection->db->commit();
943
		}
944
		return '';
945
        }
946
947
	public static function modes_fam() {
948
		global $tmp_dir, $globalTransaction;
949
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
950
		try {
951
			$Connection = new Connection();
952
			$sth = $Connection->db->prepare($query);
953
                        $sth->execute(array(':source' => 'website_fam'));
954
                } catch(PDOException $e) {
955
                        return "error : ".$e->getMessage();
956
                }
957
958
		
959
		//update_db::unzip($out_file);
960
		$delimiter = "\t";
961
		$Connection = new Connection();
962
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
963
		{
964
			$i = 0;
965
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
966
			//$Connection->db->beginTransaction();
967
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
968
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
969
			{
970
				if ($i > 0) {
971
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
972
					try {
973
						$sth = $Connection->db->prepare($query);
974
						$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'));
975
					} catch(PDOException $e) {
976
						return "error : ".$e->getMessage();
977
					}
978
				}
979
				$i++;
980
			}
981
			fclose($handle);
982
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
983
		}
984
		return '';
985
        }
986
987
	public static function routes_fam() {
988
		global $tmp_dir, $globalTransaction;
989
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
990
		try {
991
			$Connection = new Connection();
992
			$sth = $Connection->db->prepare($query);
993
                        $sth->execute(array(':source' => 'website_fam'));
994
                } catch(PDOException $e) {
995
                        return "error : ".$e->getMessage();
996
                }
997
998
		
999
		//update_db::unzip($out_file);
1000
		$delimiter = "\t";
1001
		$Connection = new Connection();
1002
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1003
		{
1004
			$i = 0;
1005
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1006
			//$Connection->db->beginTransaction();
1007
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
1008
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1009
			{
1010
				if ($i > 0) {
1011
					$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)';
1012
					try {
1013
						$sth = $Connection->db->prepare($query);
1014
						$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'));
1015
					} catch(PDOException $e) {
1016
						return "error : ".$e->getMessage();
1017
					}
1018
				}
1019
				$i++;
1020
			}
1021
			fclose($handle);
1022
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
1023
		}
1024
		return '';
1025
        }
1026
1027
	public static function tle($filename,$tletype) {
1028
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1029
		global $tmp_dir, $globalTransaction;
1030
		//$Spotter = new Spotter();
1031
		
1032
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1033
		try {
1034
			$Connection = new Connection();
1035
			$sth = $Connection->db->prepare($query);
1036
                        $sth->execute(array(':source' => $filename));
1037
                } catch(PDOException $e) {
1038
                        return "error : ".$e->getMessage();
1039
                }
1040
		
1041
		$Connection = new Connection();
1042
		if (($handle = fopen($filename, 'r')) !== FALSE)
1043
		{
1044
			$i = 0;
1045
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1046
			//$Connection->db->beginTransaction();
1047
			$dbdata = array();
1048
			while (($data = fgets($handle, 1000)) !== FALSE)
1049
			{
1050
				if ($i == 0) {
1051
					$dbdata['name'] = trim($data);
1052
					$i++;
1053
				} elseif ($i == 1) {
1054
					$dbdata['tle1'] = trim($data);
1055
					$i++;
1056
				} elseif ($i == 2) {
1057
					$dbdata['tle2'] = trim($data);
1058
					//print_r($dbdata);
1059
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1060
					try {
1061
						$sth = $Connection->db->prepare($query);
1062
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1063
					} catch(PDOException $e) {
1064
						return "error : ".$e->getMessage();
1065
					}
1066
1067
					$i = 0;
1068
				}
1069
			}
1070
			fclose($handle);
1071
			//$Connection->db->commit();
1072
		}
1073
		return '';
1074
        }
1075
1076
	/**
1077
        * Convert a HTML table to an array
1078
        * @param String $data HTML page
1079
        * @return Array array of the tables in HTML page
1080
        */
1081
        private static function table2array($data) {
1082
                $html = str_get_html($data);
1083
                $tabledata=array();
1084
                foreach($html->find('tr') as $element)
1085
                {
1086
                        $td = array();
1087
                        foreach( $element->find('th') as $row)
1088
                        {
1089
                                $td [] = trim($row->plaintext);
1090
                        }
1091
                        $td=array_filter($td);
1092
                        $tabledata[] = $td;
1093
1094
                        $td = array();
1095
                        $tdi = array();
1096
                        foreach( $element->find('td') as $row)
1097
                        {
1098
                                $td [] = trim($row->plaintext);
1099
                                $tdi [] = trim($row->innertext);
1100
                        }
1101
                        $td=array_filter($td);
1102
                        $tdi=array_filter($tdi);
0 ignored issues
show
Unused Code introduced by
$tdi is not used, you could remove the assignment.

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

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

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

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

Loading history...
1103
                    //    $tabledata[]=array_merge($td,$tdi);
1104
                        $tabledata[]=$td;
1105
                }
1106
                return(array_filter($tabledata));
1107
        }
1108
1109
       /**
1110
        * Get data from form result
1111
        * @param String $url form URL
1112
        * @return String the result
1113
        */
1114
        private static function getData($url) {
1115
                $ch = curl_init();
1116
                curl_setopt($ch, CURLOPT_URL, $url);
1117
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1118
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1119
                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');
1120
                return curl_exec($ch);
1121
        }
1122
/*
1123
	public static function waypoints() {
1124
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1125
		$table = update_db::table2array($data);
1126
//		print_r($table);
1127
		$query = 'TRUNCATE TABLE waypoints';
1128
		try {
1129
			$Connection = new Connection();
1130
			$sth = $Connection->db->prepare($query);
1131
                        $sth->execute();
1132
                } catch(PDOException $e) {
1133
                        return "error : ".$e->getMessage();
1134
                }
1135
1136
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1137
		$Connection = new Connection();
1138
		$sth_dest = $Connection->db->prepare($query_dest);
1139
		$Connection->db->beginTransaction();
1140
                foreach ($table as $row) {
1141
            		if ($row[0] != 'Ident') {
1142
				$ident = $row[0];
1143
				$latitude = $row[2];
1144
				$longitude = $row[3];
1145
				$control = $row[4];
1146
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1147
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1148
				try {
1149
					$sth_dest->execute($query_dest_values);
1150
				} catch(PDOException $e) {
1151
					return "error : ".$e->getMessage();
1152
				}
1153
			}
1154
                }
1155
		$Connection->db->commit();
1156
1157
	}
1158
*/
1159
	public static function waypoints($filename) {
1160
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1161
		global $tmp_dir, $globalTransaction;
1162
		//$Spotter = new Spotter();
1163
		//$out_file = $tmp_dir.'translation.zip';
1164
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1165
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1166
		$Connection = new Connection();
1167
		//update_db::unzip($out_file);
1168
		$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...
1169
		$delimiter = ' ';
1170
		if (($handle = fopen($filename, 'r')) !== FALSE)
1171
		{
1172
			$i = 0;
1173
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
1174
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1175
			{
1176
				$i++;
1177
				if($i > 3 && count($row) > 2) {
1178
					$data = array_values(array_filter($row));
1179
					$cntdata = count($data);
1180
					if ($cntdata > 10) {
1181
						$value = $data[9];
1182
						
1183
						for ($i =10;$i < $cntdata;$i++) {
1184
							$value .= ' '.$data[$i];
1185
						}
1186
						$data[9] = $value;
1187
					}
1188
					//print_r($data);
1189
					if (count($data) > 9) {
1190
						$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)';
1191
						try {
1192
							$sth = $Connection->db->prepare($query);
1193
							$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]));
1194
						} catch(PDOException $e) {
1195
							return "error : ".$e->getMessage();
1196
						}
1197
					}
1198
				}
1199
			}
1200
			fclose($handle);
1201
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
1202
		}
1203
		return '';
1204
        }
1205
1206
	public static function ivao_airlines($filename) {
1207
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1208
		global $tmp_dir, $globalTransaction;
1209
		//$query = 'TRUNCATE TABLE airlines';
1210
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1211
		try {
1212
			$Connection = new Connection();
1213
			$sth = $Connection->db->prepare($query);
1214
                        $sth->execute();
1215
                } catch(PDOException $e) {
1216
                        return "error : ".$e->getMessage();
1217
                }
1218
1219
		$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...
1220
		$delimiter = ':';
1221
		$Connection = new Connection();
1222
		if (($handle = fopen($filename, 'r')) !== FALSE)
1223
		{
1224
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
1225
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1226
			{
1227
				if(count($row) > 1) {
1228
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1229
					try {
1230
						$sth = $Connection->db->prepare($query);
1231
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1232
					} catch(PDOException $e) {
1233
						return "error : ".$e->getMessage();
1234
					}
1235
				}
1236
			}
1237
			fclose($handle);
1238
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
1239
		}
1240
		return '';
1241
        }
1242
	
1243
	public static function update_airspace() {
1244
		global $tmp_dir, $globalDBdriver;
1245
		include_once('class.create_db.php');
1246
		$Connection = new Connection();
1247
		if ($Connection->tableExists('airspace')) {
1248
			$query = 'DROP TABLE airspace';
1249
			try {
1250
				$sth = $Connection->db->prepare($query);
1251
                    		$sth->execute();
1252
	                } catch(PDOException $e) {
1253
				return "error : ".$e->getMessage();
1254
	                }
1255
	        }
1256
1257
1258
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1259
		else {
1260
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1261
			$query = "CREATE EXTENSION postgis";
1262
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1263
			try {
1264
				$sth = $Connection->db->prepare($query);
1265
				$sth->execute();
1266
			} catch(PDOException $e) {
1267
				return "error : ".$e->getMessage();
1268
			}
1269
		}
1270
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1271
		return $error;
1272
	}
1273
1274
	public static function update_notam_fam() {
1275
		global $tmp_dir, $globalDebug;
1276
		include_once('class.create_db.php');
1277
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1278
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1279
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1280
		$error = '';
1281
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1282
			if ($globalDebug) echo "Gunzip...";
1283
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1284
			if ($globalDebug) echo "Add to DB...";
1285
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1286
			$NOTAM = new NOTAM();
1287
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1288
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1289
		if ($error != '') {
1290
			return $error;
1291
		} elseif ($globalDebug) echo "Done\n";
1292
		return '';
1293
	}
1294
1295
	public static function update_vatsim() {
1296
		global $tmp_dir;
1297
		include_once('class.create_db.php');
1298
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1299
		return $error;
1300
	}
1301
	
1302
	public static function update_countries() {
1303
		global $tmp_dir, $globalDBdriver;
1304
		include_once('class.create_db.php');
1305
		$Connection = new Connection();
1306
		if ($Connection->tableExists('countries')) {
1307
			$query = 'DROP TABLE countries';
1308
			try {
1309
				$sth = $Connection->db->prepare($query);
1310
            	        	$sth->execute();
1311
	                } catch(PDOException $e) {
1312
    	                	echo "error : ".$e->getMessage();
1313
	                }
1314
		}
1315
		if ($globalDBdriver == 'mysql') {
1316
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1317
		} else {
1318
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1319
		}
1320
		$error = create_db::import_file($tmp_dir.'countries.sql');
1321
		return $error;
1322
	}
1323
1324
	
1325
	public static function update_waypoints() {
1326
		global $tmp_dir;
1327
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1328
//		update_db::unzip($tmp_dir.'AptNav.zip');
1329
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1330
//		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');
1331
		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');
1332
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1333
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1334
		return $error;
1335
	}
1336
1337
	public static function update_ivao() {
1338
		global $tmp_dir, $globalDebug;
1339
		$Common = new Common();
1340
		$error = '';
1341
		//Direct download forbidden
1342
		//if ($globalDebug) echo "IVAO : Download...";
1343
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1344
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1345
			if ($globalDebug) echo "Unzip...";
1346
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1347
			if ($globalDebug) echo "Add to DB...";
1348
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1349
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1350
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1351
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1352
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1353
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1354
		if ($error != '') {
1355
			return $error;
1356
		} elseif ($globalDebug) echo "Done\n";
1357
		return '';
1358
	}
1359
1360
	public static function update_routes() {
1361
		global $tmp_dir, $globalDebug;
1362
		$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...
1363
		if ($globalDebug) echo "Routes : Download...";
1364
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1365
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1366
			if ($globalDebug) echo "Gunzip...";
1367
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1368
			if ($globalDebug) echo "Add to DB...";
1369
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1370
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1371
		if ($error != '') {
1372
			return $error;
1373
		} elseif ($globalDebug) echo "Done\n";
1374
		return '';
1375
	}
1376
	public static function update_oneworld() {
1377
		global $tmp_dir, $globalDebug;
1378
		$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...
1379
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1380
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1381
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1382
			if ($globalDebug) echo "Gunzip...";
1383
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1384
			if ($globalDebug) echo "Add to DB...";
1385
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1386
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1387
		if ($error != '') {
1388
			return $error;
1389
		} elseif ($globalDebug) echo "Done\n";
1390
		return '';
1391
	}
1392
	public static function update_skyteam() {
1393
		global $tmp_dir, $globalDebug;
1394
		$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...
1395
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1396
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1397
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1398
			if ($globalDebug) echo "Gunzip...";
1399
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1400
			if ($globalDebug) echo "Add to DB...";
1401
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1402
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1403
		if ($error != '') {
1404
			return $error;
1405
		} elseif ($globalDebug) echo "Done\n";
1406
		return '';
1407
	}
1408
	public static function update_ModeS() {
1409
		global $tmp_dir, $globalDebug;
1410
/*
1411
		if ($globalDebug) echo "Modes : Download...";
1412
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1413
		if ($globalDebug) echo "Unzip...";
1414
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1415
		if ($globalDebug) echo "Add to DB...";
1416
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1417
		if ($error != true) {
1418
			echo $error;
1419
			exit;
1420
		} elseif ($globalDebug) echo "Done\n";
1421
*/
1422
		if ($globalDebug) echo "Modes : Download...";
1423
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1424
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1425
1426
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1427
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1428
			if ($globalDebug) echo "Unzip...";
1429
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1430
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1431
			if ($globalDebug) echo "Add to DB...";
1432
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1433
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1434
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1435
		if ($error != '') {
1436
			return $error;
1437
		} elseif ($globalDebug) echo "Done\n";
1438
		return '';
1439
	}
1440
1441
	public static function update_ModeS_flarm() {
1442
		global $tmp_dir, $globalDebug;
1443
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1444
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1445
		if (file_exists($tmp_dir.'data.fln')) {
1446
			if ($globalDebug) echo "Add to DB...";
1447
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1448
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1449
		if ($error != '') {
1450
			return $error;
1451
		} elseif ($globalDebug) echo "Done\n";
1452
		return '';
1453
	}
1454
1455
	public static function update_ModeS_ogn() {
1456
		global $tmp_dir, $globalDebug;
1457
		if ($globalDebug) echo "Modes OGN: Download...";
1458
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1459
		if (file_exists($tmp_dir.'ogn.csv')) {
1460
			if ($globalDebug) echo "Add to DB...";
1461
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1462
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1463
		if ($error != '') {
1464
			return $error;
1465
		} elseif ($globalDebug) echo "Done\n";
1466
		return '';
1467
	}
1468
1469
	public static function update_owner() {
1470
		global $tmp_dir, $globalDebug;
1471
		
1472
		if ($globalDebug) echo "Owner France: Download...";
1473
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1474
		if (file_exists($tmp_dir.'owner_f.csv')) {
1475
			if ($globalDebug) echo "Add to DB...";
1476
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1477
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1478
		if ($error != '') {
1479
			return $error;
1480
		} elseif ($globalDebug) echo "Done\n";
1481
		
1482
		if ($globalDebug) echo "Owner Ireland: Download...";
1483
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1484
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1485
			if ($globalDebug) echo "Add to DB...";
1486
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1487
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1488
		if ($error != '') {
1489
			return $error;
1490
		} elseif ($globalDebug) echo "Done\n";
1491
		if ($globalDebug) echo "Owner Switzerland: Download...";
1492
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1493
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1494
			if ($globalDebug) echo "Add to DB...";
1495
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1496
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1497
		if ($error != '') {
1498
			return $error;
1499
		} elseif ($globalDebug) echo "Done\n";
1500
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1501
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1502
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1503
			if ($globalDebug) echo "Add to DB...";
1504
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1505
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1506
		if ($error != '') {
1507
			return $error;
1508
		} elseif ($globalDebug) echo "Done\n";
1509
		if ($globalDebug) echo "Owner Australia: Download...";
1510
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1511
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1512
			if ($globalDebug) echo "Add to DB...";
1513
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1514
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1515
		if ($error != '') {
1516
			return $error;
1517
		} elseif ($globalDebug) echo "Done\n";
1518
		if ($globalDebug) echo "Owner Austria: Download...";
1519
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1520
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1521
			if ($globalDebug) echo "Add to DB...";
1522
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1523
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1524
		if ($error != '') {
1525
			return $error;
1526
		} elseif ($globalDebug) echo "Done\n";
1527
		if ($globalDebug) echo "Owner Chile: Download...";
1528
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1529
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1530
			if ($globalDebug) echo "Add to DB...";
1531
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1532
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1533
		if ($error != '') {
1534
			return $error;
1535
		} elseif ($globalDebug) echo "Done\n";
1536
		if ($globalDebug) echo "Owner Colombia: Download...";
1537
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1538
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1539
			if ($globalDebug) echo "Add to DB...";
1540
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1541
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1542
		if ($error != '') {
1543
			return $error;
1544
		} elseif ($globalDebug) echo "Done\n";
1545
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1546
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1547
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1548
			if ($globalDebug) echo "Add to DB...";
1549
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1550
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1551
		if ($error != '') {
1552
			return $error;
1553
		} elseif ($globalDebug) echo "Done\n";
1554
		if ($globalDebug) echo "Owner Brazil: Download...";
1555
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1556
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1557
			if ($globalDebug) echo "Add to DB...";
1558
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1559
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1560
		if ($error != '') {
1561
			return $error;
1562
		} elseif ($globalDebug) echo "Done\n";
1563
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1564
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1565
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1566
			if ($globalDebug) echo "Add to DB...";
1567
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1568
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1569
		if ($error != '') {
1570
			return $error;
1571
		} elseif ($globalDebug) echo "Done\n";
1572
		if ($globalDebug) echo "Owner Croatia: Download...";
1573
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1574
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1575
			if ($globalDebug) echo "Add to DB...";
1576
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1577
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1578
		if ($error != '') {
1579
			return $error;
1580
		} elseif ($globalDebug) echo "Done\n";
1581
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1582
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1583
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1584
			if ($globalDebug) echo "Add to DB...";
1585
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1586
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1587
		if ($error != '') {
1588
			return $error;
1589
		} elseif ($globalDebug) echo "Done\n";
1590
		if ($globalDebug) echo "Owner Maldives: Download...";
1591
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1592
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1593
			if ($globalDebug) echo "Add to DB...";
1594
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1595
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1596
		if ($error != '') {
1597
			return $error;
1598
		} elseif ($globalDebug) echo "Done\n";
1599
		if ($globalDebug) echo "Owner New Zealand: Download...";
1600
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1601
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1602
			if ($globalDebug) echo "Add to DB...";
1603
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1604
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1605
		if ($error != '') {
1606
			return $error;
1607
		} elseif ($globalDebug) echo "Done\n";
1608
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1609
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1610
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1611
			if ($globalDebug) echo "Add to DB...";
1612
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1613
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1614
		if ($error != '') {
1615
			return $error;
1616
		} elseif ($globalDebug) echo "Done\n";
1617
		if ($globalDebug) echo "Owner Slovakia: Download...";
1618
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1619
		if (file_exists($tmp_dir.'owner_om.csv')) {
1620
			if ($globalDebug) echo "Add to DB...";
1621
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1622
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1623
		if ($error != '') {
1624
			return $error;
1625
		} elseif ($globalDebug) echo "Done\n";
1626
		if ($globalDebug) echo "Owner Ecuador: Download...";
1627
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1628
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1629
			if ($globalDebug) echo "Add to DB...";
1630
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1631
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1632
		if ($error != '') {
1633
			return $error;
1634
		} elseif ($globalDebug) echo "Done\n";
1635
		if ($globalDebug) echo "Owner Iceland: Download...";
1636
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1637
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1638
			if ($globalDebug) echo "Add to DB...";
1639
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1640
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1641
		if ($error != '') {
1642
			return $error;
1643
		} elseif ($globalDebug) echo "Done\n";
1644
		return '';
1645
	}
1646
1647
	public static function update_translation() {
1648
		global $tmp_dir, $globalDebug;
1649
		$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...
1650
		if ($globalDebug) echo "Translation : Download...";
1651
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1652
		if (file_exists($tmp_dir.'translation.zip')) {
1653
			if ($globalDebug) echo "Unzip...";
1654
			update_db::unzip($tmp_dir.'translation.zip');
1655
			if ($globalDebug) echo "Add to DB...";
1656
			$error = update_db::translation();
1657
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1658
		if ($error != '') {
1659
			return $error;
1660
		} elseif ($globalDebug) echo "Done\n";
1661
		return '';
1662
	}
1663
1664
	public static function update_translation_fam() {
1665
		global $tmp_dir, $globalDebug;
1666
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1667
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1668
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1669
			if ($globalDebug) echo "Gunzip...";
1670
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1671
			if ($globalDebug) echo "Add to DB...";
1672
			$error = update_db::translation_fam();
1673
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1674
		if ($error != '') {
1675
			return $error;
1676
		} elseif ($globalDebug) echo "Done\n";
1677
		return '';
1678
	}
1679
	public static function update_ModeS_fam() {
1680
		global $tmp_dir, $globalDebug;
1681
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1682
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1683
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1684
			if ($globalDebug) echo "Gunzip...";
1685
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1686
			if ($globalDebug) echo "Add to DB...";
1687
			$error = update_db::modes_fam();
1688
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1689
		if ($error != '') {
1690
			return $error;
1691
		} elseif ($globalDebug) echo "Done\n";
1692
		return '';
1693
	}
1694
	public static function update_routes_fam() {
1695
		global $tmp_dir, $globalDebug;
1696
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
1697
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
1698
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
1699
			if ($globalDebug) echo "Gunzip...";
1700
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
1701
			if ($globalDebug) echo "Add to DB...";
1702
			$error = update_db::routes_fam();
1703
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
1704
		if ($error != '') {
1705
			return $error;
1706
		} elseif ($globalDebug) echo "Done\n";
1707
		return '';
1708
	}
1709
1710
	public static function update_airspace_fam() {
1711
		global $tmp_dir, $globalDebug, $globalDBdriver;
1712
		include_once('class.create_db.php');
1713
		$error = '';
1714
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1715
		if ($globalDBdriver == 'mysql') {
1716
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1717
		} else {
1718
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1719
		}
1720
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1721
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1722
			$airspace_md5 = $airspace_md5_file[0];
1723
			if (!update_db::check_airspace_version($airspace_md5)) {
1724
				if ($globalDBdriver == 'mysql') {
1725
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1726
				} else {
1727
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1728
				}
1729
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1730
					if ($globalDebug) echo "Gunzip...";
1731
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1732
					if ($globalDebug) echo "Add to DB...";
1733
					$Connection = new Connection();
1734
					if ($Connection->tableExists('airspace')) {
1735
						$query = 'DROP TABLE airspace';
1736
						try {
1737
							$sth = $Connection->db->prepare($query);
1738
    	    	    					$sth->execute();
1739
			            		} catch(PDOException $e) {
1740
							return "error : ".$e->getMessage();
1741
		            			}
1742
		    			}
1743
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1744
					update_db::insert_airspace_version($airspace_md5);
1745
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1746
			}
1747
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1748
		if ($error != '') {
1749
			return $error;
1750
		} elseif ($globalDebug) echo "Done\n";
1751
		return '';
1752
	}
1753
1754
	public static function update_tle() {
1755
		global $tmp_dir, $globalDebug;
1756
		if ($globalDebug) echo "Download TLE : Download...";
1757
		$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',
1758
		'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',
1759
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1760
		foreach ($alltle as $filename) {
1761
			if ($globalDebug) echo "downloading ".$filename.'...';
1762
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1763
			if (file_exists($tmp_dir.$filename)) {
1764
				if ($globalDebug) echo "Add to DB ".$filename."...";
1765
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1766
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1767
			if ($error != '') {
1768
				echo $error."\n";
1769
			} elseif ($globalDebug) echo "Done\n";
1770
		}
1771
		return '';
1772
	}
1773
1774
	public static function update_models() {
1775
		global $tmp_dir, $globalDebug;
1776
		$error = '';
1777
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1778
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1779
		if (file_exists($tmp_dir.'models.md5sum')) {
1780
			if ($globalDebug) echo "Check files...\n";
1781
			$newmodelsdb = array();
1782
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1783
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1784
					$model = trim($row[2]);
1785
					$newmodelsdb[$model] = trim($row[0]);
1786
				}
1787
			}
1788
			$modelsdb = array();
1789
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1790
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1791
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1792
						$model = trim($row[2]);
1793
						$modelsdb[$model] = trim($row[0]);
1794
					}
1795
				}
1796
			}
1797
			$diff = array_diff($newmodelsdb,$modelsdb);
1798
			foreach ($diff as $key => $value) {
1799
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1800
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1801
				
1802
			}
1803
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1804
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1805
		if ($error != '') {
1806
			return $error;
1807
		} elseif ($globalDebug) echo "Done\n";
1808
		return '';
1809
	}
1810
1811
	public static function update_space_models() {
1812
		global $tmp_dir, $globalDebug;
1813
		$error = '';
1814
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1815
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1816
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1817
			if ($globalDebug) echo "Check files...\n";
1818
			$newmodelsdb = array();
1819
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1820
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1821
					$model = trim($row[2]);
1822
					$newmodelsdb[$model] = trim($row[0]);
1823
				}
1824
			}
1825
			$modelsdb = array();
1826
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1827
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1828
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1829
						$model = trim($row[2]);
1830
						$modelsdb[$model] = trim($row[0]);
1831
					}
1832
				}
1833
			}
1834
			$diff = array_diff($newmodelsdb,$modelsdb);
1835
			foreach ($diff as $key => $value) {
1836
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1837
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1838
				
1839
			}
1840
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1841
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1842
		if ($error != '') {
1843
			return $error;
1844
		} elseif ($globalDebug) echo "Done\n";
1845
		return '';
1846
	}
1847
1848
	public static function update_aircraft() {
1849
		global $tmp_dir, $globalDebug;
1850
		date_default_timezone_set('UTC');
1851
		//$error = '';
1852
		/*
1853
		if ($globalDebug) echo "Aircrafts : Download...";
1854
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1855
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1856
		//$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);
1857
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1858
//		echo strlen($data_req);
1859
		echo $data;
1860
		*/
1861
		if (file_exists($tmp_dir.'aircrafts.html')) {
1862
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1863
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1864
		    $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...
1865
		    //echo $result;
1866
		    //var_dump(str_get_html($result));
1867
		    //print_r(self::table2array($result));
1868
		}
1869
1870
	}
1871
	
1872
	public static function update_notam() {
1873
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1874
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1875
		$Common = new Common();
1876
		date_default_timezone_set('UTC');
1877
		$query = 'TRUNCATE TABLE notam';
1878
		try {
1879
			$Connection = new Connection();
1880
			$sth = $Connection->db->prepare($query);
1881
                        $sth->execute();
1882
                } catch(PDOException $e) {
1883
                        return "error : ".$e->getMessage();
1884
                }
1885
1886
		$error = '';
1887
		if ($globalDebug) echo "Notam : Download...";
1888
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1889
		if (file_exists($tmp_dir.'notam.rss')) {
1890
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1891
			foreach ($notams['channel']['item'] as $notam) {
1892
				$title = explode(':',$notam['title']);
1893
				$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...
1894
				unset($title[0]);
1895
				$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...
1896
				$description = strip_tags($notam['description'],'<pre>');
1897
				preg_match(':^(.*?)<pre>:',$description,$match);
1898
				$q = explode('/',$match[1]);
1899
				$data['fir'] = $q[0];
1900
				$data['code'] = $q[1];
1901
				$ifrvfr = $q[2];
1902
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1903
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1904
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1905
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1906
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1907
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1908
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1909
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1910
				//$data['scope'] = $q[4];
1911
				$data['lower_limit'] = $q[5];
1912
				$data['upper_limit'] = $q[6];
1913
				$latlonrad = $q[7];
1914
				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...
1915
				$latitude = $Common->convertDec($las,'latitude');
1916
				$longitude = $Common->convertDec($lns,'longitude');
1917
				if ($lac == 'S') $latitude = '-'.$latitude;
1918
				if ($lnc == 'W') $longitude = '-'.$longitude;
1919
				$data['center_latitude'] = $latitude;
1920
				$data['center_longitude'] = $longitude;
1921
				$data['radius'] = intval($radius);
1922
				
1923
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1924
				$data['text'] = $match[1];
1925
				preg_match(':</pre>(.*?)$:',$description,$match);
1926
				$fromto = $match[1];
1927
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1928
				$fromall = trim($match[1]);
1929
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1930
				$from = trim($match[1]);
1931
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1932
				preg_match('#TO:(.*?)$#',$fromto,$match);
1933
				$toall = trim($match[1]);
1934
				if (!preg_match(':Permanent:',$toall)) {
1935
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1936
					$to = trim($match[1]);
1937
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1938
					$data['permanent'] = 0;
1939
				} else {
1940
				    $data['date_end'] = NULL;
1941
				    $data['permanent'] = 1;
1942
				}
1943
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1944
				$NOTAM = new NOTAM();
1945
				$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']);
1946
				unset($data);
1947
			} 
1948
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1949
		if ($error != '') {
1950
			return $error;
1951
		} elseif ($globalDebug) echo "Done\n";
1952
		return '';
1953
	}
1954
	
1955
	public static function create_airspace() {
1956
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
1957
		$Connection = new Connection();
1958
		if ($Connection->tableExists('airspace')) {
1959
			if ($globalDBdriver == 'mysql') {
1960
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
1961
			} else {
1962
				$query = 'DROP TABLE airspace';
1963
			}
1964
			try {
1965
				$Connection = new Connection();
1966
				$sth = $Connection->db->prepare($query);
1967
				$sth->execute();
1968
			} catch(PDOException $e) {
1969
				return "error : ".$e->getMessage();
1970
			}
1971
		}
1972
		$Common = new Common();
1973
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
1974
		$airspace_json = json_decode($airspace_lst,true);
1975
		foreach ($airspace_json['records'] as $airspace) {
1976
			if ($globalDebug) echo $airspace['name']."...\n";
1977
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
1978
			if (file_exists($tmp_dir.$airspace['name'])) {
1979
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
1980
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
1981
				if ($globalDBdriver == 'mysql') {
1982
					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'].'"');
1983
				} else {
1984
					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'].'"');
1985
				}
1986
			}
1987
		}
1988
	}
1989
	
1990
	public static function check_last_update() {
1991
		global $globalDBdriver;
1992
		if ($globalDBdriver == 'mysql') {
1993
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
1994
		} else {
1995
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1996
		}
1997
		try {
1998
			$Connection = new Connection();
1999
			$sth = $Connection->db->prepare($query);
2000
                        $sth->execute();
2001
                } catch(PDOException $e) {
2002
                        return "error : ".$e->getMessage();
2003
                }
2004
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2005
                if ($row['nb'] > 0) return false;
2006
                else return true;
2007
	}
2008
2009
	public static function insert_last_update() {
2010
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2011
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2012
		try {
2013
			$Connection = new Connection();
2014
			$sth = $Connection->db->prepare($query);
2015
                        $sth->execute();
2016
                } catch(PDOException $e) {
2017
                        return "error : ".$e->getMessage();
2018
                }
2019
	}
2020
2021
	public static function check_airspace_version($version) {
2022
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2023
		try {
2024
			$Connection = new Connection();
2025
			$sth = $Connection->db->prepare($query);
2026
                        $sth->execute(array(':version' => $version));
2027
                } catch(PDOException $e) {
2028
                        return "error : ".$e->getMessage();
2029
                }
2030
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2031
                if ($row['nb'] > 0) return true;
2032
                else return false;
2033
	}
2034
2035
2036
	public static function insert_airspace_version($version) {
2037
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2038
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2039
		try {
2040
			$Connection = new Connection();
2041
			$sth = $Connection->db->prepare($query);
2042
                        $sth->execute(array(':version' => $version));
2043
                } catch(PDOException $e) {
2044
                        return "error : ".$e->getMessage();
2045
                }
2046
	}
2047
2048
	public static function check_last_notam_update() {
2049
		global $globalDBdriver;
2050
		if ($globalDBdriver == 'mysql') {
2051
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2052
		} else {
2053
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2054
		}
2055
		try {
2056
			$Connection = new Connection();
2057
			$sth = $Connection->db->prepare($query);
2058
                        $sth->execute();
2059
                } catch(PDOException $e) {
2060
                        return "error : ".$e->getMessage();
2061
                }
2062
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2063
                if ($row['nb'] > 0) return false;
2064
                else return true;
2065
	}
2066
2067
	public static function insert_last_notam_update() {
2068
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2069
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2070
		try {
2071
			$Connection = new Connection();
2072
			$sth = $Connection->db->prepare($query);
2073
                        $sth->execute();
2074
                } catch(PDOException $e) {
2075
                        return "error : ".$e->getMessage();
2076
                }
2077
	}
2078
	public static function check_last_airspace_update() {
2079
		global $globalDBdriver;
2080
		if ($globalDBdriver == 'mysql') {
2081
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2082
		} else {
2083
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2084
		}
2085
		try {
2086
			$Connection = new Connection();
2087
			$sth = $Connection->db->prepare($query);
2088
                        $sth->execute();
2089
                } catch(PDOException $e) {
2090
                        return "error : ".$e->getMessage();
2091
                }
2092
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2093
                if ($row['nb'] > 0) return false;
2094
                else return true;
2095
	}
2096
2097
	public static function insert_last_airspace_update() {
2098
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2099
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2100
		try {
2101
			$Connection = new Connection();
2102
			$sth = $Connection->db->prepare($query);
2103
                        $sth->execute();
2104
                } catch(PDOException $e) {
2105
                        return "error : ".$e->getMessage();
2106
                }
2107
	}
2108
2109
	public static function check_last_owner_update() {
2110
		global $globalDBdriver;
2111
		if ($globalDBdriver == 'mysql') {
2112
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2113
		} else {
2114
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2115
		}
2116
		try {
2117
			$Connection = new Connection();
2118
			$sth = $Connection->db->prepare($query);
2119
                        $sth->execute();
2120
                } catch(PDOException $e) {
2121
                        return "error : ".$e->getMessage();
2122
                }
2123
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2124
                if ($row['nb'] > 0) return false;
2125
                else return true;
2126
	}
2127
2128
	public static function insert_last_owner_update() {
2129
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2130
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2131
		try {
2132
			$Connection = new Connection();
2133
			$sth = $Connection->db->prepare($query);
2134
                        $sth->execute();
2135
                } catch(PDOException $e) {
2136
                        return "error : ".$e->getMessage();
2137
                }
2138
	}
2139
	public static function check_last_schedules_update() {
2140
		global $globalDBdriver;
2141
		if ($globalDBdriver == 'mysql') {
2142
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2143
		} else {
2144
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2145
		}
2146
		try {
2147
			$Connection = new Connection();
2148
			$sth = $Connection->db->prepare($query);
2149
                        $sth->execute();
2150
                } catch(PDOException $e) {
2151
                        return "error : ".$e->getMessage();
2152
                }
2153
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2154
                if ($row['nb'] > 0) return false;
2155
                else return true;
2156
	}
2157
2158
	public static function insert_last_schedules_update() {
2159
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2160
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2161
		try {
2162
			$Connection = new Connection();
2163
			$sth = $Connection->db->prepare($query);
2164
                        $sth->execute();
2165
                } catch(PDOException $e) {
2166
                        return "error : ".$e->getMessage();
2167
                }
2168
	}
2169
	public static function check_last_tle_update() {
2170
		global $globalDBdriver;
2171
		if ($globalDBdriver == 'mysql') {
2172
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2173
		} else {
2174
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2175
		}
2176
		try {
2177
			$Connection = new Connection();
2178
			$sth = $Connection->db->prepare($query);
2179
                        $sth->execute();
2180
                } catch(PDOException $e) {
2181
                        return "error : ".$e->getMessage();
2182
                }
2183
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2184
                if ($row['nb'] > 0) return false;
2185
                else return true;
2186
	}
2187
2188
	public static function insert_last_tle_update() {
2189
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2190
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2191
		try {
2192
			$Connection = new Connection();
2193
			$sth = $Connection->db->prepare($query);
2194
                        $sth->execute();
2195
                } catch(PDOException $e) {
2196
                        return "error : ".$e->getMessage();
2197
                }
2198
	}
2199
	public static function delete_duplicatemodes() {
2200
		global $globalDBdriver;
2201
		if ($globalDBdriver == 'mysql') {
2202
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.AircraftID < b.AircraftID AND a.Source != 'ACARS'";
2203
		} else {
2204
			$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'";
2205
		}
2206
		try {
2207
			$Connection = new Connection();
2208
			$sth = $Connection->db->prepare($query);
2209
                        $sth->execute();
2210
                } catch(PDOException $e) {
2211
                        return "error : ".$e->getMessage();
2212
                }
2213
	}
2214
	
2215
	public static function update_all() {
2216
		global $globalMasterServer;
2217
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2218
			//echo update_db::update_routes();
2219
			echo update_db::update_routes_fam();
2220
			echo update_db::update_translation();
2221
			echo update_db::update_translation_fam();
2222
			echo update_db::update_notam_fam();
2223
			//echo update_db::update_ModeS();
2224
			echo update_db::update_ModeS_fam();
2225
			echo update_db::update_ModeS_flarm();
2226
			echo update_db::update_ModeS_ogn();
2227
			echo update_db::delete_duplicatemodes();
2228
		}
2229
	}
2230
}
2231
2232
//echo update_db::update_airports();
2233
//echo update_db::translation();
2234
//echo update_db::update_waypoints();
2235
//echo update_db::update_airspace();
2236
//echo update_db::update_notam();
2237
//echo update_db::update_ivao();
2238
//echo update_db::update_ModeS_flarm();
2239
//echo update_db::update_ModeS_ogn();
2240
//echo update_db::update_aircraft();
2241
//$update_db = new update_db();
2242
//echo $update_db->update_owner();
2243
//update_db::update_translation_fam();
2244
//echo update_db::update_routes();
2245
//update_db::update_models();
2246
//echo $update_db::update_skyteam();
2247
//echo $update_db::update_tle();
2248
//echo update_db::update_notam_fam();
2249
//echo update_db::create_airspace();
2250
//echo update_db::update_ModeS();
2251
//echo update_db::update_ModeS_fam();
2252
//echo update_db::update_routes_fam();
2253
?>
2254