Completed
Push — master ( 8b39c3...091523 )
by Yannick
09:33
created

update_db::update_airspace()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 30
Code Lines 23

Duplication

Lines 9
Ratio 30 %

Importance

Changes 0
Metric Value
cc 5
eloc 23
nc 10
nop 0
dl 9
loc 30
rs 8.439
c 0
b 0
f 0
1
<?php
2
//require_once('libs/simple_html_dom.php');
3
require(dirname(__FILE__).'/../require/settings.php');
4
require_once(dirname(__FILE__).'/../require/class.Common.php');
5
require_once(dirname(__FILE__).'/../require/class.Connection.php');
6
7
$tmp_dir = dirname(__FILE__).'/tmp/';
8
//$globalDebug = true;
9
//$globalTransaction = true;
10
class update_db {
11
	public static $db_sqlite;
12
13
	public static function download($url, $file, $referer = '') {
14
		$fp = fopen($file, 'w+');
15
		$ch = curl_init();
16
		curl_setopt($ch, CURLOPT_URL, $url);
17
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
18
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
19
		if ($referer != '') curl_setopt($ch, CURLOPT_REFERER, $referer);
20
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
21
		curl_setopt($ch, CURLOPT_FILE, $fp);
22
		$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
	public static function retrieve_modes_sqlite_to_dest($database_file) {
107
		global $globalTransaction;
108
		//$query = 'TRUNCATE TABLE aircraft_modes';
109
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
110
		try {
111
			$Connection = new Connection();
112
			$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...
113
                        $sth->execute(array(':source' => $database_file));
114
                } catch(PDOException $e) {
115
                        return "error : ".$e->getMessage();
116
                }
117
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
118
		try {
119
			$Connection = new Connection();
120
			$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...
121
                        $sth->execute(array(':source' => $database_file));
122
                } catch(PDOException $e) {
123
                        return "error : ".$e->getMessage();
124
                }
125
126
    		update_db::connect_sqlite($database_file);
127
		$query = 'select * from Aircraft';
128
		try {
129
                        $sth = update_db::$db_sqlite->prepare($query);
130
                        $sth->execute();
131
                } catch(PDOException $e) {
132
                        return "error : ".$e->getMessage();
133
                }
134
		//$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)';
135
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
136
		
137
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
138
		
139
		$Connection = new Connection();
140
		$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...
141
		$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...
142
		try {
143
			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...
144
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
145
			//$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']);
146
				if ($values['UserString4'] == 'M') $type = 'military';
147
				else $type = null;
148
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
149
				$sth_dest->execute($query_dest_values);
150
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
151
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
152
				    $sth_dest_owner->execute($query_dest_owner_values);
153
				}
154
            		}
155
			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...
156
		} catch(PDOException $e) {
157
			return "error : ".$e->getMessage();
158
		}
159
160
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
161
		try {
162
			$Connection = new Connection();
163
			$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...
164
                        $sth->execute(array(':source' => $database_file));
165
                } catch(PDOException $e) {
166
                        return "error : ".$e->getMessage();
167
                }
168
		return '';
169
	}
170
171
	public static function retrieve_modes_flarmnet($database_file) {
172
		global $globalTransaction;
173
		$Common = new Common();
174
		//$query = 'TRUNCATE TABLE aircraft_modes';
175
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
176
		try {
177
			$Connection = new Connection();
178
			$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...
179
                        $sth->execute(array(':source' => $database_file));
180
                } catch(PDOException $e) {
181
                        return "error : ".$e->getMessage();
182
                }
183
		
184
		if ($fh = fopen($database_file,"r")) {
185
			//$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)';
186
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
187
		
188
			$Connection = new Connection();
189
			$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...
190
			try {
191
				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...
192
            			while (!feof($fh)) {
193
            				$line = $Common->hex2str(fgets($fh,9999));
194
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
195
            				$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...
196
            				$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...
197
            				$aircraft_name = trim(substr($line,48,6));
198
            				// Check if we can find ICAO, else set it to GLID
199
            				$aircraft_name_split = explode(' ',$aircraft_name);
200
            				$search_more = '';
201 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...
202
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
203
            				$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...
204
					try {
205
                                    		$sth_search->execute();
206
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
207
	            				//if (count($result) > 0) {
208 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...
209
	            				    $values['ICAOTypeCode'] = $result['icao'];
210
	            				} 
211
					} catch(PDOException $e) {
212
						return "error : ".$e->getMessage();
213
					}
214
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
215
					// Add data to db
216 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...
217
						//$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']);
218
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
219
						//print_r($query_dest_values);
220
						$sth_dest->execute($query_dest_values);
221
					}
222
				}
223
				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...
224
			} catch(PDOException $e) {
225
				return "error : ".$e->getMessage();
226
			}
227
		}
228
229
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
230
		try {
231
			$Connection = new Connection();
232
			$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...
233
                        $sth->execute(array(':source' => $database_file));
234
                } catch(PDOException $e) {
235
                        return "error : ".$e->getMessage();
236
                }
237
		return '';
238
	}
239
240
	public static function retrieve_modes_ogn($database_file) {
241
		global $globalTransaction;
242
		//$query = 'TRUNCATE TABLE aircraft_modes';
243
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
244
		try {
245
			$Connection = new Connection();
246
			$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...
247
                        $sth->execute(array(':source' => $database_file));
248
                } catch(PDOException $e) {
249
                        return "error : ".$e->getMessage();
250
                }
251
		
252
		if ($fh = fopen($database_file,"r")) {
253
			//$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)';
254
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
255
		
256
			$Connection = new Connection();
257
			$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...
258
			try {
259
				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...
260
				$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...
261
            			while (!feof($fh)) {
262
            				$line = fgetcsv($fh,9999,',',"'");
263
            				
264
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
265
					//print_r($line);
266
            				$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...
267
            				$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...
268
            				$aircraft_name = $line[2];
269
            				// Check if we can find ICAO, else set it to GLID
270
            				$aircraft_name_split = explode(' ',$aircraft_name);
271
            				$search_more = '';
272 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...
273
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
274
            				$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...
275
					try {
276
                                    		$sth_search->execute();
277
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
278 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...
279
					} catch(PDOException $e) {
280
						return "error : ".$e->getMessage();
281
					}
282
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
283
					// Add data to db
284 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...
285
						//$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']);
286
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
287
						//print_r($query_dest_values);
288
						$sth_dest->execute($query_dest_values);
289
					}
290
				}
291
				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...
292
			} catch(PDOException $e) {
293
				return "error : ".$e->getMessage();
294
			}
295
		}
