Completed
Push — master ( 144f1c...4c4fd5 )
by Yannick
11:39
created

update_db::update_all()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 0
dl 0
loc 12
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 tle($filename,$tletype) {
948
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
949
		global $tmp_dir, $globalTransaction;
950
		//$Spotter = new Spotter();
951
		
952
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
953
		try {
954
			$Connection = new Connection();
955
			$sth = $Connection->db->prepare($query);
956
                        $sth->execute(array(':source' => $filename));
957
                } catch(PDOException $e) {
958
                        return "error : ".$e->getMessage();
959
                }
960
		
961
		$Connection = new Connection();
962
		if (($handle = fopen($filename, 'r')) !== FALSE)
963
		{
964
			$i = 0;
965
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
966
			//$Connection->db->beginTransaction();
967
			$dbdata = array();
968
			while (($data = fgets($handle, 1000)) !== FALSE)
969
			{
970
				if ($i == 0) {
971
					$dbdata['name'] = trim($data);
972
					$i++;
973
				} elseif ($i == 1) {
974
					$dbdata['tle1'] = trim($data);
975
					$i++;
976
				} elseif ($i == 2) {
977
					$dbdata['tle2'] = trim($data);
978
					//print_r($dbdata);
979
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
980
					try {
981
						$sth = $Connection->db->prepare($query);
982
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
983
					} catch(PDOException $e) {
984
						return "error : ".$e->getMessage();
985
					}
986
987
					$i = 0;
988
				}
989
			}
990
			fclose($handle);
991
			//$Connection->db->commit();
992
		}
993
		return '';
994
        }
995
996
	/**
997
        * Convert a HTML table to an array
998
        * @param String $data HTML page
999
        * @return Array array of the tables in HTML page
1000
        */
1001
        private static function table2array($data) {
1002
                $html = str_get_html($data);
1003
                $tabledata=array();
1004
                foreach($html->find('tr') as $element)
1005
                {
1006
                        $td = array();
1007
                        foreach( $element->find('th') as $row)
1008
                        {
1009
                                $td [] = trim($row->plaintext);
1010
                        }
1011
                        $td=array_filter($td);
1012
                        $tabledata[] = $td;
1013
1014
                        $td = array();
1015
                        $tdi = array();
1016
                        foreach( $element->find('td') as $row)
1017
                        {
1018
                                $td [] = trim($row->plaintext);
1019
                                $tdi [] = trim($row->innertext);
1020
                        }
1021
                        $td=array_filter($td);
1022
                        $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...
1023
                    //    $tabledata[]=array_merge($td,$tdi);
1024
                        $tabledata[]=$td;
1025
                }
1026
                return(array_filter($tabledata));
1027
        }
1028
1029
       /**
1030
        * Get data from form result
1031
        * @param String $url form URL
1032
        * @return String the result
1033
        */
1034
        private static function getData($url) {
1035
                $ch = curl_init();
1036
                curl_setopt($ch, CURLOPT_URL, $url);
1037
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1038
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1039
                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');
1040
                return curl_exec($ch);
1041
        }
