Completed
Push — master ( 9d6f17...825d36 )
by Yannick
09:37
created

update_db::update_routes()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 16
Code Lines 15

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
c 0
b 0
f 0
nc 30
nop 0
dl 16
loc 16
rs 8.2222
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
		$data = curl_exec($ch);
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...
23
		curl_close($ch);
24
	}
25
26
	public static function gunzip($in_file,$out_file_name = '') {
27
		//echo $in_file.' -> '.$out_file_name."\n";
28
		$buffer_size = 4096; // read 4kb at a time
29
		if ($out_file_name == '') $out_file_name = str_replace('.gz', '', $in_file); 
30
		if ($in_file != '' && file_exists($in_file)) {
31
			// PHP version of Ubuntu use gzopen64 instead of gzopen
32
			if (function_exists('gzopen')) $file = gzopen($in_file,'rb');
33
			elseif (function_exists('gzopen64')) $file = gzopen64($in_file,'rb');
34
			$out_file = fopen($out_file_name, 'wb'); 
35
			while(!gzeof($file)) {
0 ignored issues
show
Bug introduced by
The variable $file 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...
36
				fwrite($out_file, gzread($file, $buffer_size));
37
			}  
38
			fclose($out_file);
39
			gzclose($file);
40
		}
41
	}
42
43
	public static function unzip($in_file) {
44
		if ($in_file != '' && file_exists($in_file)) {
45
			$path = pathinfo(realpath($in_file), PATHINFO_DIRNAME);
46
			$zip = new ZipArchive;
47
			$res = $zip->open($in_file);
48
			if ($res === TRUE) {
49
				$zip->extractTo($path);
50
				$zip->close();
51
			} else return false;
52
		} else return false;
53
	}
54
	
55
	public static function connect_sqlite($database) {
56
		try {
57
			self::$db_sqlite = new PDO('sqlite:'.$database);
58
			self::$db_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
59
		} catch(PDOException $e) {
60
			return "error : ".$e->getMessage();
61
		}
62
	}
63
	
64
	public static function retrieve_route_sqlite_to_dest($database_file) {
65
		global $globalDebug, $globalTransaction;
66
		//$query = 'TRUNCATE TABLE routes';
67
		if ($globalDebug) echo " - Delete previous routes from DB -";
68
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
69
		$Connection = new Connection();
70
		try {
71
			//$Connection = new Connection();
72
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
73
                        $sth->execute(array(':source' => $database_file));
74
                } catch(PDOException $e) {
75
                        return "error : ".$e->getMessage();
76
                }
77
78
    		if ($globalDebug) echo " - Add routes to DB -";
79
    		update_db::connect_sqlite($database_file);
80
		//$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';
81
		$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";
82
		try {
83
                        $sth = update_db::$db_sqlite->prepare($query);
84
                        $sth->execute();
85
                } catch(PDOException $e) {
86
                        return "error : ".$e->getMessage();
87
                }
88
		//$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)';
89
		$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,ToAirport_ICAO,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
90
		$Connection = new Connection();
91
		$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
92
		try {
93
			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...
94
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
95
				//$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);
96
				$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);
97
				$sth_dest->execute($query_dest_values);
98
            		}
99
			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...
100
		} catch(PDOException $e) {
101
			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...
102
			return "error : ".$e->getMessage();
103
		}
104
                return '';
105
	}
106 View Code Duplication
	public static function retrieve_route_oneworld($database_file) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
		global $globalDebug, $globalTransaction;
108
		//$query = 'TRUNCATE TABLE routes';
109
		if ($globalDebug) echo " - Delete previous routes from DB -";
110
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
111
		$Connection = new Connection();
112
		try {
113
			//$Connection = new Connection();
114
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
115
                        $sth->execute(array(':source' => 'oneworld'));
116
                } catch(PDOException $e) {
117
                        return "error : ".$e->getMessage();
118
                }
119
120
    		if ($globalDebug) echo " - Add routes to DB -";
121
122
		if ($fh = fopen($database_file,"r")) {
123
			$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)';
124
			$Connection = new Connection();
125
			$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
126
			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...
127
			while (!feof($fh)) {
128
				$line = fgetcsv($fh,9999,',');
129
				if ($line[0] != '') {
130
					try {
131
						$query_dest_values = array(':CallSign' => str_replace('*','',$line[7]),':Operator_ICAO' => '',':FromAirport_ICAO' => $line[0],':FromAirport_Time' => $line[5],':ToAirport_ICAO' => $line[1],':ToAirport_Time' => $line[6],':routestop' => '',':source' => 'oneworld');
132
						$sth_dest->execute($query_dest_values);
133
					} catch(PDOException $e) {
134
						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...
135
						return "error : ".$e->getMessage();
136
					}
137
				}
138
			}
139
			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...
140
		}
141
                return '';
142
	}
143
	
144 View Code Duplication
	public static function retrieve_route_skyteam($database_file) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
145
		global $globalDebug, $globalTransaction;
146
		//$query = 'TRUNCATE TABLE routes';
147
		if ($globalDebug) echo " - Delete previous routes from DB -";
148
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
149
		$Connection = new Connection();
150
		try {
151
			//$Connection = new Connection();
152
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
153
                        $sth->execute(array(':source' => 'skyteam'));
154
                } catch(PDOException $e) {
155
                        return "error : ".$e->getMessage();
156
                }
157
158
    		if ($globalDebug) echo " - Add routes to DB -";
159
160
		if ($fh = fopen($database_file,"r")) {
161
			$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)';
162
			$Connection = new Connection();
163
			$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
164
			try {
165
				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...
166
				while (!feof($fh)) {
167
					$line = fgetcsv($fh,9999,',');
168
					if ($line[0] != '') {
169
						$query_dest_values = array(':CallSign' => str_replace('*','',$line[6]),':Operator_ICAO' => '',':FromAirport_ICAO' => $line[0],':FromAirport_Time' => $line[4],':ToAirport_ICAO' => $line[1],':ToAirport_Time' => $line[5],':routestop' => '',':source' => 'skyteam');
170
						$sth_dest->execute($query_dest_values);
171
					}
172
				}
173
				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...
174
			} catch(PDOException $e) {
175
				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...
176
				return "error : ".$e->getMessage();
177
			}
178
		}
179
                return '';
180
	}
