Completed
Push — master ( 825d36...6c3bce )
by Yannick
06:25
created

Connection::check_schema_version()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 5
nop 0
dl 0
loc 20
rs 9.2
c 0
b 0
f 0
1
<?php
2
require_once(dirname(__FILE__).'/settings.php');
3
4
class Connection{
5
	public $db = null;
6
	public $dbs = array();
7
	public $latest_schema = 23;
8
	
9
	public function __construct($dbc = null,$dbname = null,$user = null,$pass = null) {
10
	    global $globalDBdriver;
11
	    if ($dbc === null) {
12
		if ($this->db === null && $dbname === null) {
13
		    if ($user === null && $pass === null) {
14
			$this->createDBConnection();
15
		    } else {
16
			$this->createDBConnection(null,$user,$pass);
17
		    }
18
		} else {
19
		    $this->createDBConnection($dbname);
20
		}
21
	    } elseif ($dbname === null || $dbname === 'default') {
22
		$this->db = $dbc;
23
		if ($this->connectionExists() === false) {
24
			/*
25
			echo 'Restart Connection !!!'."\n";
26
			$e = new \Exception;
27
			var_dump($e->getTraceAsString());
28
			*/
29
			$this->createDBConnection();
30
		}
31
	    } else {
32
		//$this->connectionExists();
33
		$this->dbs[$dbname] = $dbc;
34
	    }
35
	}
36
37
	public function db() {
38
		return $this->db;
39
	}
40
41
	/**
42
	* Creates the database connection
43
	*
44
	* @return Boolean of the database connection
45
	*
46
	*/
47
48
	public function createDBConnection($DBname = null, $user = null, $pass = null)
49
	{
50
		global $globalDBdriver, $globalDBhost, $globalDBuser, $globalDBpass, $globalDBname, $globalDebug, $globalDB, $globalDBport, $globalDBTimeOut, $globalDBretry, $globalDBPersistent;
51
		if ($DBname === null) {
52
			if ($user === null && $pass === null) {
53
				$DBname = 'default';
54
				$globalDBSdriver = $globalDBdriver;
55
				$globalDBShost = $globalDBhost;
56
				$globalDBSname = $globalDBname;
57
				$globalDBSuser = $globalDBuser;
58
				$globalDBSpass = $globalDBpass;
59 View Code Duplication
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
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...
60
				else $globalDBSport = $globalDBport;
61
			} else {
62
				$DBname = 'default';
63
				$globalDBSdriver = $globalDBdriver;
64
				$globalDBShost = $globalDBhost;
65
				$globalDBSname = $globalDBname;
66
				$globalDBSuser = $user;
67
				$globalDBSpass = $pass;
68 View Code Duplication
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
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...
69
				else $globalDBSport = $globalDBport;
70
			}
71
		} else {
72
			$globalDBSdriver = $globalDB[$DBname]['driver'];
73
			$globalDBShost = $globalDB[$DBname]['host'];
74
			$globalDBSname = $globalDB[$DBname]['name'];
75
			$globalDBSuser = $globalDB[$DBname]['user'];
76
			$globalDBSpass = $globalDB[$DBname]['pass'];
77
			if (isset($globalDB[$DBname]['port'])) $globalDBSport = $globalDB[$DBname]['port'];
78
			else $globalDBSport = 3306;
79
		}
80
		// Set number of try to connect to DB
81
		if (!isset($globalDBretry) || $globalDBretry == '' || $globalDBretry === NULL) $globalDBretry = 5;
82
		$i = 0;
83
		while (true) {
84
			try {
85
				if ($globalDBSdriver == 'mysql') {
86
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;charset=utf8", $globalDBSuser,  $globalDBSpass);
87
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
88
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
89
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
90 View Code Duplication
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,200);
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...
91
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
92 View Code Duplication
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
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...
93
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
94
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
95
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
96
					// Workaround against "ONLY_FULL_GROUP_BY" mode
97
					// to enable it : $this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY"');
98
					$this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"');
99
				} else {
100
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;options='--client_encoding=utf8'", $globalDBSuser,  $globalDBSpass);
101
					//$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
102
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
103
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
104 View Code Duplication
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,200);
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...
105
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
106 View Code Duplication
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
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...
107
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
108
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
109
				}
110
				break;
111
			} catch(PDOException $e) {
112
				$i++;
113
				if (isset($globalDebug) && $globalDebug) echo $e->getMessage()."\n";
114
				//exit;
115
				if ($i > $globalDBretry) return false;
116
				//return false;
117
			}
118
		}
119
		if ($DBname === 'default') $this->db = $this->dbs['default'];
120
		return true;
121
	}
122
123
	public function tableExists($table)
