Completed
Push — master ( d35909...f740b5 )
by Yannick
06:46
created

update_db::tle()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 32
nc 7
nop 2
dl 0
loc 48
rs 5.9322
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
					try {
137
						$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');
138
						$sth_dest->execute($query_dest_values);
139
					} catch(PDOException $e) {
140
						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...
141
						return "error : ".$e->getMessage();
142
					}
143
				}
144
			}
145
			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...
146
		}
147
                return '';
148
	}
149
	
150
	public static function retrieve_route_skyteam($database_file) {
151
		global $globalDebug, $globalTransaction;
152
		//$query = 'TRUNCATE TABLE routes';
153
		if ($globalDebug) echo " - Delete previous routes from DB -";
154
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
155
		$Connection = new Connection();
156
		try {
157
			//$Connection = new Connection();
158
			$sth = $Connection->db->prepare($query);
159
                        $sth->execute(array(':source' => 'skyteam'));
160
                } catch(PDOException $e) {
161
                        return "error : ".$e->getMessage();
162
                }
163
164
    		if ($globalDebug) echo " - Add routes to DB -";
165
166
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
167
		$Spotter = new Spotter();
168
		if ($fh = fopen($database_file,"r")) {
169
			$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)';
170
			$Connection = new Connection();
171
			$sth_dest = $Connection->db->prepare($query_dest);
172
			try {
173
				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...
174
				while (!feof($fh)) {
175
					$line = fgetcsv($fh,9999,',');
176
					if ($line[0] != '') {
177
						$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');
178
						$sth_dest->execute($query_dest_values);
179
					}
180
				}
181
				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...
182
			} catch(PDOException $e) {
183
				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...
184
				return "error : ".$e->getMessage();
185
			}
186
		}
187
                return '';
188
	}
189
	public static function retrieve_modes_sqlite_to_dest($database_file) {
190
		global $globalTransaction;
191
		//$query = 'TRUNCATE TABLE aircraft_modes';
192
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
193
		try {
194
			$Connection = new Connection();
195
			$sth = $Connection->db->prepare($query);
196
                        $sth->execute(array(':source' => $database_file));
197
                } catch(PDOException $e) {
198
                        return "error : ".$e->getMessage();
199
                }
200
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
201
		try {
202
			$Connection = new Connection();
203
			$sth = $Connection->db->prepare($query);
204
                        $sth->execute(array(':source' => $database_file));
205
                } catch(PDOException $e) {
206
                        return "error : ".$e->getMessage();
207
                }
208
209
    		update_db::connect_sqlite($database_file);
210
		$query = 'select * from Aircraft';
211
		try {
212
                        $sth = update_db::$db_sqlite->prepare($query);
213
                        $sth->execute();
214
                } catch(PDOException $e) {
215
                        return "error : ".$e->getMessage();
216
                }
217
		//$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)';
218
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
219
		
220
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
221
		
222
		$Connection = new Connection();
223
		$sth_dest = $Connection->db->prepare($query_dest);
224
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
225
		try {
226
			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...
227
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
228
			//$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']);
229
				if ($values['UserString4'] == 'M') $type = 'military';
230
				else $type = null;
231
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
232
				$sth_dest->execute($query_dest_values);
233
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
234
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
235
				    $sth_dest_owner->execute($query_dest_owner_values);
236
				}
237
            		}
238
			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...
239
		} catch(PDOException $e) {
240
			return "error : ".$e->getMessage();
241
		}
242
243
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
244
		try {
245
			$Connection = new Connection();
246
			$sth = $Connection->db->prepare($query);
247
                        $sth->execute(array(':source' => $database_file));
248
                } catch(PDOException $e) {
249
                        return "error : ".$e->getMessage();
250
                }
251
		return '';
252
	}
253
254
	public static function retrieve_modes_flarmnet($database_file) {
255
		global $globalTransaction;
256
		$Common = new Common();
257
		//$query = 'TRUNCATE TABLE aircraft_modes';
258
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
259
		try {
260
			$Connection = new Connection();
261
			$sth = $Connection->db->prepare($query);
262
                        $sth->execute(array(':source' => $database_file));
263
                } catch(PDOException $e) {
264
                        return "error : ".$e->getMessage();
265
                }
266
		
267
		if ($fh = fopen($database_file,"r")) {
268
			//$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)';
269
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
270
		
271
			$Connection = new Connection();
272
			$sth_dest = $Connection->db->prepare($query_dest);
273
			try {
274
				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...
275
            			while (!feof($fh)) {
276
            				$values = array();
277
            				$line = $Common->hex2str(fgets($fh,9999));
278
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
279
            				$values['ModeS'] = substr($line,0,6);
280
            				$values['Registration'] = trim(substr($line,69,6));
281
            				$aircraft_name = trim(substr($line,48,6));
282
            				// Check if we can find ICAO, else set it to GLID
283
            				$aircraft_name_split = explode(' ',$aircraft_name);
284
            				$search_more = '';
285
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
286
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
287
            				$sth_search = $Connection->db->prepare($query_search);
288
					try {
289
                                    		$sth_search->execute();
290
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
291
	            				//if (count($result) > 0) {
292
	            				if (isset($result['icao']) && $result['icao'] != '') {
293
	            				    $values['ICAOTypeCode'] = $result['icao'];
294
	            				} 
295
					} catch(PDOException $e) {
296
						return "error : ".$e->getMessage();
297
					}
298
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
299
					// Add data to db
300
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000') {
301
						//$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']);
302
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
303
						//print_r($query_dest_values);
304
						$sth_dest->execute($query_dest_values);
305
					}
306
				}
307
				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...
308
			} catch(PDOException $e) {
309
				return "error : ".$e->getMessage();
310
			}
311
		}
312
313
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
314
		try {
315
			$Connection = new Connection();
316
			$sth = $Connection->db->prepare($query);
317
                        $sth->execute(array(':source' => $database_file));
318
                } catch(PDOException $e) {
319
                        return "error : ".$e->getMessage();
320
                }
321
		return '';
322
	}
323
324
	public static function retrieve_modes_ogn($database_file) {
325
		global $globalTransaction;
326
		//$query = 'TRUNCATE TABLE aircraft_modes';
327
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
328
		try {
329
			$Connection = new Connection();
330
			$sth = $Connection->db->prepare($query);
331
                        $sth->execute(array(':source' => $database_file));
332
                } catch(PDOException $e) {
333
                        return "error : ".$e->getMessage();
334
                }
335
		
336
		if ($fh = fopen($database_file,"r")) {
337
			//$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)';
338
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
339
		
340
			$Connection = new Connection();
341
			$sth_dest = $Connection->db->prepare($query_dest);
342
			try {
343
				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...
344
				$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...
345
            			while (!feof($fh)) {
346
            				$line = fgetcsv($fh,9999,',',"'");
347
            				
348
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
349
					//print_r($line);
350
            				$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...
351
            				$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...
352
            				$aircraft_name = $line[2];
353
            				// Check if we can find ICAO, else set it to GLID
354
            				$aircraft_name_split = explode(' ',$aircraft_name);
355
            				$search_more = '';
356
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
357
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
358
            				$sth_search = $Connection->db->prepare($query_search);
359
					try {
360
                                    		$sth_search->execute();
361
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
362
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
363
					} catch(PDOException $e) {
364
						return "error : ".$e->getMessage();
365
					}
366
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
367
					// Add data to db
368
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
369
						//$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']);
370
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
371
						//print_r($query_dest_values);
372
						$sth_dest->execute($query_dest_values);
373
					}
374
				}
375
				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...
376
			} catch(PDOException $e) {
377
				return "error : ".$e->getMessage();
378
			}
379
		}