181
	public static function retrieve_modes_sqlite_to_dest($database_file) {
182
		global $globalTransaction;
183
		//$query = 'TRUNCATE TABLE aircraft_modes';
184
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
185
		try {
186
			$Connection = new Connection();
187
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare cannot be called on $Connection->db (of type null).

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

Loading history...
188
                        $sth->execute(array(':source' => $database_file));
189
                } catch(PDOException $e) {
190
                        return "error : ".$e->getMessage();
191
                }
192
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
193
		try {
194
			$Connection = new Connection();
195
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
196
                        $sth->execute(array(':source' => $database_file));
197
                } catch(PDOException $e) {
198
                        return "error : ".$e->getMessage();
199
                }
200
201
    		update_db::connect_sqlite($database_file);
202
		$query = 'select * from Aircraft';
203
		try {
204
                        $sth = update_db::$db_sqlite->prepare($query);
205
                        $sth->execute();
206
                } catch(PDOException $e) {
207
                        return "error : ".$e->getMessage();
208
                }
209
		//$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)';
210
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
211
		
212
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
213
		
214
		$Connection = new Connection();
215
		$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
216
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
1 ignored issue
show
Bug introduced by
The method prepare 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...
217
		try {
218
			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...
219
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
220
			//$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']);
221
				if ($values['UserString4'] == 'M') $type = 'military';
222
				else $type = null;
223
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
224
				$sth_dest->execute($query_dest_values);
225
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
226
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
227
				    $sth_dest_owner->execute($query_dest_owner_values);
228
				}
229
            		}
230
			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...
231
		} catch(PDOException $e) {
232
			return "error : ".$e->getMessage();
233
		}
234
235
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
236
		try {
237
			$Connection = new Connection();
238
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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
                        $sth->execute(array(':source' => $database_file));
240
                } catch(PDOException $e) {
241
                        return "error : ".$e->getMessage();
242
                }
243
		return '';
244
	}
245
246
	public static function retrieve_modes_flarmnet($database_file) {
247
		global $globalTransaction;
248
		$Common = new Common();
249
		//$query = 'TRUNCATE TABLE aircraft_modes';
250
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
251
		try {
252
			$Connection = new Connection();
253
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
254
                        $sth->execute(array(':source' => $database_file));
255
                } catch(PDOException $e) {
256
                        return "error : ".$e->getMessage();
257
                }
258
		
259
		if ($fh = fopen($database_file,"r")) {
260
			//$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)';
261
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
262
		
263
			$Connection = new Connection();
264
			$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
265
			try {
266
				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...
267
            			while (!feof($fh)) {
268
            				$line = $Common->hex2str(fgets($fh,9999));
269
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
270
            				$values['ModeS'] = substr($line,0,6);
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...
271
            				$values['Registration'] = trim(substr($line,69,6));
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...
272
            				$aircraft_name = trim(substr($line,48,6));
273
            				// Check if we can find ICAO, else set it to GLID
274
            				$aircraft_name_split = explode(' ',$aircraft_name);
275
            				$search_more = '';
276 View Code Duplication
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
277
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
278
            				$sth_search = $Connection->db->prepare($query_search);
1 ignored issue
show
Bug introduced by
The method prepare 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...
279
					try {
280
                                    		$sth_search->execute();
281
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
282
	            				//if (count($result) > 0) {
283 View Code Duplication
	            				if (isset($result['icao']) && $result['icao'] != '') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
284
	            				    $values['ICAOTypeCode'] = $result['icao'];
285
	            				} 
286
					} catch(PDOException $e) {
287
						return "error : ".$e->getMessage();
288
					}
289
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
290
					// Add data to db
291 View Code Duplication
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
292
						//$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']);
293
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
294
						//print_r($query_dest_values);
295
						$sth_dest->execute($query_dest_values);
296
					}
297
				}
298
				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...
299
			} catch(PDOException $e) {
300
				return "error : ".$e->getMessage();
301
			}
302
		}
303
304
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
305
		try {
306
			$Connection = new Connection();
307
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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
                        $sth->execute(array(':source' => $database_file));
309
                } catch(PDOException $e) {
310
                        return "error : ".$e->getMessage();
311
                }
312
		return '';
313
	}
314
315
	public static function retrieve_modes_ogn($database_file) {
316
		global $globalTransaction;
317
		//$query = 'TRUNCATE TABLE aircraft_modes';
318
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
319
		try {
320
			$Connection = new Connection();
321
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
322
                        $sth->execute(array(':source' => $database_file));
323
                } catch(PDOException $e) {
324
                        return "error : ".$e->getMessage();
325
                }
326
		
327
		if ($fh = fopen($database_file,"r")) {
328
			//$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)';
329
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
330
		
331
			$Connection = new Connection();
332
			$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
333
			try {
334
				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...
335
				$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...
336
            			while (!feof($fh)) {
337
            				$line = fgetcsv($fh,9999,',',"'");
338
            				
339
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
340
					//print_r($line);
341
            				$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...
342
            				$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...
343
            				$aircraft_name = $line[2];
344
            				// Check if we can find ICAO, else set it to GLID
345
            				$aircraft_name_split = explode(' ',$aircraft_name);
346
            				$search_more = '';
347 View Code Duplication
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
348
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
349
            				$sth_search = $Connection->db->prepare($query_search);
1 ignored issue
show
Bug introduced by
The method prepare 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...
350
					try {
351
                                    		$sth_search->execute();
352
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
353 View Code Duplication
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
354
					} catch(PDOException $e) {
355
						return "error : ".$e->getMessage();
356
					}
357
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
358
					// Add data to db
359 View Code Duplication
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
360
						//$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']);
361
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
362
						//print_r($query_dest_values);
363
						$sth_dest->execute($query_dest_values);
364
					}
365
				}
366
				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...
367
			} catch(PDOException $e) {
368
				return "error : ".$e->getMessage();
369
			}
370
		}
371
372
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
373
		try {
374
			$Connection = new Connection();
375
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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
                        $sth->execute(array(':source' => $database_file));
377
                } catch(PDOException $e) {
378
                        return "error : ".$e->getMessage();
379
                }
380
		return '';
381
	}