1042
/*
1043
	public static function waypoints() {
1044
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1045
		$table = update_db::table2array($data);
1046
//		print_r($table);
1047
		$query = 'TRUNCATE TABLE waypoints';
1048
		try {
1049
			$Connection = new Connection();
1050
			$sth = $Connection->db->prepare($query);
1051
                        $sth->execute();
1052
                } catch(PDOException $e) {
1053
                        return "error : ".$e->getMessage();
1054
                }
1055
1056
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1057
		$Connection = new Connection();
1058
		$sth_dest = $Connection->db->prepare($query_dest);
1059
		$Connection->db->beginTransaction();
1060
                foreach ($table as $row) {
1061
            		if ($row[0] != 'Ident') {
1062
				$ident = $row[0];
1063
				$latitude = $row[2];
1064
				$longitude = $row[3];
1065
				$control = $row[4];
1066
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1067
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1068
				try {
1069
					$sth_dest->execute($query_dest_values);
1070
				} catch(PDOException $e) {
1071
					return "error : ".$e->getMessage();
1072
				}
1073
			}
1074
                }
1075
		$Connection->db->commit();
1076
1077
	}
1078
*/
1079
	public static function waypoints($filename) {
1080
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1081
		global $tmp_dir, $globalTransaction;
1082
		//$Spotter = new Spotter();
1083
		//$out_file = $tmp_dir.'translation.zip';
1084
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1085
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1086
		$Connection = new Connection();
1087
		//update_db::unzip($out_file);
1088
		$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...
1089
		$delimiter = ' ';
1090
		if (($handle = fopen($filename, 'r')) !== FALSE)
1091
		{
1092
			$i = 0;
1093
			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...
1094
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1095
			{
1096
				$i++;
1097
				if($i > 3 && count($row) > 2) {
1098
					$data = array_values(array_filter($row));
1099
					$cntdata = count($data);
1100
					if ($cntdata > 10) {
1101
						$value = $data[9];
1102
						
1103
						for ($i =10;$i < $cntdata;$i++) {
1104
							$value .= ' '.$data[$i];
1105
						}
1106
						$data[9] = $value;
1107
					}
1108
					//print_r($data);
1109
					if (count($data) > 9) {
1110
						$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)';
1111
						try {
1112
							$sth = $Connection->db->prepare($query);
1113
							$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]));
1114
						} catch(PDOException $e) {
1115
							return "error : ".$e->getMessage();
1116
						}
1117
					}
1118
				}
1119
			}
1120
			fclose($handle);
1121
			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...
1122
		}
1123
		return '';
1124
        }
1125
1126
	public static function ivao_airlines($filename) {
1127
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1128
		global $tmp_dir, $globalTransaction;
1129
		//$query = 'TRUNCATE TABLE airlines';
1130
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1131
		try {
1132
			$Connection = new Connection();
1133
			$sth = $Connection->db->prepare($query);
1134
                        $sth->execute();
1135
                } catch(PDOException $e) {
1136
                        return "error : ".$e->getMessage();
1137
                }
1138
1139
		$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...
1140
		$delimiter = ':';
1141
		$Connection = new Connection();
1142
		if (($handle = fopen($filename, 'r')) !== FALSE)
1143
		{
1144
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
1145
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1146
			{
1147
				if(count($row) > 1) {
1148
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1149
					try {
1150
						$sth = $Connection->db->prepare($query);
1151
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1152
					} catch(PDOException $e) {
1153
						return "error : ".$e->getMessage();
1154
					}
1155
				}
1156
			}
1157
			fclose($handle);
1158
			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...
1159
		}
1160
		return '';
1161
        }
1162
	
1163
	public static function update_airspace() {
1164
		global $tmp_dir, $globalDBdriver;
1165
		include_once('class.create_db.php');
1166
		$Connection = new Connection();
1167
		if ($Connection->tableExists('airspace')) {
1168
			$query = 'DROP TABLE airspace';
1169
			try {
1170
				$sth = $Connection->db->prepare($query);
1171
                    		$sth->execute();
1172
	                } catch(PDOException $e) {
1173
				return "error : ".$e->getMessage();
1174
	                }
1175
	        }
1176
1177
1178
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1179
		else {
1180
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1181
			$query = "CREATE EXTENSION postgis";
1182
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1183
			try {
1184
				$sth = $Connection->db->prepare($query);
1185
				$sth->execute();
1186
			} catch(PDOException $e) {
1187
				return "error : ".$e->getMessage();
1188
			}
1189
		}
1190
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1191
		return $error;
1192
	}
1193
1194
	public static function update_notam_fam() {
1195
		global $tmp_dir, $globalDebug;
1196
		include_once('class.create_db.php');
1197
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1198
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1199
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1200
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1201
			if ($globalDebug) echo "Gunzip...";
1202
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1203
			if ($globalDebug) echo "Add to DB...";
1204
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1205
			$NOTAM = new NOTAM();
1206
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1207
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1208
		if ($error != '') {
1209
			return $error;
0 ignored issues
show
Bug introduced by
The variable $error 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...
1210
		} elseif ($globalDebug) echo "Done\n";
1211
		return '';
1212
	}