380
381
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
382
		try {
383
			$Connection = new Connection();
384
			$sth = $Connection->db->prepare($query);
385
                        $sth->execute(array(':source' => $database_file));
386
                } catch(PDOException $e) {
387
                        return "error : ".$e->getMessage();
388
                }
389
		return '';
390
	}
391
392
	public static function retrieve_owner($database_file,$country = 'F') {
393
		global $globalTransaction;
394
		//$query = 'TRUNCATE TABLE aircraft_modes';
395
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
396
		try {
397
			$Connection = new Connection();
398
			$sth = $Connection->db->prepare($query);
399
                        $sth->execute(array(':source' => $database_file));
400
                } catch(PDOException $e) {
401
                        return "error : ".$e->getMessage();
402
                }
403
		
404
		if ($fh = fopen($database_file,"r")) {
405
			//$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)';
406
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
407
		
408
			$Connection = new Connection();
409
			$sth_dest = $Connection->db->prepare($query_dest);
410
			try {
411
				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...
412
				$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...
413
            			while (!feof($fh)) {
414
            				$line = fgetcsv($fh,9999,',','"');
415
            				$values = array();
416
            				//print_r($line);
417
            				if ($country == 'F') {
418
            				    $values['registration'] = $line[0];
419
            				    $values['base'] = $line[4];
420
            				    $values['owner'] = $line[5];
421
            				    if ($line[6] == '') $values['date_first_reg'] = null;
422
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
423
					    $values['cancel'] = $line[7];
424
					} elseif ($country == 'EI') {
425
					    // TODO : add modeS & reg to aircraft_modes
426
            				    $values['registration'] = $line[0];
427
            				    $values['base'] = $line[3];
428
            				    $values['owner'] = $line[2];
429
            				    if ($line[1] == '') $values['date_first_reg'] = null;
430
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
431
					    $values['cancel'] = '';
432
					} elseif ($country == 'HB') {
433
					    // TODO : add modeS & reg to aircraft_modes
434
            				    $values['registration'] = $line[0];
435
            				    $values['base'] = null;
436
            				    $values['owner'] = $line[5];
437
            				    $values['date_first_reg'] = null;
438
					    $values['cancel'] = '';
439
					} elseif ($country == 'OK') {
440
					    // TODO : add modeS & reg to aircraft_modes
441
            				    $values['registration'] = $line[3];
442
            				    $values['base'] = null;
443
            				    $values['owner'] = $line[5];
444
            				    if ($line[18] == '') $values['date_first_reg'] = null;
445
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
446
					    $values['cancel'] = '';
447
					} elseif ($country == 'VH') {
448
					    // TODO : add modeS & reg to aircraft_modes
449
            				    $values['registration'] = $line[0];
450
            				    $values['base'] = null;
451
            				    $values['owner'] = $line[12];
452
            				    if ($line[28] == '') $values['date_first_reg'] = null;
453
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
454
455
					    $values['cancel'] = $line[39];
456
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
457
            				    $values['registration'] = $line[0];
458
            				    $values['base'] = null;
459
            				    $values['owner'] = $line[4];
460
            				    $values['date_first_reg'] = null;
461
					    $values['cancel'] = '';
462
					} elseif ($country == 'CC') {
463
            				    $values['registration'] = $line[0];
464
            				    $values['base'] = null;
465
            				    $values['owner'] = $line[6];
466
            				    $values['date_first_reg'] = null;
467
					    $values['cancel'] = '';
468
					} elseif ($country == 'HJ') {
469
            				    $values['registration'] = $line[0];
470
            				    $values['base'] = null;
471
            				    $values['owner'] = $line[8];
472
            				    if ($line[7] == '') $values['date_first_reg'] = null;
473
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
474
					    $values['cancel'] = '';
475
					} elseif ($country == 'PP') {
476
            				    $values['registration'] = $line[0];
477
            				    $values['base'] = null;
478
            				    $values['owner'] = $line[4];
479
            				    if ($line[6] == '') $values['date_first_reg'] = null;
480
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
481
					    $values['cancel'] = $line[7];
482
					} elseif ($country == 'E7') {
483
            				    $values['registration'] = $line[0];
484
            				    $values['base'] = null;
485
            				    $values['owner'] = $line[4];
486
            				    if ($line[5] == '') $values['date_first_reg'] = null;
487
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
488
					    $values['cancel'] = '';
489
					} elseif ($country == '8Q') {
490
            				    $values['registration'] = $line[0];
491
            				    $values['base'] = null;
492
            				    $values['owner'] = $line[3];
493
            				    if ($line[7] == '') $values['date_first_reg'] = null;
494
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
495
					    $values['cancel'] = '';
496
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
497
            				    $values['registration'] = $line[0];
498
            				    $values['base'] = null;
499
            				    $values['owner'] = $line[3];
500
            				    $values['date_first_reg'] = null;
501
					    $values['cancel'] = '';
502
					}
503
					if ($values['cancel'] == '' && $values['registration'] != null) {
504
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
505
						$sth_dest->execute($query_dest_values);
506
					}
507
				}
508
				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...
509
			} catch(PDOException $e) {
510
				return "error : ".$e->getMessage();
511
			}
512
		}
513
		return '';
514
	}
515
516
	/*
517
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
518
	*/