382
383
	public static function retrieve_owner($database_file,$country = 'F') {
384
		global $globalTransaction;
385
		//$query = 'TRUNCATE TABLE aircraft_modes';
386
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
387
		try {
388
			$Connection = new Connection();
389
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
390
                        $sth->execute(array(':source' => $database_file));
391
                } catch(PDOException $e) {
392
                        return "error : ".$e->getMessage();
393
                }
394
		
395
		if ($fh = fopen($database_file,"r")) {
396
			//$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)';
397
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
398
		
399
			$Connection = new Connection();
400
			$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
401
			try {
402
				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...
403
				$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...
404
            			while (!feof($fh)) {
405
            				$line = fgetcsv($fh,9999,',','"');
406
            				//print_r($line);
407
            				if ($country == 'F') {
408
            				    $values['registration'] = $line[0];
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...
409
            				    $values['base'] = $line[4];
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...
410
            				    $values['owner'] = $line[5];
411
            				    if ($line[6] == '') $values['date_first_reg'] = null;
412
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
413
					    $values['cancel'] = $line[7];
414 View Code Duplication
					} elseif ($country == 'EI') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
415
					    // TODO : add modeS & reg to aircraft_modes
416
            				    $values['registration'] = $line[0];
417
            				    $values['base'] = $line[3];
418
            				    $values['owner'] = $line[2];
419
            				    if ($line[1] == '') $values['date_first_reg'] = null;
420
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
421
					    $values['cancel'] = '';
422
					} elseif ($country == 'HB') {
423
					    // TODO : add modeS & reg to aircraft_modes
424
            				    $values['registration'] = $line[0];
425
            				    $values['base'] = null;
426
            				    $values['owner'] = $line[5];
427
            				    $values['date_first_reg'] = null;
428
					    $values['cancel'] = '';
429 View Code Duplication
					} elseif ($country == 'OK') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
430
					    // TODO : add modeS & reg to aircraft_modes
431
            				    $values['registration'] = $line[3];
432
            				    $values['base'] = null;
433
            				    $values['owner'] = $line[5];
434
            				    if ($line[18] == '') $values['date_first_reg'] = null;
435
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
436
					    $values['cancel'] = '';
437
					} elseif ($country == 'VH') {
438
					    // TODO : add modeS & reg to aircraft_modes
439
            				    $values['registration'] = $line[0];
440
            				    $values['base'] = null;
441
            				    $values['owner'] = $line[12];
442
            				    if ($line[28] == '') $values['date_first_reg'] = null;
443
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
444
445
					    $values['cancel'] = $line[39];
446
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
447
            				    $values['registration'] = $line[0];
448
            				    $values['base'] = null;
449
            				    $values['owner'] = $line[4];
450
            				    $values['date_first_reg'] = null;
451
					    $values['cancel'] = '';
452
					} elseif ($country == 'CC') {
453
            				    $values['registration'] = $line[0];
454
            				    $values['base'] = null;
455
            				    $values['owner'] = $line[6];
456
            				    $values['date_first_reg'] = null;
457
					    $values['cancel'] = '';
458 View Code Duplication
					} elseif ($country == 'HJ') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
459
            				    $values['registration'] = $line[0];
460
            				    $values['base'] = null;
461
            				    $values['owner'] = $line[8];
462
            				    if ($line[7] == '') $values['date_first_reg'] = null;
463
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
464
					    $values['cancel'] = '';
465
					} elseif ($country == 'PP') {
466
            				    $values['registration'] = $line[0];
467
            				    $values['base'] = null;
468
            				    $values['owner'] = $line[4];
469
            				    if ($line[6] == '') $values['date_first_reg'] = null;
470
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
471
					    $values['cancel'] = $line[7];
472 View Code Duplication
					} elseif ($country == 'E7') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
473
            				    $values['registration'] = $line[0];
474
            				    $values['base'] = null;
475
            				    $values['owner'] = $line[4];
476
            				    if ($line[5] == '') $values['date_first_reg'] = null;
477
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
478
					    $values['cancel'] = '';
479
					} elseif ($country == '8Q') {
480
            				    $values['registration'] = $line[0];
481
            				    $values['base'] = null;
482
            				    $values['owner'] = $line[3];
483
            				    if ($line[7] == '') $values['date_first_reg'] = null;
484
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
485
					    $values['cancel'] = '';
486
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
487
            				    $values['registration'] = $line[0];
488
            				    $values['base'] = null;
489
            				    $values['owner'] = $line[3];
490
            				    $values['date_first_reg'] = null;
491
					    $values['cancel'] = '';
492
					}
493
					if ($values['cancel'] == '' && $values['registration'] != null) {
494
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
495
						$sth_dest->execute($query_dest_values);
496
					}
497
				}
498
				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...
499
			} catch(PDOException $e) {
500
				return "error : ".$e->getMessage();
501
			}
502
		}
503
		return '';
504
	}
505
506
	/*
507
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
508
	*/
509
	public static function update_airports() {
510
		global $tmp_dir, $globalTransaction;
511
512
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
513
		$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...
514
		$query = '
515
		    PREFIX dbo: <http://dbpedia.org/ontology/>
516
		    PREFIX dbp: <http://dbpedia.org/property/>
517
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
518
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
519
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
520
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
521
		    FROM <http://dbpedia.org>
522
		    WHERE {
523
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
524
525
			OPTIONAL {
526
			    ?airport dbo:icaoLocationIdentifier ?icao .
527
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
528
			}
529
530
			OPTIONAL {
531
			    ?airport dbo:iataLocationIdentifier ?iata .
532
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
533
			}
534
535
			OPTIONAL {
536
			    ?airport dbo:locationIdentifier ?lid .
537
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
538
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
539
			    OPTIONAL {
540
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
541
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
542
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
543
			    }
544
			    FILTER (!bound(?other_icao))
545
			}
546
547
			OPTIONAL {
548
			    ?airport dbo:faaLocationIdentifier ?faa .
549
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
550
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
551
			    OPTIONAL {
552
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
553
				?airport_x dbo:iataLocationIdentifier ?other_iata .
554
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
555
			    }
556
			    FILTER (!bound(?other_iata))
557
			}
558
559
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
560
	
561
			OPTIONAL {
562
			    ?airport rdfs:label ?name
563
			    FILTER (lang(?name) = "en")
564
			}
565
    
566
			OPTIONAL {
567
			    ?airport foaf:homepage ?homepage
568
			}
569
		    
570
			OPTIONAL {
571
			    ?airport dbp:coordinatesRegion ?country
572
			}
573
    
574
			OPTIONAL {
575
			    ?airport dbp:type ?type
576
			}
577
			
578
			OPTIONAL {
579
			    ?airport dbo:elevation ?altitude
580
			}
581
			OPTIONAL {
582
			    ?airport dbp:image ?image
583
			}
584
585
			{
586
			    ?airport geo:lat ?latitude .
587
			    ?airport geo:long ?longitude .
588
			    FILTER (datatype(?latitude) = xsd:float)
589
			    FILTER (datatype(?longitude) = xsd:float)
590
			} UNION {
591
			    ?airport geo:lat ?latitude .
592
			    ?airport geo:long ?longitude .
593
			    FILTER (datatype(?latitude) = xsd:double)
594
			    FILTER (datatype(?longitude) = xsd:double)
595
			    OPTIONAL {
596
				?airport geo:lat ?lat_f .
597
				?airport geo:long ?long_f .
598
				FILTER (datatype(?lat_f) = xsd:float)
599
				FILTER (datatype(?long_f) = xsd:float)
600
			    }
601
			    FILTER (!bound(?lat_f) && !bound(?long_f))
602
			}
603
604
		    }
605
		    ORDER BY ?airport
606
		';
607
		$result = sparql_query($query);
608
  
609
		$query = 'TRUNCATE TABLE airport';
610
		try {
611
			$Connection = new Connection();
612
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
613
                        $sth->execute();
614
                } catch(PDOException $e) {
615
                        return "error : ".$e->getMessage();
616
                }
617
618
619
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
620
		try {
621
			$Connection = new Connection();
622
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
623
                        $sth->execute();
624
                } catch(PDOException $e) {
625
                        return "error : ".$e->getMessage();
626
                }
627
628
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
629
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
630
		$Connection = new Connection();
631
		$sth_dest = $Connection->db->prepare($query_dest);
1 ignored issue
show
Bug introduced by
The method prepare 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...
632
		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...
633
  
634
		$i = 0;
635
		while($row = sparql_fetch_array($result))
636
		{
637
			if ($i >= 1) {
638
			//print_r($row);
639
			if (!isset($row['iata'])) $row['iata'] = '';
640
			if (!isset($row['icao'])) $row['icao'] = '';
641
			if (!isset($row['type'])) $row['type'] = '';
642
			if (!isset($row['altitude'])) $row['altitude'] = '';
643
			if (isset($row['city_bis'])) {
644
				$row['city'] = $row['city_bis'];
645
			}
646
			if (!isset($row['city'])) $row['city'] = '';
647
			if (!isset($row['country'])) $row['country'] = '';
648
			if (!isset($row['homepage'])) $row['homepage'] = '';
649
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
650
			if (!isset($row['name'])) continue;
651
			if (!isset($row['image'])) {
652
				$row['image'] = '';
653
				$row['image_thumb'] = '';
654
			} else {
655
				$image = str_replace(' ','_',$row['image']);
656
				$digest = md5($image);
657
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
658
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
659
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
660
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
661
			}
662
			
663
			$country = explode('-',$row['country']);
664
			$row['country'] = $country[0];
665
			
666
			$row['type'] = trim($row['type']);
667
			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'])) {
668
				$row['type'] = 'Military';
669
			} 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') {
670
				$row['type'] = 'small_airport';
671
			}
672
			
673
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
674
			$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']);
675
			//print_r($query_dest_values);
676
			
677
			try {
678
				$sth_dest->execute($query_dest_values);
679
			} catch(PDOException $e) {
680
				return "error : ".$e->getMessage();
681
			}
682
			}