1213
1214
	public static function update_vatsim() {
1215
		global $tmp_dir;
1216
		include_once('class.create_db.php');
1217
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1218
		return $error;
1219
	}
1220
	
1221
	public static function update_countries() {
1222
		global $tmp_dir, $globalDBdriver;
1223
		include_once('class.create_db.php');
1224
		$Connection = new Connection();
1225
		if ($Connection->tableExists('countries')) {
1226
			$query = 'DROP TABLE countries';
1227
			try {
1228
				$sth = $Connection->db->prepare($query);
1229
            	        	$sth->execute();
1230
	                } catch(PDOException $e) {
1231
    	                	echo "error : ".$e->getMessage();
1232
	                }
1233
		}
1234
		if ($globalDBdriver == 'mysql') {
1235
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1236
		} else {
1237
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1238
		}
1239
		$error = create_db::import_file($tmp_dir.'countries.sql');
1240
		return $error;
1241
	}
1242
1243
	
1244
	public static function update_waypoints() {
1245
		global $tmp_dir;
1246
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1247
//		update_db::unzip($tmp_dir.'AptNav.zip');
1248
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1249
//		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');
1250
		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');
1251
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1252
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1253
		return $error;
1254
	}
1255
1256
	public static function update_ivao() {
1257
		global $tmp_dir, $globalDebug;
1258
		$Common = new Common();
1259
		$error = '';
1260
		//Direct download forbidden
1261
		//if ($globalDebug) echo "IVAO : Download...";
1262
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1263
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1264
			if ($globalDebug) echo "Unzip...";
1265
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1266
			if ($globalDebug) echo "Add to DB...";
1267
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1268
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1269
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1270
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1271
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1272
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1273
		if ($error != '') {
1274
			return $error;
1275
		} elseif ($globalDebug) echo "Done\n";
1276
		return '';
1277
	}
1278
1279
	public static function update_routes() {
1280
		global $tmp_dir, $globalDebug;
1281
		$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...
1282
		if ($globalDebug) echo "Routes : Download...";
1283
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1284
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1285
			if ($globalDebug) echo "Gunzip...";
1286
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1287
			if ($globalDebug) echo "Add to DB...";
1288
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1289
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1290
		if ($error != '') {
1291
			return $error;
1292
		} elseif ($globalDebug) echo "Done\n";
1293
		return '';
1294
	}
1295
	public static function update_oneworld() {
1296
		global $tmp_dir, $globalDebug;
1297
		$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...
1298
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1299
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1300
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1301
			if ($globalDebug) echo "Gunzip...";
1302
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1303
			if ($globalDebug) echo "Add to DB...";
1304
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1305
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1306
		if ($error != '') {
1307
			return $error;
1308
		} elseif ($globalDebug) echo "Done\n";
1309
		return '';
1310
	}
1311
	public static function update_skyteam() {
1312
		global $tmp_dir, $globalDebug;
1313
		$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...
1314
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1315
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1316
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1317
			if ($globalDebug) echo "Gunzip...";
1318
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1319
			if ($globalDebug) echo "Add to DB...";
1320
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1321
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1322
		if ($error != '') {
1323
			return $error;
1324
		} elseif ($globalDebug) echo "Done\n";
1325
		return '';
1326
	}
1327
	public static function update_ModeS() {
1328
		global $tmp_dir, $globalDebug;
1329
/*
1330
		if ($globalDebug) echo "Modes : Download...";
1331
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1332
		if ($globalDebug) echo "Unzip...";
1333
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1334
		if ($globalDebug) echo "Add to DB...";
1335
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1336
		if ($error != true) {
1337
			echo $error;
1338
			exit;
1339
		} elseif ($globalDebug) echo "Done\n";
1340
*/
1341
		if ($globalDebug) echo "Modes : Download...";
1342
		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1343
		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1344
			if ($globalDebug) echo "Unzip...";
1345
			update_db::unzip($tmp_dir.'basestation_latest.zip');
1346
			if ($globalDebug) echo "Add to DB...";
1347
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1348
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1349
		if ($error != '') {
1350
			return $error;
1351
		} elseif ($globalDebug) echo "Done\n";
1352
		return '';
1353
	}