519
	public static function update_airports() {
520
		global $tmp_dir, $globalTransaction, $globalDebug;
521
522
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
523
		$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...
524
		$query = '
525
		    PREFIX dbo: <http://dbpedia.org/ontology/>
526
		    PREFIX dbp: <http://dbpedia.org/property/>
527
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
528
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
529
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
530
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
531
		    FROM <http://dbpedia.org>
532
		    WHERE {
533
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
534
535
			OPTIONAL {
536
			    ?airport dbo:icaoLocationIdentifier ?icao .
537
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
538
			}
539
540
			OPTIONAL {
541
			    ?airport dbo:iataLocationIdentifier ?iata .
542
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
543
			}
544
545
			OPTIONAL {
546
			    ?airport dbo:locationIdentifier ?lid .
547
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
548
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
549
			    OPTIONAL {
550
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
551
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
552
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
553
			    }
554
			    FILTER (!bound(?other_icao))
555
			}
556
557
			OPTIONAL {
558
			    ?airport dbo:faaLocationIdentifier ?faa .
559
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
560
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
561
			    OPTIONAL {
562
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
563
				?airport_x dbo:iataLocationIdentifier ?other_iata .
564
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
565
			    }
566
			    FILTER (!bound(?other_iata))
567
			}
568
569
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
570
	
571
			OPTIONAL {
572
			    ?airport rdfs:label ?name
573
			    FILTER (lang(?name) = "en")
574
			}
575
    
576
			OPTIONAL {
577
			    ?airport foaf:homepage ?homepage
578
			}
579
		    
580
			OPTIONAL {
581
			    ?airport dbp:coordinatesRegion ?country
582
			}
583
    
584
			OPTIONAL {
585
			    ?airport dbp:type ?type
586
			}
587
			
588
			OPTIONAL {
589
			    ?airport dbo:elevation ?altitude
590
			}
591
			OPTIONAL {
592
			    ?airport dbp:image ?image
593
			}
594
595
			{
596
			    ?airport geo:lat ?latitude .
597
			    ?airport geo:long ?longitude .
598
			    FILTER (datatype(?latitude) = xsd:float)
599
			    FILTER (datatype(?longitude) = xsd:float)
600
			} UNION {
601
			    ?airport geo:lat ?latitude .
602
			    ?airport geo:long ?longitude .
603
			    FILTER (datatype(?latitude) = xsd:double)
604
			    FILTER (datatype(?longitude) = xsd:double)
605
			    OPTIONAL {
606
				?airport geo:lat ?lat_f .
607
				?airport geo:long ?long_f .
608
				FILTER (datatype(?lat_f) = xsd:float)
609
				FILTER (datatype(?long_f) = xsd:float)
610
			    }
611
			    FILTER (!bound(?lat_f) && !bound(?long_f))
612
			}
613
614
		    }
615
		    ORDER BY ?airport
616
		';
617
		$result = sparql_query($query);
618
  
619
		$query = 'TRUNCATE TABLE airport';
620
		try {
621
			$Connection = new Connection();
622
			$sth = $Connection->db->prepare($query);
623
                        $sth->execute();
624
                } catch(PDOException $e) {
625
                        return "error : ".$e->getMessage();
626
                }
627
628
629
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
630
		try {
631
			$Connection = new Connection();
632
			$sth = $Connection->db->prepare($query);
633
                        $sth->execute();
634
                } catch(PDOException $e) {
635
                        return "error : ".$e->getMessage();
636
                }
637
638
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
639
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
640
		$Connection = new Connection();
641
		$sth_dest = $Connection->db->prepare($query_dest);
642
		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...
643
  
644
		$i = 0;
645
		while($row = sparql_fetch_array($result))
646
		{
647
			if ($i >= 1) {
648
			//print_r($row);
649
			if (!isset($row['iata'])) $row['iata'] = '';
650
			if (!isset($row['icao'])) $row['icao'] = '';
651
			if (!isset($row['type'])) $row['type'] = '';
652
			if (!isset($row['altitude'])) $row['altitude'] = '';
653
			if (isset($row['city_bis'])) {
654
				$row['city'] = $row['city_bis'];
655
			}
656
			if (!isset($row['city'])) $row['city'] = '';
657
			if (!isset($row['country'])) $row['country'] = '';
658
			if (!isset($row['homepage'])) $row['homepage'] = '';
659
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
660
			if (!isset($row['name'])) continue;
661
			if (!isset($row['image'])) {
662
				$row['image'] = '';
663
				$row['image_thumb'] = '';
664
			} else {
665
				$image = str_replace(' ','_',$row['image']);
666
				$digest = md5($image);
667
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
668
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
669
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
670
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
671
			}
672
			
673
			$country = explode('-',$row['country']);
674
			$row['country'] = $country[0];
675
			
676
			$row['type'] = trim($row['type']);
677
			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'])) {
678
				$row['type'] = 'Military';
679
			} 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') {
680
				$row['type'] = 'small_airport';
681
			}
682
			
683
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
684
			$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']);
685
			//print_r($query_dest_values);
686
			
687
			try {
688
				$sth_dest->execute($query_dest_values);
689
			} catch(PDOException $e) {
690
				return "error : ".$e->getMessage();
691
			}
692
			}
693
694
			$i++;
695
		}
696
		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...
697
		echo "Delete duplicate rows...\n";
698
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
699
		try {
700
			$Connection = new Connection();
701
			$sth = $Connection->db->prepare($query);
702
                        $sth->execute();
703
                } catch(PDOException $e) {
704
                        return "error : ".$e->getMessage();
705
                }
706
707
708
		if ($globalDebug) echo "Insert Not available Airport...\n";
709
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
710
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
711
		$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' => '');
712
		try {
713
			$Connection = new Connection();
714
			$sth = $Connection->db->prepare($query);
715
                        $sth->execute($query_values);
716
                } catch(PDOException $e) {
717
                        return "error : ".$e->getMessage();
718
                }
719
		$i++;
720
/*
721
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
722
		try {
723
			$Connection = new Connection();
724
			$sth = $Connection->db->prepare($query);
725
                        $sth->execute();
726
                } catch(PDOException $e) {
727
                        return "error : ".$e->getMessage();
728
                }
729
*/
730
731
		echo "Download data from ourairports.com...\n";
732
		$delimiter = ',';
733
		$out_file = $tmp_dir.'airports.csv';
734
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
735
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
736
		echo "Add data from ourairports.com...\n";
737
738
		$header = NULL;
739
		if (($handle = fopen($out_file, 'r')) !== FALSE)
740
		{
741
			$Connection = new Connection();
742
			//$Connection->db->beginTransaction();
743
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
744
			{
745
				if(!$header) $header = $row;
746
				else {
747
					$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...
748
					$data = array_combine($header, $row);
749
					try {
750
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
751
						$sth->execute(array(':icao' => $data['gps_code']));
752
					} catch(PDOException $e) {
753
						return "error : ".$e->getMessage();
754
					}
755
					if ($sth->fetchColumn() > 0) {
756
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
757
						try {
758
							$sth = $Connection->db->prepare($query);
759
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
760
						} catch(PDOException $e) {
761
							return "error : ".$e->getMessage();
762
						}
763
					} else {
764
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
765
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
766
						$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']);
767
						try {
768
							$sth = $Connection->db->prepare($query);
769
							$sth->execute($query_values);
770
						} catch(PDOException $e) {
771
							return "error : ".$e->getMessage();
772
						}
773
						$i++;
774
					}
775
				}
776
			}
777
			fclose($handle);
778
			//$Connection->db->commit();
779
		}
780
781
		echo "Download data from another free database...\n";
782
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
783
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
784
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
785
		update_db::unzip($out_file);
786
		$header = NULL;
787
		echo "Add data from another free database...\n";
788
		$delimiter = ':';
789
		$Connection = new Connection();