296
297
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
298
		try {
299
			$Connection = new Connection();
300
			$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...
301
                        $sth->execute(array(':source' => $database_file));
302
                } catch(PDOException $e) {
303
                        return "error : ".$e->getMessage();
304
                }
305
		return '';
306
	}
307
308
	public static function retrieve_owner($database_file,$country = 'F') {
309
		global $globalTransaction;
310
		//$query = 'TRUNCATE TABLE aircraft_modes';
311
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
312
		try {
313
			$Connection = new Connection();
314
			$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...
315
                        $sth->execute(array(':source' => $database_file));
316
                } catch(PDOException $e) {
317
                        return "error : ".$e->getMessage();
318
                }
319
		
320
		if ($fh = fopen($database_file,"r")) {
321
			//$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)';
322
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
323
		
324
			$Connection = new Connection();
325
			$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...
326
			try {
327
				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...
328
				$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...
329
            			while (!feof($fh)) {
330
            				$line = fgetcsv($fh,9999,',','"');
331
            				//print_r($line);
332
            				if ($country == 'F') {
333
            				    $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...
334
            				    $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...
335
            				    $values['owner'] = $line[5];
336
            				    if ($line[6] == '') $values['date_first_reg'] = null;
337
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
338
					    $values['cancel'] = $line[7];
339 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...
340
					    // TODO : add modeS & reg to aircraft_modes
341
            				    $values['registration'] = $line[0];
342
            				    $values['base'] = $line[3];
343
            				    $values['owner'] = $line[2];
344
            				    if ($line[1] == '') $values['date_first_reg'] = null;
345
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
346
					    $values['cancel'] = '';
347
					} elseif ($country == 'HB') {
348
					    // TODO : add modeS & reg to aircraft_modes
349
            				    $values['registration'] = $line[0];
350
            				    $values['base'] = null;
351
            				    $values['owner'] = $line[5];
352
            				    $values['date_first_reg'] = null;
353
					    $values['cancel'] = '';
354 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...
355
					    // TODO : add modeS & reg to aircraft_modes
356
            				    $values['registration'] = $line[3];
357
            				    $values['base'] = null;
358
            				    $values['owner'] = $line[5];
359
            				    if ($line[18] == '') $values['date_first_reg'] = null;
360
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
361
					    $values['cancel'] = '';
362
					} elseif ($country == 'VH') {
363
					    // TODO : add modeS & reg to aircraft_modes
364
            				    $values['registration'] = $line[0];
365
            				    $values['base'] = null;
366
            				    $values['owner'] = $line[12];
367
            				    if ($line[28] == '') $values['date_first_reg'] = null;
368
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
369
370
					    $values['cancel'] = $line[39];
371
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
372
            				    $values['registration'] = $line[0];
373
            				    $values['base'] = null;
374
            				    $values['owner'] = $line[4];
375
            				    $values['date_first_reg'] = null;
376
					    $values['cancel'] = '';
377
					} elseif ($country == 'CC') {
378
            				    $values['registration'] = $line[0];
379
            				    $values['base'] = null;
380
            				    $values['owner'] = $line[6];
381
            				    $values['date_first_reg'] = null;
382
					    $values['cancel'] = '';
383 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...
384
            				    $values['registration'] = $line[0];
385
            				    $values['base'] = null;
386
            				    $values['owner'] = $line[8];
387
            				    if ($line[7] == '') $values['date_first_reg'] = null;
388
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
389
					    $values['cancel'] = '';
390
					} elseif ($country == 'PP') {
391
            				    $values['registration'] = $line[0];
392
            				    $values['base'] = null;
393
            				    $values['owner'] = $line[4];
394
            				    if ($line[6] == '') $values['date_first_reg'] = null;
395
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
396
					    $values['cancel'] = $line[7];
397 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...
398
            				    $values['registration'] = $line[0];
399
            				    $values['base'] = null;
400
            				    $values['owner'] = $line[4];
401
            				    if ($line[5] == '') $values['date_first_reg'] = null;
402
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
403
					    $values['cancel'] = '';
404
					} elseif ($country == '8Q') {
405
            				    $values['registration'] = $line[0];
406
            				    $values['base'] = null;
407
            				    $values['owner'] = $line[3];
408
            				    if ($line[7] == '') $values['date_first_reg'] = null;
409
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
410
					    $values['cancel'] = '';
411
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
412
            				    $values['registration'] = $line[0];
413
            				    $values['base'] = null;
414
            				    $values['owner'] = $line[3];
415
            				    $values['date_first_reg'] = null;
416
					    $values['cancel'] = '';
417
					}
418
					if ($values['cancel'] == '' && $values['registration'] != null) {
419
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
420
						$sth_dest->execute($query_dest_values);
421
					}
422
				}
423
				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...
424
			} catch(PDOException $e) {
425
				return "error : ".$e->getMessage();
426
			}
427
		}
428
		return '';
429
	}
430
431
	/*
432
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
433
	*/