683
684
			$i++;
685
		}
686
		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...
687
		echo "Delete duplicate rows...\n";
688
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
689
		try {
690
			$Connection = new Connection();
691
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
692
                        $sth->execute();
693
                } catch(PDOException $e) {
694
                        return "error : ".$e->getMessage();
695
                }
696
697
698
		if ($globalDebug) echo "Insert Not available Airport...\n";
0 ignored issues
show
Bug introduced by
The variable $globalDebug 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...
699
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
700
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
701
		$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' => '');
702
		try {
703
			$Connection = new Connection();
704
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
705
                        $sth->execute($query_values);
706
                } catch(PDOException $e) {
707
                        return "error : ".$e->getMessage();
708
                }
709
		$i++;
710
/*
711
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
712
		try {
713
			$Connection = new Connection();
714
			$sth = $Connection->db->prepare($query);
715
                        $sth->execute();
716
                } catch(PDOException $e) {
717
                        return "error : ".$e->getMessage();
718
                }
719
*/
720
721
		echo "Download data from ourairports.com...\n";
722
		$delimiter = ',';
723
		$out_file = $tmp_dir.'airports.csv';
724
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
725
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
726
		echo "Add data from ourairports.com...\n";
727
728
		$header = NULL;
729
		if (($handle = fopen($out_file, 'r')) !== FALSE)
730
		{
731
			$Connection = new Connection();
732
			//$Connection->db->beginTransaction();
733
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
734
			{
735
				if(!$header) $header = $row;
736
				else {
737
					$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...
738
					$data = array_combine($header, $row);
739
					try {
740
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
1 ignored issue
show
Bug introduced by
The method prepare 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...
741
						$sth->execute(array(':icao' => $data['gps_code']));
742
					} catch(PDOException $e) {
743
						return "error : ".$e->getMessage();
744
					}
745
					if ($sth->fetchColumn() > 0) {
746
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
747
						try {
748
							$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
749
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
750
						} catch(PDOException $e) {
751
							return "error : ".$e->getMessage();
752
						}
753
					} else {
754
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
755
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
756
						$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']);
757
						try {
758
							$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
759
							$sth->execute($query_values);
760
						} catch(PDOException $e) {
761
							return "error : ".$e->getMessage();
762
						}
763
						$i++;
764
					}
765
				}
766
			}
767
			fclose($handle);
768
			//$Connection->db->commit();
769
		}
770
771
		echo "Download data from another free database...\n";
772
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
773
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
774
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
775
		update_db::unzip($out_file);
776
		$header = NULL;
777
		echo "Add data from another free database...\n";
778
		$delimiter = ':';
779
		$Connection = new Connection();
780
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
781
		{
782
			//$Connection->db->beginTransaction();
783
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
784
			{
785
				if(!$header) $header = $row;
786
				else {
787
					$data = $row;
788
789
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
790
					try {
791
						$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
792
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
793
					} catch(PDOException $e) {
794
						return "error : ".$e->getMessage();
795
					}
796
				}
797
			}
798
			fclose($handle);
799
			//$Connection->db->commit();
800
		}
801
802
		echo "Put type military for all air base";
803
		$Connection = new Connection();
804
		try {
805
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
1 ignored issue
show
Bug introduced by
The method prepare 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...
806
			$sth->execute();
807
		} catch(PDOException $e) {
808
			return "error : ".$e->getMessage();
809
		}
810
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
811
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
812
			try {
813
				$sth2 = $Connection->db->prepare($query2);
1 ignored issue
show
Bug introduced by
The method prepare 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...
814
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
815
			} catch(PDOException $e) {
816
				return "error : ".$e->getMessage();
817
			}
818
		}
819
820
821
822
                return "success";
823
	}
824
	
825
	public static function translation() {
826
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
827
		global $tmp_dir, $globalTransaction;
828
		$Spotter = new Spotter();
829
		//$out_file = $tmp_dir.'translation.zip';
830
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
831
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
832
		
833
		//$query = 'TRUNCATE TABLE translation';
834
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
835
		try {
836
			$Connection = new Connection();
837
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
838
                        $sth->execute(array(':source' => 'translation.csv'));
839
                } catch(PDOException $e) {
840
                        return "error : ".$e->getMessage();
841
                }
842
843
		
844
		//update_db::unzip($out_file);
845
		$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...
846
		$delimiter = ';';
847
		$Connection = new Connection();
848
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
849
		{
850
			$i = 0;
851
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
852
			//$Connection->db->beginTransaction();
853
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
854
			{
855
				$i++;
856
				if($i > 12) {
857
					$data = $row;
858
					$operator = $data[2];
859 View Code Duplication
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
860
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
861
                                                //echo substr($operator, 0, 2)."\n";;
862
                                                if (count($airline_array) > 0) {
863
							//print_r($airline_array);
864
							$operator = $airline_array[0]['icao'].substr($operator,2);
865
                                                }
866
                                        }
867
					
868
					$operator_correct = $data[3];
869 View Code Duplication
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
870
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
871
                                                if (count($airline_array) > 0) {
872
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
873
                                            	}
874
                                        }
875
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
876
					try {
877
						$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
878
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
879
					} catch(PDOException $e) {
880
						return "error : ".$e->getMessage();
881
					}
882
				}
883
			}
884
			fclose($handle);
885
			//$Connection->db->commit();
886
		}
887
		return '';
888
        }
889
	