790
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
791
		{
792
			//$Connection->db->beginTransaction();
793
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
794
			{
795
				if(!$header) $header = $row;
796
				else {
797
					$data = $row;
798
799
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
800
					try {
801
						$sth = $Connection->db->prepare($query);
802
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
803
					} catch(PDOException $e) {
804
						return "error : ".$e->getMessage();
805
					}
806
				}
807
			}
808
			fclose($handle);
809
			//$Connection->db->commit();
810
		}
811
812
		echo "Put type military for all air base";
813
		$Connection = new Connection();
814
		try {
815
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
816
			$sth->execute();
817
		} catch(PDOException $e) {
818
			return "error : ".$e->getMessage();
819
		}
820
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
821
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
822
			try {
823
				$sth2 = $Connection->db->prepare($query2);
824
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
825
			} catch(PDOException $e) {
826
				return "error : ".$e->getMessage();
827
			}
828
		}
829
830
831
832
                return "success";
833
	}
834
	
835
	public static function translation() {
836
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
837
		global $tmp_dir, $globalTransaction;
838
		$Spotter = new Spotter();
839
		//$out_file = $tmp_dir.'translation.zip';
840
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
841
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
842
		
843
		//$query = 'TRUNCATE TABLE translation';
844
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
845
		try {
846
			$Connection = new Connection();
847
			$sth = $Connection->db->prepare($query);
848
                        $sth->execute(array(':source' => 'translation.csv'));
849
                } catch(PDOException $e) {
850
                        return "error : ".$e->getMessage();
851
                }
852
853
		
854
		//update_db::unzip($out_file);
855
		$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...
856
		$delimiter = ';';
857
		$Connection = new Connection();
858
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
859
		{
860
			$i = 0;
861
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
862
			//$Connection->db->beginTransaction();
863
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
864
			{
865
				$i++;
866
				if($i > 12) {
867
					$data = $row;
868
					$operator = $data[2];
869
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
870
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
871
                                                //echo substr($operator, 0, 2)."\n";;
872
                                                if (count($airline_array) > 0) {
873
							//print_r($airline_array);
874
							$operator = $airline_array[0]['icao'].substr($operator,2);
875
                                                }
876
                                        }
877
					
878
					$operator_correct = $data[3];
879
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
880
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
881
                                                if (count($airline_array) > 0) {
882
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
883
                                            	}
884
                                        }
885
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
886
					try {
887
						$sth = $Connection->db->prepare($query);
888
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
889
					} catch(PDOException $e) {
890
						return "error : ".$e->getMessage();
891
					}
892
				}
893
			}
894
			fclose($handle);
895
			//$Connection->db->commit();
896
		}
897
		return '';
898
        }
899
	
900
	public static function translation_fam() {
901
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
902
		global $tmp_dir, $globalTransaction;
903
		$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...
904
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
905
		try {
906
			$Connection = new Connection();
907
			$sth = $Connection->db->prepare($query);
908
                        $sth->execute(array(':source' => 'website_fam'));
909
                } catch(PDOException $e) {
910
                        return "error : ".$e->getMessage();
911
                }
912
913
		
914
		//update_db::unzip($out_file);
915
		$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...
916
		$delimiter = "\t";
917
		$Connection = new Connection();
918
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
919
		{
920
			$i = 0;
921
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
922
			//$Connection->db->beginTransaction();
923
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
924
			{
925
				if ($i > 0) {
926
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
927
					try {
928
						$sth = $Connection->db->prepare($query);
929
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
930
					} catch(PDOException $e) {
931
						return "error : ".$e->getMessage();
932
					}
933
				}
934
				$i++;
935
			}
936
			fclose($handle);
937
			//$Connection->db->commit();
938
		}
939
		return '';
940
        }
941
942
	public static function tle($filename,$tletype) {
943
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
944
		global $tmp_dir, $globalTransaction;
945
		//$Spotter = new Spotter();
946
		
947
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
948
		try {
949
			$Connection = new Connection();
950
			$sth = $Connection->db->prepare($query);
951
                        $sth->execute(array(':source' => $filename));
952
                } catch(PDOException $e) {
953
                        return "error : ".$e->getMessage();
954
                }
955
		
956
		$Connection = new Connection();
957
		if (($handle = fopen($filename, 'r')) !== FALSE)
958
		{
959
			$i = 0;
960
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
961
			//$Connection->db->beginTransaction();
962
			$dbdata = array();
963
			while (($data = fgets($handle, 1000)) !== FALSE)
964
			{
965
				if ($i == 0) {
966
					$dbdata['name'] = trim($data);
967
					$i++;
968
				} elseif ($i == 1) {
969
					$dbdata['tle1'] = trim($data);
970
					$i++;
971
				} elseif ($i == 2) {
972
					$dbdata['tle2'] = trim($data);
973
					//print_r($dbdata);
974
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
975
					try {
976
						$sth = $Connection->db->prepare($query);
977
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
978
					} catch(PDOException $e) {
979
						return "error : ".$e->getMessage();
980
					}
981
982
					$i = 0;
983
				}
984
			}
985
			fclose($handle);
986
			//$Connection->db->commit();
987
		}
988
		return '';
989
        }
990
991
	/**
992
        * Convert a HTML table to an array
993
        * @param String $data HTML page
994
        * @return Array array of the tables in HTML page
995
        */
996
        private static function table2array($data) {
997
                $html = str_get_html($data);
998
                $tabledata=array();
999
                foreach($html->find('tr') as $element)
1000
                {
1001
                        $td = array();
1002
                        foreach( $element->find('th') as $row)
1003
                        {
1004
                                $td [] = trim($row->plaintext);
1005
                        }
1006
                        $td=array_filter($td);
1007
                        $tabledata[] = $td;
1008
1009
                        $td = array();
1010
                        $tdi = array();
1011
                        foreach( $element->find('td') as $row)
1012
                        {
1013
                                $td [] = trim($row->plaintext);
1014
                                $tdi [] = trim($row->innertext);
1015
                        }
1016
                        $td=array_filter($td);
1017
                        $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...
1018
                    //    $tabledata[]=array_merge($td,$tdi);
1019
                        $tabledata[]=$td;
1020
                }
1021
                return(array_filter($tabledata));
1022
        }
1023
1024
       /**
1025
        * Get data from form result
1026
        * @param String $url form URL
1027
        * @return String the result
1028
        */
1029
        private static function getData($url) {
1030
                $ch = curl_init();
1031
                curl_setopt($ch, CURLOPT_URL, $url);
1032
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1033
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1034
                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');
1035
                return curl_exec($ch);
1036
        }