434
	public static function update_airports() {
435
		global $tmp_dir, $globalTransaction;
436
437
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
438
		$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...
439
		$query = '
440
		    PREFIX dbo: <http://dbpedia.org/ontology/>
441
		    PREFIX dbp: <http://dbpedia.org/property/>
442
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
443
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
444
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
445
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
446
		    FROM <http://dbpedia.org>
447
		    WHERE {
448
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
449
450
			OPTIONAL {
451
			    ?airport dbo:icaoLocationIdentifier ?icao .
452
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
453
			}
454
455
			OPTIONAL {
456
			    ?airport dbo:iataLocationIdentifier ?iata .
457
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
458
			}
459
460
			OPTIONAL {
461
			    ?airport dbo:locationIdentifier ?lid .
462
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
463
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
464
			    OPTIONAL {
465
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
466
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
467
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
468
			    }
469
			    FILTER (!bound(?other_icao))
470
			}
471
472
			OPTIONAL {
473
			    ?airport dbo:faaLocationIdentifier ?faa .
474
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
475
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
476
			    OPTIONAL {
477
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
478
				?airport_x dbo:iataLocationIdentifier ?other_iata .
479
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
480
			    }
481
			    FILTER (!bound(?other_iata))
482
			}
483
484
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
485
	
486
			OPTIONAL {
487
			    ?airport rdfs:label ?name
488
			    FILTER (lang(?name) = "en")
489
			}
490
    
491
			OPTIONAL {
492
			    ?airport foaf:homepage ?homepage
493
			}
494
		    
495
			OPTIONAL {
496
			    ?airport dbp:coordinatesRegion ?country
497
			}
498
    
499
			OPTIONAL {
500
			    ?airport dbp:type ?type
501
			}
502
			
503
			OPTIONAL {
504
			    ?airport dbo:elevation ?altitude
505
			}
506
			OPTIONAL {
507
			    ?airport dbp:image ?image
508
			}
509
510
			{
511
			    ?airport geo:lat ?latitude .
512
			    ?airport geo:long ?longitude .
513
			    FILTER (datatype(?latitude) = xsd:float)
514
			    FILTER (datatype(?longitude) = xsd:float)
515
			} UNION {
516
			    ?airport geo:lat ?latitude .
517
			    ?airport geo:long ?longitude .
518
			    FILTER (datatype(?latitude) = xsd:double)
519
			    FILTER (datatype(?longitude) = xsd:double)
520
			    OPTIONAL {
521
				?airport geo:lat ?lat_f .
522
				?airport geo:long ?long_f .
523
				FILTER (datatype(?lat_f) = xsd:float)
524
				FILTER (datatype(?long_f) = xsd:float)
525
			    }
526
			    FILTER (!bound(?lat_f) && !bound(?long_f))
527
			}
528
529
		    }
530
		    ORDER BY ?airport
531
		';
532
		$result = sparql_query($query);
533
  
534
		$query = 'TRUNCATE TABLE airport';
535
		try {
536
			$Connection = new Connection();
537
			$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...
538
                        $sth->execute();
539
                } catch(PDOException $e) {
540
                        return "error : ".$e->getMessage();
541
                }
542
543
544
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
545
		try {
546
			$Connection = new Connection();
547
			$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...
548
                        $sth->execute();
549
                } catch(PDOException $e) {
550
                        return "error : ".$e->getMessage();
551
                }
552
553
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
554
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
555
		$Connection = new Connection();
556
		$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...
557
		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...
558
  
559
		$i = 0;
560
		while($row = sparql_fetch_array($result))
561
		{
562
			if ($i >= 1) {
563
			//print_r($row);
564
			if (!isset($row['iata'])) $row['iata'] = '';
565
			if (!isset($row['icao'])) $row['icao'] = '';
566
			if (!isset($row['type'])) $row['type'] = '';
567
			if (!isset($row['altitude'])) $row['altitude'] = '';
568
			if (isset($row['city_bis'])) {
569
				$row['city'] = $row['city_bis'];
570
			}
571
			if (!isset($row['city'])) $row['city'] = '';
572
			if (!isset($row['country'])) $row['country'] = '';
573
			if (!isset($row['homepage'])) $row['homepage'] = '';
574
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
575
			if (!isset($row['name'])) continue;
576
			if (!isset($row['image'])) {
577
				$row['image'] = '';
578
				$row['image_thumb'] = '';
579
			} else {
580
				$image = str_replace(' ','_',$row['image']);
581
				$digest = md5($image);
582
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
583
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
584
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
585
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
586
			}
587
			
588
			$country = explode('-',$row['country']);
589
			$row['country'] = $country[0];
590
			
591
			$row['type'] = trim($row['type']);
592
			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'])) {
593
				$row['type'] = 'Military';
594
			} 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') {
595
				$row['type'] = 'small_airport';
596
			}
597
			
598
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
599
			$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']);
600
			//print_r($query_dest_values);
601
			
602
			try {
603
				$sth_dest->execute($query_dest_values);
604
			} catch(PDOException $e) {
605
				return "error : ".$e->getMessage();
606
			}
607
			}
608
609
			$i++;
610
		}
611
		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...
612
		echo "Delete duplicate rows...\n";
613
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
614
		try {
615
			$Connection = new Connection();
616
			$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...
617
                        $sth->execute();
618
                } catch(PDOException $e) {
619
                        return "error : ".$e->getMessage();
620
                }
621
622
623
		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...
624
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
625
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
626
		$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' => '');
627
		try {
628
			$Connection = new Connection();
629
			$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...
630
                        $sth->execute($query_values);
631
                } catch(PDOException $e) {
632
                        return "error : ".$e->getMessage();
633
                }
634
		$i++;
635
/*
636
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
637
		try {
638
			$Connection = new Connection();
639
			$sth = $Connection->db->prepare($query);
640
                        $sth->execute();
641
                } catch(PDOException $e) {
642
                        return "error : ".$e->getMessage();
643
                }
644
*/
645
646
		echo "Download data from ourairports.com...\n";