1354
1355
	public static function update_ModeS_flarm() {
1356
		global $tmp_dir, $globalDebug;
1357
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1358
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1359
		if (file_exists($tmp_dir.'data.fln')) {
1360
			if ($globalDebug) echo "Add to DB...";
1361
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1362
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1363
		if ($error != '') {
1364
			return $error;
1365
		} elseif ($globalDebug) echo "Done\n";
1366
		return '';
1367
	}
1368
1369
	public static function update_ModeS_ogn() {
1370
		global $tmp_dir, $globalDebug;
1371
		if ($globalDebug) echo "Modes OGN: Download...";
1372
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1373
		if (file_exists($tmp_dir.'ogn.csv')) {
1374
			if ($globalDebug) echo "Add to DB...";
1375
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1376
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1377
		if ($error != '') {
1378
			return $error;
1379
		} elseif ($globalDebug) echo "Done\n";
1380
		return '';
1381
	}
1382
1383
	public static function update_owner() {
1384
		global $tmp_dir, $globalDebug;
1385
		
1386
		if ($globalDebug) echo "Owner France: Download...";
1387
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1388
		if (file_exists($tmp_dir.'owner_f.csv')) {
1389
			if ($globalDebug) echo "Add to DB...";
1390
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1391
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1392
		if ($error != '') {
1393
			return $error;
1394
		} elseif ($globalDebug) echo "Done\n";
1395
		
1396
		if ($globalDebug) echo "Owner Ireland: Download...";
1397
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1398
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1399
			if ($globalDebug) echo "Add to DB...";
1400
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1401
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1402
		if ($error != '') {
1403
			return $error;
1404
		} elseif ($globalDebug) echo "Done\n";
1405
		if ($globalDebug) echo "Owner Switzerland: Download...";
1406
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1407
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1408
			if ($globalDebug) echo "Add to DB...";
1409
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1410
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1411
		if ($error != '') {
1412
			return $error;
1413
		} elseif ($globalDebug) echo "Done\n";
1414
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1415
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1416
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1417
			if ($globalDebug) echo "Add to DB...";
1418
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1419
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1420
		if ($error != '') {
1421
			return $error;
1422
		} elseif ($globalDebug) echo "Done\n";
1423
		if ($globalDebug) echo "Owner Australia: Download...";
1424
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1425
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1426
			if ($globalDebug) echo "Add to DB...";
1427
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1428
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1429
		if ($error != '') {
1430
			return $error;
1431
		} elseif ($globalDebug) echo "Done\n";
1432
		if ($globalDebug) echo "Owner Austria: Download...";
1433
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1434
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1435
			if ($globalDebug) echo "Add to DB...";
1436
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1437
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1438
		if ($error != '') {
1439
			return $error;
1440
		} elseif ($globalDebug) echo "Done\n";
1441
		if ($globalDebug) echo "Owner Chile: Download...";
1442
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1443
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1444
			if ($globalDebug) echo "Add to DB...";
1445
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1446
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1447
		if ($error != '') {
1448
			return $error;
1449
		} elseif ($globalDebug) echo "Done\n";
1450
		if ($globalDebug) echo "Owner Colombia: Download...";
1451
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1452
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1453
			if ($globalDebug) echo "Add to DB...";
1454
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1455
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1456
		if ($error != '') {
1457
			return $error;
1458
		} elseif ($globalDebug) echo "Done\n";
1459
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1460
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1461
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1462
			if ($globalDebug) echo "Add to DB...";
1463
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1464
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1465
		if ($error != '') {
1466
			return $error;
1467
		} elseif ($globalDebug) echo "Done\n";
1468
		if ($globalDebug) echo "Owner Brazil: Download...";
1469
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1470
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1471
			if ($globalDebug) echo "Add to DB...";
1472
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1473
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1474
		if ($error != '') {
1475
			return $error;
1476
		} elseif ($globalDebug) echo "Done\n";
1477
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1478
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1479
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1480
			if ($globalDebug) echo "Add to DB...";
1481
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1482
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1483
		if ($error != '') {
1484
			return $error;
1485
		} elseif ($globalDebug) echo "Done\n";
1486
		if ($globalDebug) echo "Owner Croatia: Download...";
1487
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1488
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1489
			if ($globalDebug) echo "Add to DB...";
1490
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1491
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1492
		if ($error != '') {
1493
			return $error;
1494
		} elseif ($globalDebug) echo "Done\n";
1495
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1496
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1497
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1498
			if ($globalDebug) echo "Add to DB...";
1499
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1500
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1501
		if ($error != '') {
1502
			return $error;
1503
		} elseif ($globalDebug) echo "Done\n";
1504
		if ($globalDebug) echo "Owner Maldives: Download...";
1505
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1506
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1507
			if ($globalDebug) echo "Add to DB...";
1508
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1509
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1510
		if ($error != '') {
1511
			return $error;
1512
		} elseif ($globalDebug) echo "Done\n";
1513
		if ($globalDebug) echo "Owner New Zealand: Download...";
1514
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1515
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1516
			if ($globalDebug) echo "Add to DB...";
1517
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1518
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1519
		if ($error != '') {
1520
			return $error;
1521
		} elseif ($globalDebug) echo "Done\n";
1522
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1523
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1524
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1525
			if ($globalDebug) echo "Add to DB...";
1526
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1527
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1528
		if ($error != '') {
1529
			return $error;
1530
		} elseif ($globalDebug) echo "Done\n";
1531
		if ($globalDebug) echo "Owner Slovakia: Download...";
1532
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1533
		if (file_exists($tmp_dir.'owner_om.csv')) {
1534
			if ($globalDebug) echo "Add to DB...";
1535
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1536
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1537
		if ($error != '') {
1538
			return $error;
1539
		} elseif ($globalDebug) echo "Done\n";
1540
		if ($globalDebug) echo "Owner Ecuador: Download...";
1541
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1542
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1543
			if ($globalDebug) echo "Add to DB...";
1544
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1545
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1546
		if ($error != '') {
1547
			return $error;
1548
		} elseif ($globalDebug) echo "Done\n";
1549
		if ($globalDebug) echo "Owner Iceland: Download...";
1550
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1551
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1552
			if ($globalDebug) echo "Add to DB...";
1553
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1554
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1555
		if ($error != '') {
1556
			return $error;
1557
		} elseif ($globalDebug) echo "Done\n";
1558
		return '';
1559
	}
1560
1561
	public static function update_translation() {
1562
		global $tmp_dir, $globalDebug;
1563
		$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...
1564
		if ($globalDebug) echo "Translation : Download...";
1565
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1566
		if (file_exists($tmp_dir.'translation.zip')) {
1567
			if ($globalDebug) echo "Unzip...";
1568
			update_db::unzip($tmp_dir.'translation.zip');
1569
			if ($globalDebug) echo "Add to DB...";
1570
			$error = update_db::translation();
1571
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1572
		if ($error != '') {
1573
			return $error;
1574
		} elseif ($globalDebug) echo "Done\n";
1575
		return '';
1576
	}
1577
1578
	public static function update_translation_fam() {
1579
		global $tmp_dir, $globalDebug;
1580
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1581
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1582
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1583
			if ($globalDebug) echo "Gunzip...";
1584
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1585
			if ($globalDebug) echo "Add to DB...";
1586
			$error = update_db::translation_fam();
1587
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1588
		if ($error != '') {
1589
			return $error;
1590
		} elseif ($globalDebug) echo "Done\n";
1591
		return '';
1592
	}
1593
1594
	public static function update_tle() {
1595
		global $tmp_dir, $globalDebug;
1596
		if ($globalDebug) echo "Download TLE : Download...";
1597
		$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',
1598
		'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',
1599
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1600
		foreach ($alltle as $filename) {
1601
			if ($globalDebug) echo "downloading ".$filename.'...';
1602
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1603
			if (file_exists($tmp_dir.$filename)) {
1604
				if ($globalDebug) echo "Add to DB ".$filename."...";
1605
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1606
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1607
			if ($error != '') {
1608
				echo $error."\n";
1609
			} elseif ($globalDebug) echo "Done\n";
1610
		}
1611
		return '';
1612
	}
1613
1614
	public static function update_models() {
1615
		global $tmp_dir, $globalDebug;
1616
		$error = '';
1617
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1618
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1619
		if (file_exists($tmp_dir.'models.md5sum')) {
1620
			if ($globalDebug) echo "Check files...\n";
1621
			$newmodelsdb = array();
1622
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1623
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1624
					$model = trim($row[2]);
1625
					$newmodelsdb[$model] = trim($row[0]);
1626
				}
1627
			}
1628
			$modelsdb = array();
1629
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1630
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1631
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1632
						$model = trim($row[2]);
1633
						$modelsdb[$model] = trim($row[0]);
1634
					}
1635
				}
1636
			}
1637
			$diff = array_diff($newmodelsdb,$modelsdb);
1638
			foreach ($diff as $key => $value) {
1639
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1640
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1641
				
1642
			}
1643
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1644
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1645
		if ($error != '') {
1646
			return $error;
1647
		} elseif ($globalDebug) echo "Done\n";
1648
		return '';
1649
	}
1650
1651
	public static function update_space_models() {
1652
		global $tmp_dir, $globalDebug;
1653
		$error = '';
1654
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1655
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1656
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1657
			if ($globalDebug) echo "Check files...\n";
1658
			$newmodelsdb = array();
1659
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1660
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1661
					$model = trim($row[2]);
1662
					$newmodelsdb[$model] = trim($row[0]);
1663
				}
1664
			}
1665
			$modelsdb = array();
1666
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1667
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1668
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1669
						$model = trim($row[2]);
1670
						$modelsdb[$model] = trim($row[0]);
1671
					}