1037
/*
1038
	public static function waypoints() {
1039
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1040
		$table = update_db::table2array($data);
1041
//		print_r($table);
1042
		$query = 'TRUNCATE TABLE waypoints';
1043
		try {
1044
			$Connection = new Connection();
1045
			$sth = $Connection->db->prepare($query);
1046
                        $sth->execute();
1047
                } catch(PDOException $e) {
1048
                        return "error : ".$e->getMessage();
1049
                }
1050
1051
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1052
		$Connection = new Connection();
1053
		$sth_dest = $Connection->db->prepare($query_dest);
1054
		$Connection->db->beginTransaction();
1055
                foreach ($table as $row) {
1056
            		if ($row[0] != 'Ident') {
1057
				$ident = $row[0];
1058
				$latitude = $row[2];
1059
				$longitude = $row[3];
1060
				$control = $row[4];
1061
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1062
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1063
				try {
1064
					$sth_dest->execute($query_dest_values);
1065
				} catch(PDOException $e) {
1066
					return "error : ".$e->getMessage();
1067
				}
1068
			}
1069
                }
1070
		$Connection->db->commit();
1071
1072
	}
1073
*/
1074
	public static function waypoints($filename) {
1075
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1076
		global $tmp_dir, $globalTransaction;
1077
		//$Spotter = new Spotter();
1078
		//$out_file = $tmp_dir.'translation.zip';
1079
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1080
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1081
		$Connection = new Connection();
1082
		//update_db::unzip($out_file);
1083
		$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...
1084
		$delimiter = ' ';
1085
		if (($handle = fopen($filename, 'r')) !== FALSE)
1086
		{
1087
			$i = 0;
1088
			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...
1089
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1090
			{
1091
				$i++;
1092
				if($i > 3 && count($row) > 2) {
1093
					$data = array_values(array_filter($row));
1094
					$cntdata = count($data);
1095
					if ($cntdata > 10) {
1096
						$value = $data[9];
1097
						
1098
						for ($i =10;$i < $cntdata;$i++) {
1099
							$value .= ' '.$data[$i];
1100
						}
1101
						$data[9] = $value;
1102
					}
1103
					//print_r($data);
1104
					if (count($data) > 9) {
1105
						$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)';
1106
						try {
1107
							$sth = $Connection->db->prepare($query);
1108
							$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]));
1109
						} catch(PDOException $e) {
1110
							return "error : ".$e->getMessage();
1111
						}
1112
					}
1113
				}
1114
			}
1115
			fclose($handle);
1116
			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...
1117
		}
1118
		return '';
1119
        }
1120
1121
	public static function ivao_airlines($filename) {
1122
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1123
		global $tmp_dir, $globalTransaction;
1124
		$query = 'TRUNCATE TABLE airlines';
1125
		try {
1126
			$Connection = new Connection();
1127
			$sth = $Connection->db->prepare($query);
1128
                        $sth->execute();
1129
                } catch(PDOException $e) {
1130
                        return "error : ".$e->getMessage();
1131
                }
1132
1133
		$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...
1134
		$delimiter = ':';
1135
		$Connection = new Connection();
1136
		if (($handle = fopen($filename, 'r')) !== FALSE)
1137
		{
1138
			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...
1139
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1140
			{
1141
				if(count($row) > 1) {
1142
					$query = "INSERT INTO airlines (name,icao,active) VALUES (:name, :icao, 'Y')";
1143
					try {
1144
						$sth = $Connection->db->prepare($query);
1145
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1146
					} catch(PDOException $e) {
1147
						return "error : ".$e->getMessage();
1148
					}
1149
				}
1150
			}
1151
			fclose($handle);
1152
			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...
1153
		}
1154
		return '';
1155
        }
1156
	
1157
	public static function update_airspace() {
1158
		global $tmp_dir, $globalDBdriver;
1159
		include_once('class.create_db.php');
1160
		$Connection = new Connection();
1161
		if ($Connection->tableExists('airspace')) {
1162
			$query = 'DROP TABLE airspace';
1163
			try {
1164
				$sth = $Connection->db->prepare($query);
1165
                    		$sth->execute();
1166
	                } catch(PDOException $e) {
1167
				return "error : ".$e->getMessage();
1168
	                }
1169
	        }
1170
1171
1172
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1173
		else {
1174
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1175
			$query = "CREATE EXTENSION postgis";
1176
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1177
			try {
1178
				$sth = $Connection->db->prepare($query);
1179
				$sth->execute();
1180
			} catch(PDOException $e) {
1181
				return "error : ".$e->getMessage();
1182
			}
1183
		}
1184
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1185
		return $error;
1186
	}
1187
1188
	public static function update_vatsim() {
1189
		global $tmp_dir;
1190
		include_once('class.create_db.php');
1191
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1192
		return $error;
1193
	}
1194
	
1195
	public static function update_countries() {
1196
		global $tmp_dir, $globalDBdriver;
1197
		include_once('class.create_db.php');
1198
		$Connection = new Connection();
1199
		if ($Connection->tableExists('countries')) {
1200
			$query = 'DROP TABLE countries';
1201
			try {
1202
				$sth = $Connection->db->prepare($query);
1203
            	        	$sth->execute();
1204
	                } catch(PDOException $e) {
1205
    	                	echo "error : ".$e->getMessage();
1206
	                }
1207
		}
1208
		if ($globalDBdriver == 'mysql') {
1209
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1210
		} else {
1211
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1212
		}
1213
		$error = create_db::import_file($tmp_dir.'countries.sql');
1214
		return $error;
1215
	}
1216
1217
	
1218
	public static function update_waypoints() {
1219
		global $tmp_dir;
1220
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1221
//		update_db::unzip($tmp_dir.'AptNav.zip');
1222
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1223
//		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');
1224
		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');
1225
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1226
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1227
		return $error;
1228
	}
1229
1230
	public static function update_ivao() {
1231
		global $tmp_dir, $globalDebug;
1232
		$Common = new Common();
1233
		$error = '';
1234
		//Direct download forbidden
1235
		//if ($globalDebug) echo "IVAO : Download...";
1236
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1237
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1238
			if ($globalDebug) echo "Unzip...";
1239
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1240
			if ($globalDebug) echo "Add to DB...";
1241
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1242
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1243
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1244
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1245
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1246
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1247
		if ($error != '') {
1248
			return $error;
1249
		} elseif ($globalDebug) echo "Done\n";
1250
		return '';
1251
	}
1252
1253
	public static function update_routes() {
1254
		global $tmp_dir, $globalDebug;
1255
		$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...
1256
		if ($globalDebug) echo "Routes : Download...";
1257
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1258
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1259
			if ($globalDebug) echo "Gunzip...";
1260
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1261
			if ($globalDebug) echo "Add to DB...";
1262
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1263
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1264
		if ($error != '') {
1265
			return $error;
1266
		} elseif ($globalDebug) echo "Done\n";
1267
		return '';
1268
	}
1269
	public static function update_oneworld() {
1270
		global $tmp_dir, $globalDebug;
1271
		$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...
1272
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1273
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1274
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1275
			if ($globalDebug) echo "Gunzip...";
1276
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1277
			if ($globalDebug) echo "Add to DB...";
1278
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1279
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1280
		if ($error != '') {
1281
			return $error;
1282
		} elseif ($globalDebug) echo "Done\n";
1283
		return '';
1284
	}