647
		$delimiter = ',';
648
		$out_file = $tmp_dir.'airports.csv';
649
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
650
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
651
		echo "Add data from ourairports.com...\n";
652
653
		$header = NULL;
654
		if (($handle = fopen($out_file, 'r')) !== FALSE)
655
		{
656
			$Connection = new Connection();
657
			//$Connection->db->beginTransaction();
658
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
659
			{
660
				if(!$header) $header = $row;
661
				else {
662
					$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...
663
					$data = array_combine($header, $row);
664
					try {
665
						$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...
666
						$sth->execute(array(':icao' => $data['gps_code']));
667
					} catch(PDOException $e) {
668
						return "error : ".$e->getMessage();
669
					}
670
					if ($sth->fetchColumn() > 0) {
671
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
672
						try {
673
							$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...
674
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
675
						} catch(PDOException $e) {
676
							return "error : ".$e->getMessage();
677
						}
678
					} else {
679
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
680
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
681
						$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']);
682
						try {
683
							$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...
684
							$sth->execute($query_values);
685
						} catch(PDOException $e) {
686
							return "error : ".$e->getMessage();
687
						}
688
						$i++;
689
					}
690
				}
691
			}
692
			fclose($handle);
693
			//$Connection->db->commit();
694
		}
695
696
		echo "Download data from another free database...\n";
697
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
698
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
699
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
700
		update_db::unzip($out_file);
701
		$header = NULL;
702
		echo "Add data from another free database...\n";
703
		$delimiter = ':';
704
		$Connection = new Connection();
705
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
706
		{
707
			//$Connection->db->beginTransaction();
708
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
709
			{
710
				if(!$header) $header = $row;
711
				else {
712
					$data = $row;
713
714
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
715
					try {
716
						$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...
717
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
718
					} catch(PDOException $e) {
719
						return "error : ".$e->getMessage();
720
					}
721
				}
722
			}
723
			fclose($handle);
724
			//$Connection->db->commit();
725
		}
726
727
		echo "Put type military for all air base";
728
		$Connection = new Connection();
729
		try {
730
			$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...
731
			$sth->execute();
732
		} catch(PDOException $e) {
733
			return "error : ".$e->getMessage();
734
		}
735
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
736
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
737
			try {
738
				$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...
739
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
740
			} catch(PDOException $e) {
741
				return "error : ".$e->getMessage();
742
			}
743
		}
744
745
746
747
                return "success";
748
	}
749
	
750
	public static function translation() {
751
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
752
		global $tmp_dir, $globalTransaction;
753
		$Spotter = new Spotter();
754
		//$out_file = $tmp_dir.'translation.zip';
755
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
756
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
757
		
758
		//$query = 'TRUNCATE TABLE translation';
759
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
760
		try {
761
			$Connection = new Connection();
762
			$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...
763
                        $sth->execute(array(':source' => 'translation.csv'));
764
                } catch(PDOException $e) {
765
                        return "error : ".$e->getMessage();
766
                }
767
768
		
769
		//update_db::unzip($out_file);
770
		$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...
771
		$delimiter = ';';
772
		$Connection = new Connection();
773
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
774
		{
775
			$i = 0;
776
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
777
			//$Connection->db->beginTransaction();
778
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
779
			{
780
				$i++;
781
				if($i > 12) {
782
					$data = $row;
783
					$operator = $data[2];
784 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...
785
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
786
                                                //echo substr($operator, 0, 2)."\n";;
787
                                                if (count($airline_array) > 0) {
788
							//print_r($airline_array);
789
							$operator = $airline_array[0]['icao'].substr($operator,2);
790
                                                }
791
                                        }
792
					
793
					$operator_correct = $data[3];
794 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...
795
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
796
                                                if (count($airline_array) > 0) {
797
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
798
                                            	}
799
                                        }
800
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
801
					try {
802
						$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...
803
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
804
					} catch(PDOException $e) {
805
						return "error : ".$e->getMessage();
806
					}
807
				}
808
			}
809
			fclose($handle);
810
			//$Connection->db->commit();
811
		}
812
		return '';
813
        }
814
	
815
	public static function translation_fam() {
816
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
817
		global $tmp_dir, $globalTransaction;
818
		$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...
819
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
820
		try {
821
			$Connection = new Connection();
822
			$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...
823
                        $sth->execute(array(':source' => 'website_fam'));
824
                } catch(PDOException $e) {
825
                        return "error : ".$e->getMessage();
826
                }
827
828
		
829
		//update_db::unzip($out_file);
830
		$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...
831
		$delimiter = "\t";
832
		$Connection = new Connection();
833
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
834
		{
835
			$i = 0;
836
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
837
			//$Connection->db->beginTransaction();
838
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
839
			{
840
				if ($i > 0) {
841
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
842
					try {
843
						$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...
844
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
845
					} catch(PDOException $e) {
846
						return "error : ".$e->getMessage();
847
					}
848
				}
849
				$i++;
850
			}
851
			fclose($handle);
852
			//$Connection->db->commit();
853
		}
854
		return '';
855
        }
856
857
	/**
858
        * Convert a HTML table to an array
859
        * @param String $data HTML page
860
        * @return Array array of the tables in HTML page
861
        */
862
        private static function table2array($data) {
1 ignored issue
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
863
                $html = str_get_html($data);
864
                $tabledata=array();
865 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...
866
                {
867
                        $td = array();
868
                        foreach( $element->find('th') as $row)
869
                        {
870
                                $td [] = trim($row->plaintext);
871
                        }
872
                        $td=array_filter($td);
873
                        $tabledata[] = $td;
874
875
                        $td = array();
876
                        $tdi = array();
877
                        foreach( $element->find('td') as $row)
878
                        {
879
                                $td [] = trim($row->plaintext);
880
                                $tdi [] = trim($row->innertext);
881
                        }
882
                        $td=array_filter($td);
883
                        $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...
884
                    //    $tabledata[]=array_merge($td,$tdi);
885
                        $tabledata[]=$td;
886
                }
887
                return(array_filter($tabledata));
888
        }