890
	public static function translation_fam() {
891
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
892
		global $tmp_dir, $globalTransaction;
893
		$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...
894
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
895
		try {
896
			$Connection = new Connection();
897
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
898
                        $sth->execute(array(':source' => 'website_fam'));
899
                } catch(PDOException $e) {
900
                        return "error : ".$e->getMessage();
901
                }
902
903
		
904
		//update_db::unzip($out_file);
905
		$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...
906
		$delimiter = "\t";
907
		$Connection = new Connection();
908
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
909
		{
910
			$i = 0;
911
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
912
			//$Connection->db->beginTransaction();
913
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
914
			{
915
				if ($i > 0) {
916
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
917
					try {
918
						$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
919
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
920
					} catch(PDOException $e) {
921
						return "error : ".$e->getMessage();
922
					}
923
				}
924
				$i++;
925
			}
926
			fclose($handle);
927
			//$Connection->db->commit();
928
		}
929
		return '';
930
        }
931
932
	/**
933
        * Convert a HTML table to an array
934
        * @param String $data HTML page
935
        * @return Array array of the tables in HTML page
936
        */
937
        private static function table2array($data) {
1 ignored issue
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
938
                $html = str_get_html($data);
939
                $tabledata=array();
940 View Code Duplication
                foreach($html->find('tr') as $element)
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
941
                {
942
                        $td = array();
943
                        foreach( $element->find('th') as $row)
944
                        {
945
                                $td [] = trim($row->plaintext);
946
                        }
947
                        $td=array_filter($td);
948
                        $tabledata[] = $td;
949
950
                        $td = array();
951
                        $tdi = array();
952
                        foreach( $element->find('td') as $row)
953
                        {
954
                                $td [] = trim($row->plaintext);
955
                                $tdi [] = trim($row->innertext);
956
                        }
957
                        $td=array_filter($td);
958
                        $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...
959
                    //    $tabledata[]=array_merge($td,$tdi);
960
                        $tabledata[]=$td;
961
                }
962
                return(array_filter($tabledata));
963
        }
964
965
       /**
966
        * Get data from form result
967
        * @param String $url form URL
968
        * @return String the result
969
        */
970
        private static function getData($url) {
1 ignored issue
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
971
                $ch = curl_init();
972
                curl_setopt($ch, CURLOPT_URL, $url);
973
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
974
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
975
                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');
976
                return curl_exec($ch);
977
        }
978
/*
979
	public static function waypoints() {
980
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
981
		$table = update_db::table2array($data);
982
//		print_r($table);
983
		$query = 'TRUNCATE TABLE waypoints';
984
		try {
985
			$Connection = new Connection();
986
			$sth = $Connection->db->prepare($query);
987
                        $sth->execute();
988
                } catch(PDOException $e) {
989
                        return "error : ".$e->getMessage();
990
                }
991
992
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
993
		$Connection = new Connection();
994
		$sth_dest = $Connection->db->prepare($query_dest);
995
		$Connection->db->beginTransaction();
996
                foreach ($table as $row) {
997
            		if ($row[0] != 'Ident') {
998
				$ident = $row[0];
999
				$latitude = $row[2];
1000
				$longitude = $row[3];
1001
				$control = $row[4];
1002
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1003
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1004
				try {
1005
					$sth_dest->execute($query_dest_values);
1006
				} catch(PDOException $e) {
1007
					return "error : ".$e->getMessage();
1008
				}
1009
			}
1010
                }
1011
		$Connection->db->commit();
1012
1013
	}
1014
*/
1015
	public static function waypoints($filename) {
1016
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1017
		global $tmp_dir, $globalTransaction;
1018
		//$Spotter = new Spotter();
1019
		//$out_file = $tmp_dir.'translation.zip';
1020
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1021
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1022
		$Connection = new Connection();
1023
		//update_db::unzip($out_file);
1024
		$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...
1025
		$delimiter = ' ';
1026
		if (($handle = fopen($filename, 'r')) !== FALSE)
1027
		{
1028
			$i = 0;
1029
			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...
1030
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1031
			{
1032
				$i++;
1033
				if($i > 3 && count($row) > 2) {
1034
					$data = array_values(array_filter($row));
1035
					$cntdata = count($data);
1036
					if ($cntdata > 10) {
1037
						$value = $data[9];
1038
						
1039
						for ($i =10;$i < $cntdata;$i++) {
1040
							$value .= ' '.$data[$i];
1041
						}
1042
						$data[9] = $value;
1043
					}
1044
					//print_r($data);
1045
					if (count($data) > 9) {
1046
						$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)';
1047
						try {
1048
							$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1049
							$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]));
1050
						} catch(PDOException $e) {
1051
							return "error : ".$e->getMessage();
1052
						}
1053
					}
1054
				}
1055
			}
1056
			fclose($handle);
1057
			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...
1058
		}
1059
		return '';
1060
        }
1061
1062
	public static function ivao_airlines($filename) {
1063
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1064
		global $tmp_dir, $globalTransaction;
1065
		$query = 'TRUNCATE TABLE airlines';
1066
		try {
1067
			$Connection = new Connection();
1068
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1069
                        $sth->execute();
1070
                } catch(PDOException $e) {
1071
                        return "error : ".$e->getMessage();
1072
                }
1073
1074
		$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...
1075
		$delimiter = ':';
1076
		$Connection = new Connection();
1077
		if (($handle = fopen($filename, 'r')) !== FALSE)
1078
		{
1079
			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...
1080
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1081
			{
1082
				if(count($row) > 1) {
1083
					$query = "INSERT INTO airlines (name,icao,active) VALUES (:name, :icao, 'Y')";
1084
					try {
1085
						$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1086
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1087
					} catch(PDOException $e) {
1088
						return "error : ".$e->getMessage();
1089
					}
1090
				}
1091
			}
1092
			fclose($handle);
1093
			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...
1094
		}
1095
		return '';
1096
        }
1097
	
1098
	public static function update_airspace() {
1099
		global $tmp_dir, $globalDBdriver;
1100
		include_once('class.create_db.php');
1101
		$Connection = new Connection();
1102 View Code Duplication
		if ($Connection->tableExists('airspace')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1103
			$query = 'DROP TABLE airspace';
1104
			try {
1105
				$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1106
                    		$sth->execute();
1107
	                } catch(PDOException $e) {
1108
				return "error : ".$e->getMessage();
1109
	                }
1110
	        }
1111
1112
1113
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1114
		else {
1115
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1116
			$query = "CREATE EXTENSION postgis";
1117
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1118
			try {
1119
				$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1120
				$sth->execute();
1121
			} catch(PDOException $e) {
1122
				return "error : ".$e->getMessage();
1123
			}
1124
		}
1125
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1126
		return $error;
1127
	}
1128
1129
	public static function update_vatsim() {
1130
		global $tmp_dir;
1131
		include_once('class.create_db.php');
1132
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1133
		return $error;
1134
	}
1135
	