1285
	public static function update_skyteam() {
1286
		global $tmp_dir, $globalDebug;
1287
		$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...
1288
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1289
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1290
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1291
			if ($globalDebug) echo "Gunzip...";
1292
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1293
			if ($globalDebug) echo "Add to DB...";
1294
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1295
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1296
		if ($error != '') {
1297
			return $error;
1298
		} elseif ($globalDebug) echo "Done\n";
1299
		return '';
1300
	}
1301
	public static function update_ModeS() {
1302
		global $tmp_dir, $globalDebug;
1303
/*
1304
		if ($globalDebug) echo "Modes : Download...";
1305
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1306
		if ($globalDebug) echo "Unzip...";
1307
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1308
		if ($globalDebug) echo "Add to DB...";
1309
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1310
		if ($error != true) {
1311
			echo $error;
1312
			exit;
1313
		} elseif ($globalDebug) echo "Done\n";
1314
*/
1315
		if ($globalDebug) echo "Modes : Download...";
1316
		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1317
		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1318
			if ($globalDebug) echo "Unzip...";
1319
			update_db::unzip($tmp_dir.'basestation_latest.zip');
1320
			if ($globalDebug) echo "Add to DB...";
1321
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1322
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1323
		if ($error != '') {
1324
			return $error;
1325
		} elseif ($globalDebug) echo "Done\n";
1326
		return '';
1327
	}
1328
1329
	public static function update_ModeS_flarm() {
1330
		global $tmp_dir, $globalDebug;
1331
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1332
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1333
		if (file_exists($tmp_dir.'data.fln')) {
1334
			if ($globalDebug) echo "Add to DB...";
1335
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1336
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1337
		if ($error != '') {
1338
			return $error;
1339
		} elseif ($globalDebug) echo "Done\n";
1340
		return '';
1341
	}
1342
1343
	public static function update_ModeS_ogn() {
1344
		global $tmp_dir, $globalDebug;
1345
		if ($globalDebug) echo "Modes OGN: Download...";
1346
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1347
		if (file_exists($tmp_dir.'ogn.csv')) {
1348
			if ($globalDebug) echo "Add to DB...";
1349
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1350
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1351
		if ($error != '') {
1352
			return $error;
1353
		} elseif ($globalDebug) echo "Done\n";
1354
		return '';
1355
	}
1356
1357
	public static function update_owner() {
1358
		global $tmp_dir, $globalDebug;
1359
		
1360
		if ($globalDebug) echo "Owner France: Download...";
1361
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1362
		if (file_exists($tmp_dir.'owner_f.csv')) {
1363
			if ($globalDebug) echo "Add to DB...";
1364
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1365
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1366
		if ($error != '') {
1367
			return $error;
1368
		} elseif ($globalDebug) echo "Done\n";
1369
		
1370
		if ($globalDebug) echo "Owner Ireland: Download...";
1371
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1372
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1373
			if ($globalDebug) echo "Add to DB...";
1374
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1375
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1376
		if ($error != '') {
1377
			return $error;
1378
		} elseif ($globalDebug) echo "Done\n";
1379
		if ($globalDebug) echo "Owner Switzerland: Download...";
1380
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1381
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1382
			if ($globalDebug) echo "Add to DB...";
1383
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1384
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1385
		if ($error != '') {
1386
			return $error;
1387
		} elseif ($globalDebug) echo "Done\n";
1388
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1389
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1390
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1391
			if ($globalDebug) echo "Add to DB...";
1392
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1393
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1394
		if ($error != '') {
1395
			return $error;
1396
		} elseif ($globalDebug) echo "Done\n";
1397
		if ($globalDebug) echo "Owner Australia: Download...";
1398
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1399
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1400
			if ($globalDebug) echo "Add to DB...";
1401
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1402
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1403
		if ($error != '') {
1404
			return $error;
1405
		} elseif ($globalDebug) echo "Done\n";
1406
		if ($globalDebug) echo "Owner Austria: Download...";
1407
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1408
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1409
			if ($globalDebug) echo "Add to DB...";
1410
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1411
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1412
		if ($error != '') {
1413
			return $error;
1414
		} elseif ($globalDebug) echo "Done\n";
1415
		if ($globalDebug) echo "Owner Chile: Download...";
1416
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1417
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1418
			if ($globalDebug) echo "Add to DB...";
1419
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1420
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1421
		if ($error != '') {
1422
			return $error;
1423
		} elseif ($globalDebug) echo "Done\n";
1424
		if ($globalDebug) echo "Owner Colombia: Download...";
1425
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1426
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1427
			if ($globalDebug) echo "Add to DB...";
1428
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1429
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1430
		if ($error != '') {
1431
			return $error;
1432
		} elseif ($globalDebug) echo "Done\n";
1433
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1434
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1435
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1436
			if ($globalDebug) echo "Add to DB...";
1437
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1438
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1439
		if ($error != '') {
1440
			return $error;
1441
		} elseif ($globalDebug) echo "Done\n";
1442
		if ($globalDebug) echo "Owner Brazil: Download...";
1443
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1444
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1445
			if ($globalDebug) echo "Add to DB...";
1446
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1447
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1448
		if ($error != '') {
1449
			return $error;
1450
		} elseif ($globalDebug) echo "Done\n";
1451
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1452
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1453
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1454
			if ($globalDebug) echo "Add to DB...";
1455
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1456
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1457
		if ($error != '') {
1458
			return $error;
1459
		} elseif ($globalDebug) echo "Done\n";
1460
		if ($globalDebug) echo "Owner Croatia: Download...";
1461
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1462
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1463
			if ($globalDebug) echo "Add to DB...";
1464
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1465
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1466
		if ($error != '') {
1467
			return $error;
1468
		} elseif ($globalDebug) echo "Done\n";
1469
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1470
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1471
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1472
			if ($globalDebug) echo "Add to DB...";
1473
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1474
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1475
		if ($error != '') {
1476
			return $error;
1477
		} elseif ($globalDebug) echo "Done\n";
1478
		if ($globalDebug) echo "Owner Maldives: Download...";
1479
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1480
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1481
			if ($globalDebug) echo "Add to DB...";
1482
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1483
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1484
		if ($error != '') {
1485
			return $error;
1486
		} elseif ($globalDebug) echo "Done\n";
1487
		if ($globalDebug) echo "Owner New Zealand: Download...";
1488
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1489
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1490
			if ($globalDebug) echo "Add to DB...";
1491
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1492
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1493
		if ($error != '') {
1494
			return $error;
1495
		} elseif ($globalDebug) echo "Done\n";
1496
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1497
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1498
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1499
			if ($globalDebug) echo "Add to DB...";
1500
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1501
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1502
		if ($error != '') {
1503
			return $error;
1504
		} elseif ($globalDebug) echo "Done\n";
1505
		if ($globalDebug) echo "Owner Slovakia: Download...";
1506
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1507
		if (file_exists($tmp_dir.'owner_om.csv')) {
1508
			if ($globalDebug) echo "Add to DB...";
1509
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1510
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1511
		if ($error != '') {
1512
			return $error;
1513
		} elseif ($globalDebug) echo "Done\n";
1514
		if ($globalDebug) echo "Owner Ecuador: Download...";
1515
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1516
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1517
			if ($globalDebug) echo "Add to DB...";
1518
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1519
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1520
		if ($error != '') {
1521
			return $error;
1522
		} elseif ($globalDebug) echo "Done\n";
1523
		if ($globalDebug) echo "Owner Iceland: Download...";
1524
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1525
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1526
			if ($globalDebug) echo "Add to DB...";
1527
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1528
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1529
		if ($error != '') {
1530
			return $error;
1531
		} elseif ($globalDebug) echo "Done\n";
1532
		return '';
1533
	}
1534
1535
	public static function update_translation() {
1536
		global $tmp_dir, $globalDebug;
1537
		$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...
1538
		if ($globalDebug) echo "Translation : Download...";
1539
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1540
		if (file_exists($tmp_dir.'translation.zip')) {
1541
			if ($globalDebug) echo "Unzip...";
1542
			update_db::unzip($tmp_dir.'translation.zip');
1543
			if ($globalDebug) echo "Add to DB...";
1544
			$error = update_db::translation();
1545
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1546
		if ($error != '') {
1547
			return $error;
1548
		} elseif ($globalDebug) echo "Done\n";
1549
		return '';
1550
	}
1551
1552
	public static function update_translation_fam() {
1553
		global $tmp_dir, $globalDebug;
1554
		$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...
1555
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1556
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1557
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1558
			if ($globalDebug) echo "Gunzip...";
1559
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1560
			if ($globalDebug) echo "Add to DB...";
1561
			$error = update_db::translation_fam();
1562
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1563
		if ($error != '') {
1564
			return $error;
1565
		} elseif ($globalDebug) echo "Done\n";
1566
		return '';
1567
	}
1568
1569
	public static function update_tle() {
1570
		global $tmp_dir, $globalDebug;
1571
		$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...
1572
		if ($globalDebug) echo "Download TLE : Download...";
1573
		$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',
1574
		'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',
1575
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1576
		foreach ($alltle as $filename) {
1577
			if ($globalDebug) echo "downloading ".$filename.'...';
1578
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1579
			if (file_exists($tmp_dir.$filename)) {
1580
				if ($globalDebug) echo "Add to DB ".$filename."...";
1581
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1582
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1583
			if ($error != '') {
1584
				echo $error."\n";
1585
			} elseif ($globalDebug) echo "Done\n";
1586
		}
1587
		return '';
1588
	}
1589
1590
	public static function update_models() {
1591
		global $tmp_dir, $globalDebug;
1592
		$error = '';
1593
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1594
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1595
		if (file_exists($tmp_dir.'models.md5sum')) {
1596
			if ($globalDebug) echo "Check files...\n";
1597
			$newmodelsdb = array();
1598
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1599
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1600
					$model = trim($row[2]);
1601
					$newmodelsdb[$model] = trim($row[0]);
1602
				}
1603
			}
1604
			$modelsdb = array();
1605
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1606
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1607
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1608
						$model = trim($row[2]);
1609
						$modelsdb[$model] = trim($row[0]);
1610
					}
1611
				}
1612
			}
1613
			$diff = array_diff($newmodelsdb,$modelsdb);
1614
			foreach ($diff as $key => $value) {
1615
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1616
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1617
				
1618
			}
1619
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1620
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1621
		if ($error != '') {
1622
			return $error;
1623
		} elseif ($globalDebug) echo "Done\n";
1624
		return '';
1625
	}
1626
1627
	public static function update_space_models() {
1628
		global $tmp_dir, $globalDebug;
1629
		$error = '';
1630
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1631
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1632
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1633
			if ($globalDebug) echo "Check files...\n";
1634
			$newmodelsdb = array();
1635
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1636
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1637
					$model = trim($row[2]);
1638
					$newmodelsdb[$model] = trim($row[0]);
1639
				}
1640
			}
1641
			$modelsdb = array();
1642
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1643
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1644
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1645
						$model = trim($row[2]);
1646
						$modelsdb[$model] = trim($row[0]);
1647
					}