889
890
       /**
891
        * Get data from form result
892
        * @param String $url form URL
893
        * @return String the result
894
        */
895
        private static function getData($url) {
1 ignored issue
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
896
                $ch = curl_init();
897
                curl_setopt($ch, CURLOPT_URL, $url);
898
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
899
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
900
                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');
901
                return curl_exec($ch);
902
        }
903
/*
904
	public static function waypoints() {
905
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
906
		$table = update_db::table2array($data);
907
//		print_r($table);
908
		$query = 'TRUNCATE TABLE waypoints';
909
		try {
910
			$Connection = new Connection();
911
			$sth = $Connection->db->prepare($query);
912
                        $sth->execute();
913
                } catch(PDOException $e) {
914
                        return "error : ".$e->getMessage();
915
                }
916
917
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
918
		$Connection = new Connection();
919
		$sth_dest = $Connection->db->prepare($query_dest);
920
		$Connection->db->beginTransaction();
921
                foreach ($table as $row) {
922
            		if ($row[0] != 'Ident') {
923
				$ident = $row[0];
924
				$latitude = $row[2];
925
				$longitude = $row[3];
926
				$control = $row[4];
927
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
928
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
929
				try {
930
					$sth_dest->execute($query_dest_values);
931
				} catch(PDOException $e) {
932
					return "error : ".$e->getMessage();
933
				}
934
			}
935
                }
936
		$Connection->db->commit();
937
938
	}
939
*/
940
	public static function waypoints($filename) {
941
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
942
		global $tmp_dir, $globalTransaction;
943
		//$Spotter = new Spotter();
944
		//$out_file = $tmp_dir.'translation.zip';
945
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
946
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
947
		$Connection = new Connection();
948
		//update_db::unzip($out_file);
949
		$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...
950
		$delimiter = ' ';
951
		if (($handle = fopen($filename, 'r')) !== FALSE)
952
		{
953
			$i = 0;
954
			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...
955
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
956
			{
957
				$i++;
958
				if($i > 3 && count($row) > 2) {
959
					$data = array_values(array_filter($row));
960
					$cntdata = count($data);
961
					if ($cntdata > 10) {
962
						$value = $data[9];
963
						
964
						for ($i =10;$i < $cntdata;$i++) {
965
							$value .= ' '.$data[$i];
966
						}
967
						$data[9] = $value;
968
					}
969
					//print_r($data);
970
					if (count($data) > 9) {
971
						$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)';
972
						try {
973
							$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...
974
							$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]));
975
						} catch(PDOException $e) {
976
							return "error : ".$e->getMessage();
977
						}
978
					}
979
				}
980
			}
981
			fclose($handle);
982
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

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

Loading history...
983
		}
984
		return '';
985
        }
986
987
	public static function ivao_airlines($filename) {
988
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
989
		global $tmp_dir, $globalTransaction;
990
		$query = 'TRUNCATE TABLE airlines';
991
		try {
992
			$Connection = new Connection();
993
			$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...
994
                        $sth->execute();
995
                } catch(PDOException $e) {
996
                        return "error : ".$e->getMessage();
997
                }
998
999
		$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...
1000
		$delimiter = ':';
1001
		$Connection = new Connection();
1002
		if (($handle = fopen($filename, 'r')) !== FALSE)
1003
		{
1004
			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...
1005
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1006
			{
1007
				if(count($row) > 1) {
1008
					$query = "INSERT INTO airlines (name,icao,active) VALUES (:name, :icao, 'Y')";
1009
					try {
1010
						$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...
1011
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1012
					} catch(PDOException $e) {
1013
						return "error : ".$e->getMessage();
1014
					}
1015
				}
1016
			}
1017
			fclose($handle);
1018
			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...
1019
		}
1020
		return '';
1021
        }
1022
	
1023
	public static function update_airspace() {
1024
		global $tmp_dir, $globalDBdriver;
1025
		include_once('class.create_db.php');
1026
		$Connection = new Connection();
1027 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...
1028
			$query = 'DROP TABLE airspace';
1029
			try {
1030
				$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...
1031
                    		$sth->execute();
1032
	                } catch(PDOException $e) {
1033
				return "error : ".$e->getMessage();
1034
	                }
1035
	        }
1036
1037
1038
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1039
		else {
1040
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1041
			$query = "CREATE EXTENSION postgis";
1042
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1043
			try {
1044
				$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...
1045
				$sth->execute();
1046
			} catch(PDOException $e) {
1047
				return "error : ".$e->getMessage();
1048
			}
1049
		}
1050
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1051
		return $error;
1052
	}
1053
1054
	public static function update_vatsim() {
1055
		global $tmp_dir;
1056
		include_once('class.create_db.php');
1057
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1058
		return $error;
1059
	}
1060
	
1061
	public static function update_countries() {
1062
		global $tmp_dir, $globalDBdriver;
1063
		include_once('class.create_db.php');
1064
		$Connection = new Connection();
1065 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...
1066
			$query = 'DROP TABLE countries';
1067
			try {
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
    	                	echo "error : ".$e->getMessage();
1072
	                }
1073
		}
1074
		if ($globalDBdriver == 'mysql') {
1075
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1076
		} else {
1077
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1078
		}
1079
		$error = create_db::import_file($tmp_dir.'countries.sql');
1080
		return $error;
1081
	}
1082
1083
	
1084
	public static function update_waypoints() {
1085
		global $tmp_dir;
1086
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1087
//		update_db::unzip($tmp_dir.'AptNav.zip');
1088
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1089
//		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');
1090
		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');
1091
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1092
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1093
		return $error;
1094
	}