1672
				}
1673
			}
1674
			$diff = array_diff($newmodelsdb,$modelsdb);
1675
			foreach ($diff as $key => $value) {
1676
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1677
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1678
				
1679
			}
1680
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1681
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1682
		if ($error != '') {
1683
			return $error;
1684
		} elseif ($globalDebug) echo "Done\n";
1685
		return '';
1686
	}
1687
1688
	public static function update_aircraft() {
1689
		global $tmp_dir, $globalDebug;
1690
		date_default_timezone_set('UTC');
1691
		//$error = '';
1692
		/*
1693
		if ($globalDebug) echo "Aircrafts : Download...";
1694
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1695
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1696
		//$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);
1697
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1698
//		echo strlen($data_req);
1699
		echo $data;
1700
		*/
1701
		if (file_exists($tmp_dir.'aircrafts.html')) {
1702
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1703
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1704
		    $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...
1705
		    //echo $result;
1706
		    //var_dump(str_get_html($result));
1707
		    //print_r(self::table2array($result));
1708
		}
1709
1710
	}
1711
	
1712
	public static function update_notam() {
1713
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1714
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1715
		$Common = new Common();
1716
		date_default_timezone_set('UTC');
1717
		$query = 'TRUNCATE TABLE notam';
1718
		try {
1719
			$Connection = new Connection();
1720
			$sth = $Connection->db->prepare($query);
1721
                        $sth->execute();
1722
                } catch(PDOException $e) {
1723
                        return "error : ".$e->getMessage();
1724
                }
1725
1726
		$error = '';
1727
		if ($globalDebug) echo "Notam : Download...";
1728
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1729
		if (file_exists($tmp_dir.'notam.rss')) {
1730
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1731
			foreach ($notams['channel']['item'] as $notam) {
1732
				$title = explode(':',$notam['title']);
1733
				$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...
1734
				unset($title[0]);
1735
				$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...
1736
				$description = strip_tags($notam['description'],'<pre>');
1737
				preg_match(':^(.*?)<pre>:',$description,$match);
1738
				$q = explode('/',$match[1]);
1739
				$data['fir'] = $q[0];
1740
				$data['code'] = $q[1];
1741
				$ifrvfr = $q[2];
1742
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1743
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1744
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1745
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1746
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1747
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1748
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1749
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1750
				//$data['scope'] = $q[4];
1751
				$data['lower_limit'] = $q[5];
1752
				$data['upper_limit'] = $q[6];
1753
				$latlonrad = $q[7];
1754
				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...
1755
				$latitude = $Common->convertDec($las,'latitude');
1756
				$longitude = $Common->convertDec($lns,'longitude');
1757
				if ($lac == 'S') $latitude = '-'.$latitude;
1758
				if ($lnc == 'W') $longitude = '-'.$longitude;
1759
				$data['center_latitude'] = $latitude;
1760
				$data['center_longitude'] = $longitude;
1761
				$data['radius'] = intval($radius);
1762
				
1763
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1764
				$data['text'] = $match[1];
1765
				preg_match(':</pre>(.*?)$:',$description,$match);
1766
				$fromto = $match[1];
1767
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1768
				$fromall = trim($match[1]);
1769
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1770
				$from = trim($match[1]);
1771
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1772
				preg_match('#TO:(.*?)$#',$fromto,$match);
1773
				$toall = trim($match[1]);
1774
				if (!preg_match(':Permanent:',$toall)) {
1775
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1776
					$to = trim($match[1]);
1777
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1778
					$data['permanent'] = 0;
1779
				} else {
1780
				    $data['date_end'] = NULL;
1781
				    $data['permanent'] = 1;
1782
				}
1783
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1784
				$NOTAM = new NOTAM();
1785
				$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']);
1786
				unset($data);
1787
			} 
1788
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1789
		if ($error != '') {
1790
			return $error;
1791
		} elseif ($globalDebug) echo "Done\n";
1792
		return '';
1793
	}
1794
	
1795
	public static function check_last_update() {
1796
		global $globalDBdriver;
1797
		if ($globalDBdriver == 'mysql') {
1798
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1799
		} else {
1800
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1801
		}
1802
		try {
1803
			$Connection = new Connection();
1804
			$sth = $Connection->db->prepare($query);
1805
                        $sth->execute();
1806
                } catch(PDOException $e) {
1807
                        return "error : ".$e->getMessage();
1808
                }
1809
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1810
                if ($row['nb'] > 0) return false;
1811
                else return true;
1812
	}
1813
1814
	public static function insert_last_update() {
1815
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1816
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1817
		try {
1818
			$Connection = new Connection();
1819
			$sth = $Connection->db->prepare($query);
1820
                        $sth->execute();
1821
                } catch(PDOException $e) {
1822
                        return "error : ".$e->getMessage();
1823
                }
1824
	}
1825
1826
	public static function check_last_notam_update() {
1827
		global $globalDBdriver;
1828
		if ($globalDBdriver == 'mysql') {
1829
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)";
1830
		} else {
1831
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
1832
		}
1833
		try {
1834
			$Connection = new Connection();
1835
			$sth = $Connection->db->prepare($query);
1836
                        $sth->execute();
1837
                } catch(PDOException $e) {
1838
                        return "error : ".$e->getMessage();
1839
                }
1840
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1841
                if ($row['nb'] > 0) return false;
1842
                else return true;
1843
	}
