Completed
Push — master ( d8c574...a11679 )
by Yannick
07:12
created

Connection::__construct()   D

Complexity

Conditions 9
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 9
eloc 16
c 1
b 1
f 0
nc 6
nop 4
dl 0
loc 27
rs 4.909
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
			/*
1 ignored issue
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
25
			echo 'Restart Connection !!!'."\n";
26
			$e = new \Exception;
27
			var_dump($e->getTraceAsString());
28
			*/
29
			$this->createDBConnection();
30
		}
31
	    } else {
32
		//$this->connectionExists();
1 ignored issue
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
		$this->dbs[$dbname] = $dbc;
34
	    }
35
	}
36
37
38
	/**
39
	* Creates the database connection
40
	*
41
	* @return Boolean of the database connection
42
	*
43
	*/
44
45
	public function createDBConnection($DBname = null, $user = null, $pass = null)
46
	{
47
		global $globalDBdriver, $globalDBhost, $globalDBuser, $globalDBpass, $globalDBname, $globalDebug, $globalDB, $globalDBport, $globalDBTimeOut, $globalDBretry, $globalDBPersistent;
48
		if ($DBname === null) {
49
			if ($user === null && $pass === null) {
50
				$DBname = 'default';
51
				$globalDBSdriver = $globalDBdriver;
52
				$globalDBShost = $globalDBhost;
53
				$globalDBSname = $globalDBname;
54
				$globalDBSuser = $globalDBuser;
55
				$globalDBSpass = $globalDBpass;
56 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...
57
				else $globalDBSport = intval($globalDBport);
58
			} else {
59
				$DBname = 'default';
60
				$globalDBSdriver = $globalDBdriver;
61
				$globalDBShost = $globalDBhost;
62
				$globalDBSname = $globalDBname;
63
				$globalDBSuser = $user;
64
				$globalDBSpass = $pass;
65 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...
66
				else $globalDBSport = intval($globalDBport);
67
			}
68
		} else {
69
			$globalDBSdriver = $globalDB[$DBname]['driver'];
70
			$globalDBShost = $globalDB[$DBname]['host'];
71
			$globalDBSname = $globalDB[$DBname]['name'];
72
			$globalDBSuser = $globalDB[$DBname]['user'];
73
			$globalDBSpass = $globalDB[$DBname]['pass'];
74
			if (isset($globalDB[$DBname]['port'])) $globalDBSport = intval($globalDB[$DBname]['port']);
75
			else $globalDBSport = 3306;
76
		}
77
		// Set number of try to connect to DB
78
		if (!isset($globalDBretry) || $globalDBretry == '' || $globalDBretry === NULL) $globalDBretry = 5;
79
		$i = 0;
80
		while (true) {
81
			try {
82
				if ($globalDBSdriver == 'mysql') {
83
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;charset=utf8", $globalDBSuser,  $globalDBSpass);
84
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
85
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
86
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
87 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...
88
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
89 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...
90
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
91
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
92
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
93
					// Workaround against "ONLY_FULL_GROUP_BY" mode
94
					// to enable it : $this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY"');
1 ignored issue
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
95
					$this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"');
96
				} else {
97
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;options='--client_encoding=utf8'", $globalDBSuser,  $globalDBSpass);
98
					//$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
1 ignored issue
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
99
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
100
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
101 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...
102
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
103 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...
104
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
105
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
106
				}
107
				break;
108
			} catch(PDOException $e) {
109
				$i++;
110
				if (isset($globalDebug) && $globalDebug) echo $e->getMessage()."\n";
111
				//exit;
112
				if ($i > $globalDBretry) return false;
113
				//return false;
114
			}
115
		}
116
		if ($DBname === 'default') $this->db = $this->dbs['default'];
117
		return true;
118
	}
119
120
	public function tableExists($table)
121
	{
122
		global $globalDBdriver, $globalDBname;
123
		if ($globalDBdriver == 'mysql') {
124
			$query = "SHOW TABLES LIKE '".$table."'";
125
		} elseif ($globalDBdriver == 'pgsql') {
126
			$query = "SELECT * FROM pg_catalog.pg_tables WHERE tablename = '".$table."'";
127
		}
128
		if ($this->db == NULL) return false;
129
		try {
130
			//$Connection = new Connection();
1 ignored issue
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
131
			$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...
132
		} catch(PDOException $e) {
133
			return false;
134
		}
135
		if($results->rowCount()>0) {
136
		    return true; 
137
		}
138
		else return false;
139
	}