1136
	public static function update_countries() {
1137
		global $tmp_dir, $globalDBdriver;
1138
		include_once('class.create_db.php');
1139
		$Connection = new Connection();
1140 View Code Duplication
		if ($Connection->tableExists('countries')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1141
			$query = 'DROP TABLE countries';
1142
			try {
1143
				$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1144
            	        	$sth->execute();
1145
	                } catch(PDOException $e) {
1146
    	                	echo "error : ".$e->getMessage();
1147
	                }
1148
		}
1149
		if ($globalDBdriver == 'mysql') {
1150
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1151
		} else {
1152
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1153
		}
1154
		$error = create_db::import_file($tmp_dir.'countries.sql');
1155
		return $error;
1156
	}
1157
1158
	
1159
	public static function update_waypoints() {
1160
		global $tmp_dir;
1161
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1162
//		update_db::unzip($tmp_dir.'AptNav.zip');
1163
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1164
//		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');
1165
		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');
1166
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1167
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1168
		return $error;
1169
	}
1170
1171
	public static function update_ivao() {
1172
		global $tmp_dir, $globalDebug;
1173
		$Common = new Common();
1174
		$error = '';
1175
		//Direct download forbidden
1176
		//if ($globalDebug) echo "IVAO : Download...";
1177
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1178
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1179
			if ($globalDebug) echo "Unzip...";
1180
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1181
			if ($globalDebug) echo "Add to DB...";
1182
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1183
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1184
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1185
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1186
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1187
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1188
		if ($error != '') {
1189
			return $error;
1190
		} elseif ($globalDebug) echo "Done\n";
1191
		return '';
1192
	}
1193
1194 View Code Duplication
	public static function update_routes() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1195
		global $tmp_dir, $globalDebug;
1196
		$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...
1197
		if ($globalDebug) echo "Routes : Download...";
1198
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1199
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1200
			if ($globalDebug) echo "Gunzip...";
1201
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1202
			if ($globalDebug) echo "Add to DB...";
1203
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1204
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1205
		if ($error != '') {
1206
			return $error;
1207
		} elseif ($globalDebug) echo "Done\n";
1208
		return '';
1209
	}
1210 View Code Duplication
	public static function update_oneworld() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1211
		global $tmp_dir, $globalDebug;
1212
		$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...
1213
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1214
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1215
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1216
			if ($globalDebug) echo "Gunzip...";
1217
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1218
			if ($globalDebug) echo "Add to DB...";
1219
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1220
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1221
		if ($error != '') {
1222
			return $error;
1223
		} elseif ($globalDebug) echo "Done\n";
1224
		return '';
1225
	}
1226 View Code Duplication
	public static function update_skyteam() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1227
		global $tmp_dir, $globalDebug;
1228
		$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...
1229
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1230
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1231
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1232
			if ($globalDebug) echo "Gunzip...";
1233
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1234
			if ($globalDebug) echo "Add to DB...";
1235
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1236
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1237
		if ($error != '') {
1238
			return $error;
1239
		} elseif ($globalDebug) echo "Done\n";
1240
		return '';
1241
	}
1242 View Code Duplication
	public static function update_ModeS() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1243
		global $tmp_dir, $globalDebug;
1244
/*
1245
		if ($globalDebug) echo "Modes : Download...";
1246
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1247
		if ($globalDebug) echo "Unzip...";
1248
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1249
		if ($globalDebug) echo "Add to DB...";
1250
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1251
		if ($error != true) {
1252
			echo $error;
1253
			exit;
1254
		} elseif ($globalDebug) echo "Done\n";
1255
*/
1256
		if ($globalDebug) echo "Modes : Download...";
1257
		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1258
		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1259
			if ($globalDebug) echo "Unzip...";
1260
			update_db::unzip($tmp_dir.'basestation_latest.zip');
1261
			if ($globalDebug) echo "Add to DB...";
1262
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1263
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1264
		if ($error != '') {
1265
			return $error;
1266
		} elseif ($globalDebug) echo "Done\n";
1267
		return '';
1268
	}
1269
1270 View Code Duplication
	public static function update_ModeS_flarm() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1271
		global $tmp_dir, $globalDebug;
1272
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1273
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1274
		if (file_exists($tmp_dir.'data.fln')) {
1275
			if ($globalDebug) echo "Add to DB...";
1276
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1277
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1278
		if ($error != '') {
1279
			return $error;
1280
		} elseif ($globalDebug) echo "Done\n";
1281
		return '';
1282
	}
1283
1284 View Code Duplication
	public static function update_ModeS_ogn() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1285
		global $tmp_dir, $globalDebug;
1286
		if ($globalDebug) echo "Modes OGN: Download...";
1287
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1288
		if (file_exists($tmp_dir.'ogn.csv')) {
1289
			if ($globalDebug) echo "Add to DB...";
1290
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1291
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1292
		if ($error != '') {
1293
			return $error;
1294
		} elseif ($globalDebug) echo "Done\n";
1295
		return '';
1296
	}