1095
1096
	public static function update_ivao() {
1097
		global $tmp_dir, $globalDebug;
1098
		$Common = new Common();
1099
		$error = '';
1100
		//Direct download forbidden
1101
		//if ($globalDebug) echo "IVAO : Download...";
1102
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1103
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1104
			if ($globalDebug) echo "Unzip...";
1105
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1106
			if ($globalDebug) echo "Add to DB...";
1107
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1108
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1109
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1110
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1111
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1112
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1113
		if ($error != '') {
1114
			return $error;
1115
		} elseif ($globalDebug) echo "Done\n";
1116
		return '';
1117
	}
1118
1119 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...
1120
		global $tmp_dir, $globalDebug;
1121
		$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...
1122
		if ($globalDebug) echo "Routes : Download...";
1123
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1124
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1125
			if ($globalDebug) echo "Gunzip...";
1126
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1127
			if ($globalDebug) echo "Add to DB...";
1128
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1129
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1130
		if ($error != '') {
1131
			return $error;
1132
		} elseif ($globalDebug) echo "Done\n";
1133
		return '';
1134
	}
1135 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...
1136
		global $tmp_dir, $globalDebug;
1137
/*
1138
		if ($globalDebug) echo "Modes : Download...";
1139
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1140
		if ($globalDebug) echo "Unzip...";
1141
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1142
		if ($globalDebug) echo "Add to DB...";
1143
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1144
		if ($error != true) {
1145
			echo $error;
1146
			exit;
1147
		} elseif ($globalDebug) echo "Done\n";
1148
*/
1149
		if ($globalDebug) echo "Modes : Download...";
1150
		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1151
		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1152
			if ($globalDebug) echo "Unzip...";
1153
			update_db::unzip($tmp_dir.'basestation_latest.zip');
1154
			if ($globalDebug) echo "Add to DB...";
1155
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1156
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1157
		if ($error != '') {
1158
			return $error;
1159
		} elseif ($globalDebug) echo "Done\n";
1160
		return '';
1161
	}
1162
1163 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...
1164
		global $tmp_dir, $globalDebug;
1165
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1166
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1167
		if (file_exists($tmp_dir.'data.fln')) {
1168
			if ($globalDebug) echo "Add to DB...";
1169
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1170
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1171
		if ($error != '') {
1172
			return $error;
1173
		} elseif ($globalDebug) echo "Done\n";
1174
		return '';
1175
	}
1176
1177 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...
1178
		global $tmp_dir, $globalDebug;
1179
		if ($globalDebug) echo "Modes OGN: Download...";
1180
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1181
		if (file_exists($tmp_dir.'ogn.csv')) {
1182
			if ($globalDebug) echo "Add to DB...";
1183
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1184
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1185
		if ($error != '') {
1186
			return $error;
1187
		} elseif ($globalDebug) echo "Done\n";
1188
		return '';
1189
	}
1190
1191
	public static function update_owner() {
1192
		global $tmp_dir, $globalDebug;
1193
		
1194
		if ($globalDebug) echo "Owner France: Download...";
1195
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1196 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...
1197
			if ($globalDebug) echo "Add to DB...";
1198
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1199
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1200
		if ($error != '') {
1201
			return $error;
1202
		} elseif ($globalDebug) echo "Done\n";
1203
		
1204
		if ($globalDebug) echo "Owner Ireland: Download...";
1205
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1206 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...
1207
			if ($globalDebug) echo "Add to DB...";
1208
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1209
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1210
		if ($error != '') {
1211
			return $error;
1212
		} elseif ($globalDebug) echo "Done\n";
1213
		if ($globalDebug) echo "Owner Switzerland: Download...";
1214
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1215 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...
1216
			if ($globalDebug) echo "Add to DB...";
1217
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1218
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1219
		if ($error != '') {
1220
			return $error;
1221
		} elseif ($globalDebug) echo "Done\n";
1222
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1223
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1224 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...
1225
			if ($globalDebug) echo "Add to DB...";
1226
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1227
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1228
		if ($error != '') {
1229
			return $error;
1230
		} elseif ($globalDebug) echo "Done\n";
1231
		if ($globalDebug) echo "Owner Australia: Download...";
1232
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1233 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...
1234
			if ($globalDebug) echo "Add to DB...";
1235
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1236
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1237
		if ($error != '') {
1238
			return $error;
1239
		} elseif ($globalDebug) echo "Done\n";
1240
		if ($globalDebug) echo "Owner Austria: Download...";
1241
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1242 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...
1243
			if ($globalDebug) echo "Add to DB...";
1244
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1245
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1246
		if ($error != '') {
1247
			return $error;
1248
		} elseif ($globalDebug) echo "Done\n";
1249
		if ($globalDebug) echo "Owner Chile: Download...";
1250
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1251 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...
1252
			if ($globalDebug) echo "Add to DB...";
1253
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1254
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1255
		if ($error != '') {
1256
			return $error;
1257
		} elseif ($globalDebug) echo "Done\n";
1258
		if ($globalDebug) echo "Owner Colombia: Download...";
1259
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1260 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...
1261
			if ($globalDebug) echo "Add to DB...";
1262
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1263
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1264
		if ($error != '') {
1265
			return $error;
1266
		} elseif ($globalDebug) echo "Done\n";
1267
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1268
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1269 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...
1270
			if ($globalDebug) echo "Add to DB...";
1271
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1272
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1273
		if ($error != '') {
1274
			return $error;
1275
		} elseif ($globalDebug) echo "Done\n";
1276
		if ($globalDebug) echo "Owner Brazil: Download...";
1277
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1278 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...
1279
			if ($globalDebug) echo "Add to DB...";
1280
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1281
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1282
		if ($error != '') {
1283
			return $error;
1284
		} elseif ($globalDebug) echo "Done\n";
1285
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1286
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1287 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...
1288
			if ($globalDebug) echo "Add to DB...";
1289
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1290
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1291
		if ($error != '') {
1292
			return $error;
1293
		} elseif ($globalDebug) echo "Done\n";
1294
		if ($globalDebug) echo "Owner Croatia: Download...";
1295
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1296 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...
1297
			if ($globalDebug) echo "Add to DB...";
1298
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1299
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1300
		if ($error != '') {
1301
			return $error;
1302
		} elseif ($globalDebug) echo "Done\n";
1303
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1304
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1305 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...
1306
			if ($globalDebug) echo "Add to DB...";
1307
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1308
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1309
		if ($error != '') {
1310
			return $error;
1311
		} elseif ($globalDebug) echo "Done\n";
1312
		if ($globalDebug) echo "Owner Maldives: Download...";
1313
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1314 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...
1315
			if ($globalDebug) echo "Add to DB...";
1316
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1317
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1318
		if ($error != '') {
1319
			return $error;
1320
		} elseif ($globalDebug) echo "Done\n";
1321
		if ($globalDebug) echo "Owner New Zealand: Download...";
1322
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1323 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...
1324
			if ($globalDebug) echo "Add to DB...";
1325
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1326
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1327
		if ($error != '') {
1328
			return $error;
1329
		} elseif ($globalDebug) echo "Done\n";
1330
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1331
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1332 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...
1333
			if ($globalDebug) echo "Add to DB...";
1334
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1335
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1336
		if ($error != '') {
1337
			return $error;
1338
		} elseif ($globalDebug) echo "Done\n";
1339
		if ($globalDebug) echo "Owner Slovakia: Download...";
1340
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1341 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...
1342
			if ($globalDebug) echo "Add to DB...";
1343
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1344
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1345
		if ($error != '') {
1346
			return $error;
1347
		} elseif ($globalDebug) echo "Done\n";
1348
		if ($globalDebug) echo "Owner Ecuador: Download...";
1349
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1350 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...
1351
			if ($globalDebug) echo "Add to DB...";
1352
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1353
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1354
		if ($error != '') {
1355
			return $error;
1356
		} elseif ($globalDebug) echo "Done\n";
1357
		if ($globalDebug) echo "Owner Iceland: Download...";
1358
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1359 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...
1360
			if ($globalDebug) echo "Add to DB...";
1361
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1362
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1363
		if ($error != '') {
1364
			return $error;
1365
		} elseif ($globalDebug) echo "Done\n";
1366
		return '';
1367
	}