1648
				}
1649
			}
1650
			$diff = array_diff($newmodelsdb,$modelsdb);
1651
			foreach ($diff as $key => $value) {
1652
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1653
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1654
				
1655
			}
1656
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1657
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1658
		if ($error != '') {
1659
			return $error;
1660
		} elseif ($globalDebug) echo "Done\n";
1661
		return '';
1662
	}
1663
1664
	public static function update_aircraft() {
1665
		global $tmp_dir, $globalDebug;
1666
		date_default_timezone_set('UTC');
1667
		$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...
1668
		/*
1669
		if ($globalDebug) echo "Aircrafts : Download...";
1670
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1671
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1672
		//$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);
1673
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1674
//		echo strlen($data_req);
1675
		echo $data;
1676
		*/
1677
		if (file_exists($tmp_dir.'aircrafts.html')) {
1678
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1679
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1680
		    $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...
1681
		    //echo $result;
1682
		    //var_dump(str_get_html($result));
1683
		    //print_r(self::table2array($result));
1684
		}
1685
1686
	}
1687
	
1688
	public static function update_notam() {
1689
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1690
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1691
		$Common = new Common();
1692
		date_default_timezone_set('UTC');
1693
		$query = 'TRUNCATE TABLE notam';
1694
		try {
1695
			$Connection = new Connection();
1696
			$sth = $Connection->db->prepare($query);
1697
                        $sth->execute();
1698
                } catch(PDOException $e) {
1699
                        return "error : ".$e->getMessage();
1700
                }
1701
1702
		$error = '';
1703
		if ($globalDebug) echo "Notam : Download...";
1704
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1705
		if (file_exists($tmp_dir.'notam.rss')) {
1706
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1707
			foreach ($notams['channel']['item'] as $notam) {
1708
				$title = explode(':',$notam['title']);
1709
				$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...
1710
				unset($title[0]);
1711
				$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...
1712
				$description = strip_tags($notam['description'],'<pre>');
1713
				preg_match(':^(.*?)<pre>:',$description,$match);
1714
				$q = explode('/',$match[1]);
1715
				$data['fir'] = $q[0];
1716
				$data['code'] = $q[1];
1717
				$ifrvfr = $q[2];
1718
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1719
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1720
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1721
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1722
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1723
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1724
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1725
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1726
				//$data['scope'] = $q[4];
1727
				$data['lower_limit'] = $q[5];
1728
				$data['upper_limit'] = $q[6];
1729
				$latlonrad = $q[7];
1730
				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...
1731
				$latitude = $Common->convertDec($las,'latitude');
1732
				$longitude = $Common->convertDec($lns,'longitude');
1733
				if ($lac == 'S') $latitude = '-'.$latitude;
1734
				if ($lnc == 'W') $longitude = '-'.$longitude;
1735
				$data['center_latitude'] = $latitude;
1736
				$data['center_longitude'] = $longitude;
1737
				$data['radius'] = intval($radius);
1738
				
1739
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1740
				$data['text'] = $match[1];
1741
				preg_match(':</pre>(.*?)$:',$description,$match);
1742
				$fromto = $match[1];
1743
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1744
				$fromall = trim($match[1]);
1745
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1746
				$from = trim($match[1]);
1747
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1748
				preg_match('#TO:(.*?)$#',$fromto,$match);
1749
				$toall = trim($match[1]);
1750
				if (!preg_match(':Permanent:',$toall)) {
1751
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1752
					$to = trim($match[1]);
1753
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1754
					$data['permanent'] = 0;
1755
				} else {
1756
				    $data['date_end'] = NULL;
1757
				    $data['permanent'] = 1;
1758
				}
1759
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1760
				$NOTAM = new NOTAM();
1761
				$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']);
1762
				unset($data);
1763
			} 
1764
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1765
		if ($error != '') {
1766
			return $error;
1767
		} elseif ($globalDebug) echo "Done\n";
1768
		return '';
1769
	}
1770
	
1771
	public static function check_last_update() {
1772
		global $globalDBdriver;
1773
		if ($globalDBdriver == 'mysql') {
1774
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1775
		} else {
1776
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1777
		}
1778
		try {
1779
			$Connection = new Connection();
1780
			$sth = $Connection->db->prepare($query);
1781
                        $sth->execute();
1782
                } catch(PDOException $e) {
1783
                        return "error : ".$e->getMessage();
1784
                }
1785
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1786
                if ($row['nb'] > 0) return false;
1787
                else return true;
1788
	}
1789
1790
	public static function insert_last_update() {
1791
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1792
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1793
		try {
1794
			$Connection = new Connection();
1795
			$sth = $Connection->db->prepare($query);
1796
                        $sth->execute();
1797
                } catch(PDOException $e) {
1798
                        return "error : ".$e->getMessage();
1799
                }
1800
	}
1801
1802
	public static function check_last_notam_update() {
1803
		global $globalDBdriver;
1804
		if ($globalDBdriver == 'mysql') {
1805
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)";
1806
		} else {
1807
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
1808
		}
1809
		try {
1810
			$Connection = new Connection();
1811
			$sth = $Connection->db->prepare($query);
1812
                        $sth->execute();
1813
                } catch(PDOException $e) {
1814
                        return "error : ".$e->getMessage();
1815
                }
1816
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1817
                if ($row['nb'] > 0) return false;
1818
                else return true;
1819
	}