1297
1298
	public static function update_owner() {
1299
		global $tmp_dir, $globalDebug;
1300
		
1301
		if ($globalDebug) echo "Owner France: Download...";
1302
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1303 View Code Duplication
		if (file_exists($tmp_dir.'owner_f.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1304
			if ($globalDebug) echo "Add to DB...";
1305
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1306
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1307
		if ($error != '') {
1308
			return $error;
1309
		} elseif ($globalDebug) echo "Done\n";
1310
		
1311
		if ($globalDebug) echo "Owner Ireland: Download...";
1312
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1313 View Code Duplication
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1314
			if ($globalDebug) echo "Add to DB...";
1315
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1316
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1317
		if ($error != '') {
1318
			return $error;
1319
		} elseif ($globalDebug) echo "Done\n";
1320
		if ($globalDebug) echo "Owner Switzerland: Download...";
1321
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1322 View Code Duplication
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1323
			if ($globalDebug) echo "Add to DB...";
1324
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1325
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1326
		if ($error != '') {
1327
			return $error;
1328
		} elseif ($globalDebug) echo "Done\n";
1329
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1330
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1331 View Code Duplication
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1332
			if ($globalDebug) echo "Add to DB...";
1333
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1334
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1335
		if ($error != '') {
1336
			return $error;
1337
		} elseif ($globalDebug) echo "Done\n";
1338
		if ($globalDebug) echo "Owner Australia: Download...";
1339
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1340 View Code Duplication
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1341
			if ($globalDebug) echo "Add to DB...";
1342
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1343
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1344
		if ($error != '') {
1345
			return $error;
1346
		} elseif ($globalDebug) echo "Done\n";
1347
		if ($globalDebug) echo "Owner Austria: Download...";
1348
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1349 View Code Duplication
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1350
			if ($globalDebug) echo "Add to DB...";
1351
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1352
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1353
		if ($error != '') {
1354
			return $error;
1355
		} elseif ($globalDebug) echo "Done\n";
1356
		if ($globalDebug) echo "Owner Chile: Download...";
1357
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1358 View Code Duplication
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1359
			if ($globalDebug) echo "Add to DB...";
1360
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1361
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1362
		if ($error != '') {
1363
			return $error;
1364
		} elseif ($globalDebug) echo "Done\n";
1365
		if ($globalDebug) echo "Owner Colombia: Download...";
1366
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1367 View Code Duplication
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1368
			if ($globalDebug) echo "Add to DB...";
1369
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1370
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1371
		if ($error != '') {
1372
			return $error;
1373
		} elseif ($globalDebug) echo "Done\n";
1374
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1375
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1376 View Code Duplication
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1377
			if ($globalDebug) echo "Add to DB...";
1378
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1379
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1380
		if ($error != '') {
1381
			return $error;
1382
		} elseif ($globalDebug) echo "Done\n";
1383
		if ($globalDebug) echo "Owner Brazil: Download...";
1384
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1385 View Code Duplication
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1386
			if ($globalDebug) echo "Add to DB...";
1387
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1388
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1389
		if ($error != '') {
1390
			return $error;
1391
		} elseif ($globalDebug) echo "Done\n";
1392
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1393
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1394 View Code Duplication
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1395
			if ($globalDebug) echo "Add to DB...";
1396
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1397
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1398
		if ($error != '') {
1399
			return $error;
1400
		} elseif ($globalDebug) echo "Done\n";
1401
		if ($globalDebug) echo "Owner Croatia: Download...";
1402
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1403 View Code Duplication
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1404
			if ($globalDebug) echo "Add to DB...";
1405
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1406
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1407
		if ($error != '') {
1408
			return $error;
1409
		} elseif ($globalDebug) echo "Done\n";
1410
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1411
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1412 View Code Duplication
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1413
			if ($globalDebug) echo "Add to DB...";
1414
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1415
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1416
		if ($error != '') {
1417
			return $error;
1418
		} elseif ($globalDebug) echo "Done\n";
1419
		if ($globalDebug) echo "Owner Maldives: Download...";
1420
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1421 View Code Duplication
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1422
			if ($globalDebug) echo "Add to DB...";
1423
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1424
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1425
		if ($error != '') {
1426
			return $error;
1427
		} elseif ($globalDebug) echo "Done\n";
1428
		if ($globalDebug) echo "Owner New Zealand: Download...";
1429
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1430 View Code Duplication
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1431
			if ($globalDebug) echo "Add to DB...";
1432
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1433
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1434
		if ($error != '') {
1435
			return $error;
1436
		} elseif ($globalDebug) echo "Done\n";
1437
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1438
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1439 View Code Duplication
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1440
			if ($globalDebug) echo "Add to DB...";
1441
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1442
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1443
		if ($error != '') {
1444
			return $error;
1445
		} elseif ($globalDebug) echo "Done\n";
1446
		if ($globalDebug) echo "Owner Slovakia: Download...";
1447
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1448 View Code Duplication
		if (file_exists($tmp_dir.'owner_om.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1449
			if ($globalDebug) echo "Add to DB...";
1450
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1451
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1452
		if ($error != '') {
1453
			return $error;
1454
		} elseif ($globalDebug) echo "Done\n";
1455
		if ($globalDebug) echo "Owner Ecuador: Download...";
1456
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1457 View Code Duplication
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1458
			if ($globalDebug) echo "Add to DB...";
1459
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1460
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1461
		if ($error != '') {
1462
			return $error;
1463
		} elseif ($globalDebug) echo "Done\n";
1464
		if ($globalDebug) echo "Owner Iceland: Download...";
1465
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1466 View Code Duplication
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1467
			if ($globalDebug) echo "Add to DB...";
1468
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1469
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1470
		if ($error != '') {
1471
			return $error;
1472
		} elseif ($globalDebug) echo "Done\n";
1473
		return '';
1474
	}
1475
1476 View Code Duplication
	public static function update_translation() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1477
		global $tmp_dir, $globalDebug;
1478
		$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...
1479
		if ($globalDebug) echo "Translation : Download...";
1480
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1481
		if (file_exists($tmp_dir.'translation.zip')) {
1482
			if ($globalDebug) echo "Unzip...";
1483
			update_db::unzip($tmp_dir.'translation.zip');
1484
			if ($globalDebug) echo "Add to DB...";
1485
			$error = update_db::translation();
1486
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1487
		if ($error != '') {
1488
			return $error;
1489
		} elseif ($globalDebug) echo "Done\n";
1490
		return '';
1491
	}
1492
1493 View Code Duplication
	public static function update_translation_fam() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1494
		global $tmp_dir, $globalDebug;
1495
		$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...
1496
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1497
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1498
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1499
			if ($globalDebug) echo "Gunzip...";
1500
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1501
			if ($globalDebug) echo "Add to DB...";
1502
			$error = update_db::translation_fam();
1503
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1504
		if ($error != '') {
1505
			return $error;
1506
		} elseif ($globalDebug) echo "Done\n";
1507
		return '';
1508
	}
1509
1510
	public static function update_models() {
1511
		global $tmp_dir, $globalDebug;
1512
		$error = '';
1513
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1514
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1515
		if (file_exists($tmp_dir.'models.md5sum')) {
1516
			if ($globalDebug) echo "Check files...\n";
1517
			$newmodelsdb = array();
1518 View Code Duplication
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1519
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1520
					$model = trim($row[2]);
1521
					$newmodelsdb[$model] = trim($row[0]);
1522
				}
1523
			}
1524
			if (file_exists(dirname(__FILE__).'../models/models.md5sum')) {
1525 View Code Duplication
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1526
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1527
						$model = trim($row[2]);
1528
						$modelsdb[$model] = trim($row[0]);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$modelsdb was never initialized. Although not strictly required by PHP, it is generally a good practice to add $modelsdb = 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...
1529
					}
1530
				}
1531
			} else {
1532
				$modelsdb = array();
1533
			}
1534
			$diff = array_diff($newmodelsdb,$modelsdb);
0 ignored issues
show
Bug introduced by
The variable $modelsdb 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...
1535
			foreach ($diff as $key => $value) {
1536
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1537
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1538
				
1539
			}
1540
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1541
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1542
		if ($error != '') {
1543
			return $error;
1544
		} elseif ($globalDebug) echo "Done\n";
1545
		return '';
1546
	}
1547
1548
	public static function update_aircraft() {
1549
		global $tmp_dir, $globalDebug;
1550
		date_default_timezone_set('UTC');
1551
		$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...
1552
		/*
1553
		if ($globalDebug) echo "Aircrafts : Download...";
1554
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1555
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1556
		//$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);
1557
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1558
//		echo strlen($data_req);
1559
		echo $data;
1560
		*/
1561
		if (file_exists($tmp_dir.'aircrafts.html')) {
1562
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1563
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1564
		    $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...
1565
		    //echo $result;
1566
		    //var_dump(str_get_html($result));
1567
		    //print_r(self::table2array($result));
1568
		}
1569
1570
	}
1571
	