140
141
	public function connectionExists()
142
	{
143
		global $globalDBdriver, $globalDBCheckConnection;
144
		if (isset($globalDBCheckConnection) && $globalDBCheckConnection === FALSE) return true;
145
		$query = "SELECT 1 + 1";
146
		if ($this->db == NULL) return false;
147
		try {
148
			$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...
149
			if ($sum instanceof \PDOStatement) {
150
				$sum = $sum->fetchColumn(0);
151
			} else $sum = 0;
152
			if (intval($sum) !== 2) {
153
			     return false;
154
			}
155
			
156
		} catch(PDOException $e) {
157
			if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
158
            			throw $e;
159
	                }
160
	                //echo 'error ! '.$e->getMessage();
1 ignored issue
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
161
			return false;
162
		}
163
		return true; 
164
	}
165
166
	/*
167
	* Check if index exist
168
	*/
169
	public function indexExists($table,$index)
170
	{
171
		global $globalDBdriver, $globalDBname;
172
		if ($globalDBdriver == 'mysql') {
173
			$query = "SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='".$table."' AND index_name='".$index."'";
174
		} elseif ($globalDBdriver == 'pgsql') {
175
			$query = "SELECT 1 FROM   pg_class c JOIN   pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '".$index."' AND n.nspname = '".$table."'";
176
		}
177
		try {
178
			//$Connection = new Connection();
1 ignored issue
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
179
			$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...
180
		} catch(PDOException $e) {
181
			return false;
182
		}
183
		if($results->rowCount()>0) {
184
		    return true; 
185
		}
186
		else return false;
187
	}
188
189
	/*
190
	* Get columns name of a table
191
	* @return Array all column name in table
192
	*/
193
	public function getColumnName($table)
194
	{
195
		$query = "SELECT * FROM ".$table." LIMIT 0";
196
		try {
197
			$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...
198
		} catch(PDOException $e) {
199
			return "error : ".$e->getMessage()."\n";
200
		}
201
		$columns = array();
202
		$colcnt = $results->columnCount();
203 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...
204
			$col = $results->getColumnMeta($i);
205
			$columns[] = $col['name'];
206
		}
207
		return $columns;
208
	}
209
210
	/*
211
	* Check if a column name exist in a table
212
	* @return Boolean column exist or not
213
	*/
214
	public function checkColumnName($table,$name)
215
	{
216
		$query = "SELECT * FROM ".$table." LIMIT 0";
217
		try {
218
			$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...
219
		} catch(PDOException $e) {
220
			return "error : ".$e->getMessage()."\n";
221
		}
222
		$colcnt = $results->columnCount();
223 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...
224
			$col = $results->getColumnMeta($i);
225
			if ($name == $col['name']) return true;
226
		}
227
		return false;
228
	}
229
230
	/*
231
	* Get schema version
232
	* @return integer schema version
233
	*/
234
	public function check_schema_version() {
235
		$version = 0;
236
		if ($this->tableExists('aircraft')) {
237
			if (!$this->tableExists('config')) {
238
	    			$version = '1';
239
	    			return $version;
240
			} else {
241
				$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...
242
				$query = "SELECT value FROM config WHERE name = 'schema_version' LIMIT 1";
243
				try {
244
					$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...
245
					$sth->execute();
246
				} catch(PDOException $e) {
247
					return "error : ".$e->getMessage()."\n";
248
				}
249
				$result = $sth->fetch(PDO::FETCH_ASSOC);
250
				return $result['value'];
251
			}
252
		} else return $version;
253
	}
254
	
255
	/*
256
	* Check if schema version is latest_schema
257
	* @return Boolean if latest version or not
258
	*/
259
	public function latest() {
260
	    if ($this->check_schema_version() == $this->latest_schema) return true;
261
	    else return false;
262
	}
263
264
}
265
?>
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...
266