1844
1845
	public static function insert_last_notam_update() {
1846
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
1847
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
1848
		try {
1849
			$Connection = new Connection();
1850
			$sth = $Connection->db->prepare($query);
1851
                        $sth->execute();
1852
                } catch(PDOException $e) {
1853
                        return "error : ".$e->getMessage();
1854
                }
1855
	}
1856
1857
	public static function check_last_owner_update() {
1858
		global $globalDBdriver;
1859
		if ($globalDBdriver == 'mysql') {
1860
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1861
		} else {
1862
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1863
		}
1864
		try {
1865
			$Connection = new Connection();
1866
			$sth = $Connection->db->prepare($query);
1867
                        $sth->execute();
1868
                } catch(PDOException $e) {
1869
                        return "error : ".$e->getMessage();
1870
                }
1871
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1872
                if ($row['nb'] > 0) return false;
1873
                else return true;
1874
	}
1875
1876
	public static function insert_last_owner_update() {
1877
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
1878
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
1879
		try {
1880
			$Connection = new Connection();
1881
			$sth = $Connection->db->prepare($query);
1882
                        $sth->execute();
1883
                } catch(PDOException $e) {
1884
                        return "error : ".$e->getMessage();
1885
                }
1886
	}
1887
	public static function check_last_schedules_update() {
1888
		global $globalDBdriver;
1889
		if ($globalDBdriver == 'mysql') {
1890
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1891
		} else {
1892
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1893
		}
1894
		try {
1895
			$Connection = new Connection();
1896
			$sth = $Connection->db->prepare($query);
1897
                        $sth->execute();
1898
                } catch(PDOException $e) {
1899
                        return "error : ".$e->getMessage();
1900
                }
1901
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1902
                if ($row['nb'] > 0) return false;
1903
                else return true;
1904
	}