1820
1821
	public static function insert_last_notam_update() {
1822
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
1823
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
1824
		try {
1825
			$Connection = new Connection();
1826
			$sth = $Connection->db->prepare($query);
1827
                        $sth->execute();
1828
                } catch(PDOException $e) {
1829
                        return "error : ".$e->getMessage();
1830
                }
1831
	}
1832
1833
	public static function check_last_owner_update() {
1834
		global $globalDBdriver;
1835
		if ($globalDBdriver == 'mysql') {
1836
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1837
		} else {
1838
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1839
		}
1840
		try {
1841
			$Connection = new Connection();
1842
			$sth = $Connection->db->prepare($query);
1843
                        $sth->execute();
1844
                } catch(PDOException $e) {
1845
                        return "error : ".$e->getMessage();
1846
                }
1847
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1848
                if ($row['nb'] > 0) return false;
1849
                else return true;
1850
	}
1851
1852
	public static function insert_last_owner_update() {
1853
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
1854
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
1855
		try {
1856
			$Connection = new Connection();
1857
			$sth = $Connection->db->prepare($query);
1858
                        $sth->execute();
1859
                } catch(PDOException $e) {
1860
                        return "error : ".$e->getMessage();
1861
                }
1862
	}
1863
	public static function check_last_schedules_update() {
1864
		global $globalDBdriver;
1865
		if ($globalDBdriver == 'mysql') {
1866
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1867
		} else {
1868
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1869
		}
1870
		try {
1871
			$Connection = new Connection();
1872
			$sth = $Connection->db->prepare($query);
1873
                        $sth->execute();
1874
                } catch(PDOException $e) {
1875
                        return "error : ".$e->getMessage();
1876
                }
1877
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1878
                if ($row['nb'] > 0) return false;
1879
                else return true;
1880
	}
1881
1882
	public static function insert_last_schedules_update() {
1883
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
1884
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
1885
		try {
1886
			$Connection = new Connection();
1887
			$sth = $Connection->db->prepare($query);
1888
                        $sth->execute();
1889
                } catch(PDOException $e) {
1890
                        return "error : ".$e->getMessage();
1891
                }
1892
	}
1893
	public static function check_last_tle_update() {
1894
		global $globalDBdriver;
1895
		if ($globalDBdriver == 'mysql') {
1896
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(DATE(NOW()), INTERVAL 7 DAY)";
1897
		} else {
1898
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
1899
		}
1900
		try {
1901
			$Connection = new Connection();
1902
			$sth = $Connection->db->prepare($query);
1903
                        $sth->execute();
1904
                } catch(PDOException $e) {
1905
                        return "error : ".$e->getMessage();
1906
                }
1907
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1908
                if ($row['nb'] > 0) return false;
1909
                else return true;
1910
	}
1911
1912
	public static function insert_last_tle_update() {
1913
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
1914
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
1915
		try {
1916
			$Connection = new Connection();
1917
			$sth = $Connection->db->prepare($query);
1918
                        $sth->execute();
1919
                } catch(PDOException $e) {
1920
                        return "error : ".$e->getMessage();
1921
                }
1922
	}
1923
	
1924
	public static function update_all() {
1925
		echo update_db::update_routes();
1926
		echo update_db::update_ModeS();
1927
		echo update_db::update_ModeS_flarm();
1928
		echo update_db::update_ModeS_ogn();
1929
		echo update_db::update_translation();
1930
		echo update_db::update_translation_fam();
1931
	}
1932
}
1933
1934
//echo update_db::update_airports();
1935
//echo update_db::translation();
1936
//echo update_db::update_waypoints();
1937
//echo update_db::update_airspace();
1938
//echo update_db::update_notam();
1939
//echo update_db::update_ivao();
1940
//echo update_db::update_ModeS_flarm();
1941
//echo update_db::update_ModeS_ogn();
1942
//echo update_db::update_aircraft();
1943
//$update_db = new update_db();
1944
//echo $update_db->update_owner();
1945
//update_db::update_translation_fam();
1946
//echo update_db::update_routes();
1947
//update_db::update_models();
1948
//echo $update_db::update_skyteam();
1949
//echo $update_db::update_tle();
1950
?>
1951