1572
	public static function update_notam() {
1573
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1574
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1575
		$Common = new Common();
1576
		date_default_timezone_set('UTC');
1577
		$query = 'TRUNCATE TABLE notam';
1578
		try {
1579
			$Connection = new Connection();
1580
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1581
                        $sth->execute();
1582
                } catch(PDOException $e) {
1583
                        return "error : ".$e->getMessage();
1584
                }
1585
1586
		$error = '';
1587
		if ($globalDebug) echo "Notam : Download...";
1588
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1589
		if (file_exists($tmp_dir.'notam.rss')) {
1590
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1591
			foreach ($notams['channel']['item'] as $notam) {
1592
				$title = explode(':',$notam['title']);
1593
				$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...
1594
				unset($title[0]);
1595
				$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...
1596
				$description = strip_tags($notam['description'],'<pre>');
1597
				preg_match(':^(.*?)<pre>:',$description,$match);
1598
				$q = explode('/',$match[1]);
1599
				$data['fir'] = $q[0];
1600
				$data['code'] = $q[1];
1601
				$ifrvfr = $q[2];
1602
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1603
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1604
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1605
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1606
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1607
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1608
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1609
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1610
				//$data['scope'] = $q[4];
1611
				$data['lower_limit'] = $q[5];
1612
				$data['upper_limit'] = $q[6];
1613
				$latlonrad = $q[7];
1614
				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...
1615
				$latitude = $Common->convertDec($las,'latitude');
1616
				$longitude = $Common->convertDec($lns,'longitude');
1617
				if ($lac == 'S') $latitude = '-'.$latitude;
1618
				if ($lnc == 'W') $longitude = '-'.$longitude;
1619
				$data['center_latitude'] = $latitude;
1620
				$data['center_longitude'] = $longitude;
1621
				$data['radius'] = intval($radius);
1622
				
1623
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1624
				$data['text'] = $match[1];
1625
				preg_match(':</pre>(.*?)$:',$description,$match);
1626
				$fromto = $match[1];
1627
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1628
				$fromall = trim($match[1]);
1629
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1630
				$from = trim($match[1]);
1631
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1632
				preg_match('#TO:(.*?)$#',$fromto,$match);
1633
				$toall = trim($match[1]);
1634
				if (!preg_match(':Permanent:',$toall)) {
1635
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1636
					$to = trim($match[1]);
1637
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1638
					$data['permanent'] = 0;
1639
				} else {
1640
				    $data['date_end'] = NULL;
1641
				    $data['permanent'] = 1;
1642
				}
1643
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1644
				$NOTAM = new NOTAM();
1645
				$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']);
1646
				unset($data);
1647
			} 
1648
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1649
		if ($error != '') {
1650
			return $error;
1651
		} elseif ($globalDebug) echo "Done\n";
1652
		return '';
1653
	}
1654
	
1655 View Code Duplication
	public static function check_last_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1656
		global $globalDBdriver;
1657
		if ($globalDBdriver == 'mysql') {
1658
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1659
		} else {
1660
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1661
		}
1662
		try {
1663
			$Connection = new Connection();
1664
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1665
                        $sth->execute();
1666
                } catch(PDOException $e) {
1667
                        return "error : ".$e->getMessage();
1668
                }
1669
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1670
                if ($row['nb'] > 0) return false;
1671
                else return true;
1672
	}
1673
1674 View Code Duplication
	public static function insert_last_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1675
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1676
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1677
		try {
1678
			$Connection = new Connection();
1679
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1680
                        $sth->execute();
1681
                } catch(PDOException $e) {
1682
                        return "error : ".$e->getMessage();
1683
                }
1684
	}
1685
1686 View Code Duplication
	public static function check_last_notam_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1687
		global $globalDBdriver;
1688
		if ($globalDBdriver == 'mysql') {
1689
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)";
1690
		} else {
1691
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
1692
		}
1693
		try {
1694
			$Connection = new Connection();
1695
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1696
                        $sth->execute();
1697
                } catch(PDOException $e) {
1698
                        return "error : ".$e->getMessage();
1699
                }
1700
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1701
                if ($row['nb'] > 0) return false;
1702
                else return true;
1703
	}
1704
1705 View Code Duplication
	public static function insert_last_notam_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1706
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
1707
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
1708
		try {
1709
			$Connection = new Connection();
1710
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1711
                        $sth->execute();
1712
                } catch(PDOException $e) {
1713
                        return "error : ".$e->getMessage();
1714
                }
1715
	}
1716
1717 View Code Duplication
	public static function check_last_owner_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1718
		global $globalDBdriver;
1719
		if ($globalDBdriver == 'mysql') {
1720
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1721
		} else {
1722
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1723
		}
1724
		try {
1725
			$Connection = new Connection();
1726
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1727
                        $sth->execute();
1728
                } catch(PDOException $e) {
1729
                        return "error : ".$e->getMessage();
1730
                }
1731
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1732
                if ($row['nb'] > 0) return false;
1733
                else return true;
1734
	}
1735
1736 View Code Duplication
	public static function insert_last_owner_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1737
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
1738
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
1739
		try {
1740
			$Connection = new Connection();
1741
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1742
                        $sth->execute();
1743
                } catch(PDOException $e) {
1744
                        return "error : ".$e->getMessage();
1745
                }
1746
	}
1747 View Code Duplication
	public static function check_last_schedules_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1748
		global $globalDBdriver;
1749
		if ($globalDBdriver == 'mysql') {
1750
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1751
		} else {
1752
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1753
		}
1754
		try {
1755
			$Connection = new Connection();
1756
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1757
                        $sth->execute();
1758
                } catch(PDOException $e) {
1759
                        return "error : ".$e->getMessage();
1760
                }
1761
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1762
                if ($row['nb'] > 0) return false;
1763
                else return true;
1764
	}
1765
1766 View Code Duplication
	public static function insert_last_schedules_update() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1767
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
1768
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
1769
		try {
1770
			$Connection = new Connection();
1771
			$sth = $Connection->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare 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...
1772
                        $sth->execute();
1773
                } catch(PDOException $e) {
1774
                        return "error : ".$e->getMessage();
1775
                }
1776
	}
1777
	
1778
	public static function update_all() {
1779
		echo update_db::update_routes();
1780
		echo update_db::update_ModeS();
1781
		echo update_db::update_ModeS_flarm();
1782
		echo update_db::update_ModeS_ogn();
1783
		echo update_db::update_translation();
1784
		echo update_db::update_translation_fam();
1785
	}
1786
}
1787
1788
//echo update_db::update_airports();
1789
//echo update_db::translation();
1790
//echo update_db::update_waypoints();
1791
//echo update_db::update_airspace();
1792
//echo update_db::update_notam();
1793
//echo update_db::update_ivao();
1794
//echo update_db::update_ModeS_flarm();
1795
//echo update_db::update_ModeS_ogn();
1796
//echo update_db::update_aircraft();
1797
//$update_db = new update_db();
1798
//echo $update_db->update_owner();
1799
//update_db::update_translation_fam();
1800
//echo update_db::update_routes();
1801
//update_db::update_models();
1802
//echo $update_db::update_skyteam();
1803
?>
1 ignored issue
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
1804