1905
1906
	public static function insert_last_schedules_update() {
1907
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
1908
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
1909
		try {
1910
			$Connection = new Connection();
1911
			$sth = $Connection->db->prepare($query);
1912
                        $sth->execute();
1913
                } catch(PDOException $e) {
1914
                        return "error : ".$e->getMessage();
1915
                }
1916
	}
1917
	public static function check_last_tle_update() {
1918
		global $globalDBdriver;
1919
		if ($globalDBdriver == 'mysql') {
1920
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(DATE(NOW()), INTERVAL 7 DAY)";
1921
		} else {
1922
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
1923
		}
1924
		try {
1925
			$Connection = new Connection();
1926
			$sth = $Connection->db->prepare($query);
1927
                        $sth->execute();
1928
                } catch(PDOException $e) {
1929
                        return "error : ".$e->getMessage();
1930
                }
1931
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1932
                if ($row['nb'] > 0) return false;
1933
                else return true;
1934
	}
1935
1936
	public static function insert_last_tle_update() {
1937
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
1938
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
1939
		try {
1940
			$Connection = new Connection();
1941
			$sth = $Connection->db->prepare($query);
1942
                        $sth->execute();
1943
                } catch(PDOException $e) {
1944
                        return "error : ".$e->getMessage();
1945
                }
1946
	}