124
	{
125
		global $globalDBdriver, $globalDBname;
126
		if ($globalDBdriver == 'mysql') {
127
			$query = "SHOW TABLES LIKE '".$table."'";
128
		} elseif ($globalDBdriver == 'pgsql') {
129
			$query = "SELECT * FROM pg_catalog.pg_tables WHERE tablename = '".$table."'";
130
		}
131
		if ($this->db == NULL) return false;
132
		try {
133
			//$Connection = new Connection();
134
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The variable $query 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...
Bug introduced by
The method query cannot be called on $this->db (of type null).

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

Loading history...
135
		} catch(PDOException $e) {
136
			return false;
137
		}
138
		if($results->rowCount()>0) {
139
		    return true; 
140
		}
141
		else return false;
142
	}
143
144
	public function connectionExists()
145
	{
146
		global $globalDBdriver, $globalDBCheckConnection;
147
		if (isset($globalDBCheckConnection) && $globalDBCheckConnection === FALSE) return true;
148
		$query = "SELECT 1 + 1";
149
		if ($this->db == NULL) return false;
150
		try {
151
			$sum = @$this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->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...
152
			if ($sum instanceof \PDOStatement) {
153
				$sum = $sum->fetchColumn(0);
154
			} else $sum = 0;
155
			if (intval($sum) !== 2) {
156
			     return false;
157
			}
158
			
159
		} catch(PDOException $e) {
160
			if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
161
            			throw $e;
162
	                }
163
	                //echo 'error ! '.$e->getMessage();
164
			return false;
165
		}
166
		return true; 
167
	}
168
169
	/*
170
	* Check if index exist
171
	*/
172
	public function indexExists($table,$index)
173
	{
174
		global $globalDBdriver, $globalDBname;
175
		if ($globalDBdriver == 'mysql') {
176
			$query = "SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='".$table."' AND index_name='".$index."'";
177
		} elseif ($globalDBdriver == 'pgsql') {
178
			$query = "SELECT 1 FROM   pg_class c JOIN   pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '".$index."' AND n.nspname = '".$table."'";
179
		}
180
		try {
181
			//$Connection = new Connection();
182
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->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...
Bug introduced by
The variable $query 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...
183
		} catch(PDOException $e) {
184
			return false;
185
		}
186
		if($results->rowCount()>0) {
187
		    return true; 
188
		}
189
		else return false;
190
	}
191
192
	/*
193
	* Get columns name of a table
194
	* @return Array all column name in table
195
	*/
196
	public function getColumnName($table)
197
	{
198
		$query = "SELECT * FROM ".$table." LIMIT 0";
199
		try {
200
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->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...
201
		} catch(PDOException $e) {
202
			return "error : ".$e->getMessage()."\n";
203
		}
204
		$columns = array();
205
		$colcnt = $results->columnCount();
206 View Code Duplication
		for ($i = 0; $i < $colcnt; $i++) {
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...
207
			$col = $results->getColumnMeta($i);
208
			$columns[] = $col['name'];
209
		}
210
		return $columns;
211
	}
212
213
	/*
214
	* Check if a column name exist in a table
215
	* @return Boolean column exist or not
216
	*/
217
	public function checkColumnName($table,$name)
218
	{
219
		$query = "SELECT * FROM ".$table." LIMIT 0";
220
		try {
221
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->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...
222
		} catch(PDOException $e) {
223
			return "error : ".$e->getMessage()."\n";
224
		}
225
		$colcnt = $results->columnCount();
226 View Code Duplication
		for ($i = 0; $i < $colcnt; $i++) {
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...
227
			$col = $results->getColumnMeta($i);
228
			if ($name == $col['name']) return true;
229
		}
230
		return false;
231
	}
232
233
	/*
234
	* Get schema version
235
	* @return integer schema version
236
	*/
237
	public function check_schema_version() {
238
		$version = 0;
239
		if ($this->tableExists('aircraft')) {
240
			if (!$this->tableExists('config')) {
241
	    			$version = '1';
242
	    			return $version;
243
			} else {
244
				$Connection = new Connection();
0 ignored issues
show
Unused Code introduced by
$Connection 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...
245
				$query = "SELECT value FROM config WHERE name = 'schema_version' LIMIT 1";
246
				try {
247
					$sth = $this->db->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare cannot be called on $this->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...
248
					$sth->execute();
249
				} catch(PDOException $e) {
250
					return "error : ".$e->getMessage()."\n";
251
				}
252
				$result = $sth->fetch(PDO::FETCH_ASSOC);
253
				return $result['value'];
254
			}
255
		} else return $version;
256
	}
257
	
258
	/*
259
	* Check if schema version is latest_schema
260
	* @return Boolean if latest version or not
261
	*/
262
	public function latest() {
263
	    if ($this->check_schema_version() == $this->latest_schema) return true;
264
	    else return false;
265
	}
266
267
}
268
?>
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...
269