1368
1369 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...
1370
		global $tmp_dir, $globalDebug;
1371
		$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...
1372
		if ($globalDebug) echo "Translation : Download...";
1373
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1374
		if (file_exists($tmp_dir.'translation.zip')) {
1375
			if ($globalDebug) echo "Unzip...";
1376
			update_db::unzip($tmp_dir.'translation.zip');
1377
			if ($globalDebug) echo "Add to DB...";
1378
			$error = update_db::translation();
1379
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1380
		if ($error != '') {
1381
			return $error;
1382
		} elseif ($globalDebug) echo "Done\n";
1383
		return '';
1384
	}
1385
1386 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...
1387
		global $tmp_dir, $globalDebug;
1388
		$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...
1389
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1390
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1391
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1392
			if ($globalDebug) echo "Gunzip...";
1393
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1394
			if ($globalDebug) echo "Add to DB...";
1395
			$error = update_db::translation_fam();
1396
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1397
		if ($error != '') {
1398
			return $error;
1399
		} elseif ($globalDebug) echo "Done\n";
1400
		return '';
1401
	}
1402
1403
	public static function update_models() {
1404
		global $tmp_dir, $globalDebug;
1405
		$error = '';
1406
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1407
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1408
		if (file_exists($tmp_dir.'models.md5sum')) {
1409
			if ($globalDebug) echo "Check files...\n";
1410
			$newmodelsdb = array();
1411 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...
1412
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1413
					$model = trim($row[2]);
1414
					$newmodelsdb[$model] = trim($row[0]);
1415
				}
1416
			}
1417
			if (file_exists('../models/models.md5sum')) {
1418 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...
1419
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1420
						$model = trim($row[2]);
1421
						$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...
1422
					}
1423
				}
1424
			} else {
1425
				$modelsdb = array();
1426
			}
1427
			$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...
1428
			foreach ($diff as $key => $value) {
1429
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1430
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1431
				
1432
			}
1433
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1434
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1435
		if ($error != '') {
1436
			return $error;
1437
		} elseif ($globalDebug) echo "Done\n";
1438
		return '';
1439
	}
1440
1441
	public static function update_aircraft() {
1442
		global $tmp_dir, $globalDebug;
1443
		date_default_timezone_set('UTC');
1444
		$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...
1445
		/*
1446
		if ($globalDebug) echo "Aircrafts : Download...";
1447
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1448
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1449
		//$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);
1450
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1451
//		echo strlen($data_req);
1452
		echo $data;
1453
		*/
1454
		if (file_exists($tmp_dir.'aircrafts.html')) {
1455
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1456
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1457
		    $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...
1458
		    //echo $result;
1459
		    //var_dump(str_get_html($result));
1460
		    //print_r(self::table2array($result));
1461
		}
1462
1463
	}
1464
	