1947
	
1948
	public static function update_all() {
1949
		global $globalMasterServer;
1950
		if (!isset($globalMasterServer) || !$globalMasterServer) {
1951
			echo update_db::update_routes();
1952
			echo update_db::update_translation();
1953
			echo update_db::update_translation_fam();
1954
			echo update_db::update_notam_fam();
1955
		}
1956
		echo update_db::update_ModeS();
1957
		echo update_db::update_ModeS_flarm();
1958
		echo update_db::update_ModeS_ogn();
1959
	}
1960
}
1961
1962
//echo update_db::update_airports();
1963
//echo update_db::translation();
1964
//echo update_db::update_waypoints();
1965
//echo update_db::update_airspace();
1966
//echo update_db::update_notam();
1967
//echo update_db::update_ivao();
1968
//echo update_db::update_ModeS_flarm();
1969
//echo update_db::update_ModeS_ogn();
1970
//echo update_db::update_aircraft();
1971
//$update_db = new update_db();
1972
//echo $update_db->update_owner();
1973
//update_db::update_translation_fam();
1974
//echo update_db::update_routes();
1975
//update_db::update_models();
1976
//echo $update_db::update_skyteam();
1977
//echo $update_db::update_tle();
1978
//echo update_db::update_notam_fam();
1979
?>
1980