1465
	public static function update_notam() {
1466
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1467
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1468
		$Common = new Common();
1469
		date_default_timezone_set('UTC');
1470
		$query = 'TRUNCATE TABLE notam';
1471
		try {
1472
			$Connection = new Connection();
1473
			$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...
1474
                        $sth->execute();
1475
                } catch(PDOException $e) {
1476
                        return "error : ".$e->getMessage();
1477
                }
1478
1479
		$error = '';
1480
		if ($globalDebug) echo "Notam : Download...";
1481
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1482
		if (file_exists($tmp_dir.'notam.rss')) {
1483
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1484
			foreach ($notams['channel']['item'] as $notam) {
1485
				$title = explode(':',$notam['title']);
1486
				$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...
1487
				unset($title[0]);
1488
				$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...
1489
				$description = strip_tags($notam['description'],'<pre>');
1490
				preg_match(':^(.*?)<pre>:',$description,$match);
1491
				$q = explode('/',$match[1]);
1492
				$data['fir'] = $q[0];
1493
				$data['code'] = $q[1];
1494
				$ifrvfr = $q[2];
1495
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1496
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1497
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1498
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1499
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1500
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1501
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1502
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1503
				//$data['scope'] = $q[4];
1504
				$data['lower_limit'] = $q[5];
1505
				$data['upper_limit'] = $q[6];
1506
				$latlonrad = $q[7];
1507
				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...
1508
				$latitude = $Common->convertDec($las,'latitude');
1509
				$longitude = $Common->convertDec($lns,'longitude');
1510
				if ($lac == 'S') $latitude = '-'.$latitude;
1511
				if ($lnc == 'W') $longitude = '-'.$longitude;
1512
				$data['center_latitude'] = $latitude;
1513
				$data['center_longitude'] = $longitude;
1514
				$data['radius'] = intval($radius);
1515
				
1516
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1517
				$data['text'] = $match[1];
1518
				preg_match(':</pre>(.*?)$:',$description,$match);
1519
				$fromto = $match[1];
1520
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1521
				$fromall = trim($match[1]);
1522
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1523
				$from = trim($match[1]);
1524
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1525
				preg_match('#TO:(.*?)$#',$fromto,$match);
1526
				$toall = trim($match[1]);
1527
				if (!preg_match(':Permanent:',$toall)) {
1528
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1529
					$to = trim($match[1]);
1530
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1531
					$data['permanent'] = 0;
1532
				} else {
1533
				    $data['date_end'] = NULL;
1534
				    $data['permanent'] = 1;
1535
				}
1536
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1537
				$NOTAM = new NOTAM();
1538
				$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']);
1539
				unset($data);
1540
			} 
1541
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1542
		if ($error != '') {
1543
			return $error;
1544
		} elseif ($globalDebug) echo "Done\n";
1545
		return '';
1546
	}
1547
	
1548 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...
1549
		global $globalDBdriver;
1550
		if ($globalDBdriver == 'mysql') {
1551
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1552
		} else {
1553
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1554
		}
1555
		try {
1556
			$Connection = new Connection();
1557
			$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...
1558
                        $sth->execute();
1559
                } catch(PDOException $e) {
1560
                        return "error : ".$e->getMessage();
1561
                }
1562
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1563
                if ($row['nb'] > 0) return false;
1564
                else return true;
1565
	}
1566
1567
	public static function insert_last_update() {
1568
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1569
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1570
		try {
1571
			$Connection = new Connection();
1572
			$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...
1573
                        $sth->execute();
1574
                } catch(PDOException $e) {
1575
                        return "error : ".$e->getMessage();
1576
                }
1577
	}
1578
1579 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...
1580
		global $globalDBdriver;
1581
		if ($globalDBdriver == 'mysql') {
1582
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)";
1583
		} else {
1584
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
1585
		}
1586
		try {
1587
			$Connection = new Connection();
1588
			$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...
1589
                        $sth->execute();
1590
                } catch(PDOException $e) {
1591
                        return "error : ".$e->getMessage();
1592
                }
1593
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1594
                if ($row['nb'] > 0) return false;
1595
                else return true;
1596
	}
1597
1598
	public static function insert_last_notam_update() {
1599
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
1600
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
1601
		try {
1602
			$Connection = new Connection();
1603
			$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...
1604
                        $sth->execute();
1605
                } catch(PDOException $e) {
1606
                        return "error : ".$e->getMessage();
1607
                }
1608
	}
1609
1610 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...
1611
		global $globalDBdriver;
1612
		if ($globalDBdriver == 'mysql') {
1613
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(DATE(NOW()), INTERVAL 15 DAY)";
1614
		} else {
1615
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1616
		}
1617
		try {
1618
			$Connection = new Connection();
1619
			$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...
1620
                        $sth->execute();
1621
                } catch(PDOException $e) {
1622
                        return "error : ".$e->getMessage();
1623
                }
1624
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1625
                if ($row['nb'] > 0) return false;
1626
                else return true;
1627
	}
1628
1629
	public static function insert_last_owner_update() {
1630
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
1631
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
1632
		try {
1633
			$Connection = new Connection();
1634
			$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...
1635
                        $sth->execute();
1636
                } catch(PDOException $e) {
1637
                        return "error : ".$e->getMessage();
1638
                }
1639
	}
1640
	
1641
	public static function update_all() {
1642
		echo update_db::update_routes();
1643
		echo update_db::update_ModeS();
1644
		echo update_db::update_ModeS_flarm();
1645
		echo update_db::update_ModeS_ogn();
1646
		echo update_db::update_translation();
1647
		echo update_db::update_translation_fam();
1648
	}
1649
}
1650
1651
//echo update_db::update_airports();
1652
//echo update_db::translation();
1653
//echo update_db::update_waypoints();
1654
//echo update_db::update_airspace();
1655
//echo update_db::update_notam();
1656
//echo update_db::update_ivao();
1657
//echo update_db::update_ModeS_flarm();
1658
//echo update_db::update_ModeS_ogn();
1659
//echo update_db::update_aircraft();
1660
//$update_db = new update_db();
1661
//echo $update_db->update_owner();
1662
//update_db::update_translation_fam();
1663
//echo update_db::update_routes();
1664
//update_db::update_models();
1665
?>
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...
1666