Completed
Push — master ( 3474b8...2a4221 )
by Yannick
08:49
created

Connection::db()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 5
nop 0
dl 0
loc 15
rs 8.8571
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 = 37;
8
	
9
	public function __construct($dbc = null,$dbname = null,$user = null,$pass = null) {
10
	    global $globalDBdriver, $globalNoDB;
11
	    if (isset($globalNoDB) && $globalNoDB === TRUE) {
12
		$this->db = null;
13
	    } else {
14
		if ($dbc === null) {
15
		    if ($this->db === null && $dbname === null) {
16
			if ($user === null && $pass === null) {
17
			    $this->createDBConnection();
18
			} else {
19
			    $this->createDBConnection(null,$user,$pass);
20
			}
21
		    } else {
22
			$this->createDBConnection($dbname);
23
		    }
24
		} elseif ($dbname === null || $dbname === 'default') {
25
	    	    $this->db = $dbc;
26
	    	    if ($this->connectionExists() === false) {
27
			/*
28
			echo 'Restart Connection !!!'."\n";
29
			$e = new \Exception;
30
			var_dump($e->getTraceAsString());
31
			*/
32
			$this->createDBConnection();
33
		    }
34
		} else {
35
		    //$this->connectionExists();
36
		    $this->dbs[$dbname] = $dbc;
37
		}
38
	    }
39
	}
40
41
	public function db() {
42
		if (isset($globalNoDB) && $globalNoDB === TRUE) {
0 ignored issues
show
Bug introduced by
The variable $globalNoDB seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
43
			return null;
44
		} else {
45
			if ($this->db === null) {
46
				$this->__construct();
47
			}
48
			if ($this->db === null) {
49
				echo 'Can\'t connect to database. Check configuration and database status.';
50
				die;
51
			} else {
52
				return $this->db;
53
			}
54
		}
55
	}
56
57
	/**
58
	* Creates the database connection
59
	*
60
	* @return Boolean of the database connection
61
	*
62
	*/
63
64
	public function createDBConnection($DBname = null, $user = null, $pass = null)
65
	{
66
		global $globalDBdriver, $globalDBhost, $globalDBuser, $globalDBpass, $globalDBname, $globalDebug, $globalDB, $globalDBport, $globalDBTimeOut, $globalDBretry, $globalDBPersistent;
67
		if ($DBname === null) {
68
			if ($user === null && $pass === null) {
69
				$DBname = 'default';
70
				$globalDBSdriver = $globalDBdriver;
71
				$globalDBShost = $globalDBhost;
72
				$globalDBSname = $globalDBname;
73
				$globalDBSuser = $globalDBuser;
74
				$globalDBSpass = $globalDBpass;
75
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
76
				else $globalDBSport = $globalDBport;
77
			} else {
78
				$DBname = 'default';
79
				$globalDBSdriver = $globalDBdriver;
80
				$globalDBShost = $globalDBhost;
81
				$globalDBSname = $globalDBname;
82
				$globalDBSuser = $user;
83
				$globalDBSpass = $pass;
84
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
85
				else $globalDBSport = $globalDBport;
86
			}
87
		} else {
88
			$globalDBSdriver = $globalDB[$DBname]['driver'];
89
			$globalDBShost = $globalDB[$DBname]['host'];
90
			$globalDBSname = $globalDB[$DBname]['name'];
91
			$globalDBSuser = $globalDB[$DBname]['user'];
92
			$globalDBSpass = $globalDB[$DBname]['pass'];
93
			if (isset($globalDB[$DBname]['port'])) $globalDBSport = $globalDB[$DBname]['port'];
94
			else $globalDBSport = 3306;
95
		}
96
		// Set number of try to connect to DB
97
		if (!isset($globalDBretry) || $globalDBretry == '' || $globalDBretry === NULL) $globalDBretry = 5;
98
		$i = 0;
99
		while (true) {
100
			try {
101
				if ($globalDBSdriver == 'mysql') {
102
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;charset=utf8", $globalDBSuser,  $globalDBSpass);
103
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
104
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
105
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
106
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,500);
107
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
108
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
109
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
110
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
111
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
112
					// Workaround against "ONLY_FULL_GROUP_BY" mode
113
					// to enable it : $this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY"');
114
					$this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"');
115
					// Force usage of UTC
116
					$this->dbs[$DBname]->exec('SET SESSION time_zone = "+00:00"');
117
					//$this->dbs[$DBname]->exec('SET @@session.time_zone = "+00:00"');
118
				} else {
119
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;options='--client_encoding=utf8'", $globalDBSuser,  $globalDBSpass);
120
					//$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
121
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
122
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
123
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,200);
124
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
125
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
126
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
127
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
128
					$this->dbs[$DBname]->exec('SET timezone="UTC"');
129
				}
130
				break;
131
			} catch(PDOException $e) {
132
				$i++;
133
				if (isset($globalDebug) && $globalDebug) echo 'Error connecting to DB: '.$globalDBSname.' - Error: '.$e->getMessage()."\n";
134
				//exit;
135
				if ($i > $globalDBretry) return false;
136
				//return false;
137
			}
138
		}
139
		if ($DBname === 'default') $this->db = $this->dbs['default'];
140
		return true;
141
	}
142
143
	public function tableExists($table)
144
	{
145
		global $globalDBdriver, $globalDBname;
146
		if ($globalDBdriver == 'mysql') {
147
			$query = "SHOW TABLES LIKE '".$table."'";
148
		} else {
149
			$query = "SELECT * FROM pg_catalog.pg_tables WHERE tablename = '".$table."'";
150
		}
151
		if ($this->db == NULL) return false;
152
		try {
153
			//$Connection = new Connection();
154
			$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...
155
		} catch(PDOException $e) {
156
			return false;
157
		}
158
		if($results->rowCount()>0) {
159
		    return true; 
160
		}
161
		else return false;
162
	}
163
164
	public function connectionExists()
165
	{
166
		global $globalDBdriver, $globalDBCheckConnection;
167
		if (isset($globalDBCheckConnection) && $globalDBCheckConnection === FALSE) return true;
168
		$query = "SELECT 1 + 1";
169
		if ($this->db === null) return false;
170
		try {
171
			$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...
172
			if ($sum instanceof \PDOStatement) {
173
				$sum = $sum->fetchColumn(0);
174
			} else $sum = 0;
175
			if (intval($sum) !== 2) {
176
			     return false;
177
			}
178
			
179
		} catch(PDOException $e) {
180
			if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
181
            			throw $e;
182
	                }
183
	                //echo 'error ! '.$e->getMessage();
184
			return false;
185
		}
186
		return true; 
187
	}
188
189
	/*
190
	* Check if index exist
191
	*/
192
	public function indexExists($table,$index)
193
	{
194
		global $globalDBdriver, $globalDBname;
195
		if ($globalDBdriver == 'mysql') {
196
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='".$table."' AND index_name='".$index."'";
197
		} else {
198
			$query = "SELECT count(*) as nb FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '".$index."' AND n.nspname = '".$table."'";
199
		}
200
		try {
201
			//$Connection = new Connection();
202
			$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...
203
		} catch(PDOException $e) {
204
			return false;
205
		}
206
		$nb = $results->fetchAll(PDO::FETCH_ASSOC);
207
		if($nb[0]['nb'] > 0) {
208
			return true; 
209
		}
210
		else return false;
211
	}
212
213
	/*
214
	* Get columns name of a table
215
	* @return Array all column name in table
216
	*/
217
	public function getColumnName($table)
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
		$columns = array();
226
		$colcnt = $results->columnCount();
227
		for ($i = 0; $i < $colcnt; $i++) {
228
			$col = $results->getColumnMeta($i);
229
			$columns[] = $col['name'];
230
		}
231
		return $columns;
232
	}
233
234
	public function getColumnType($table,$column) {
235
		$select = $this->db->query('SELECT '.$column.' FROM '.$table);
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...
236
		$tomet = $select->getColumnMeta(0);
237
		return $tomet['native_type'];
238
	}
239
240
	/*
241
	* Check if a column name exist in a table
242
	* @return Boolean column exist or not
243
	*/
244
	public function checkColumnName($table,$name)
245
	{
246
		global $globalDBdriver, $globalDBname;
247
		if ($globalDBdriver == 'mysql') {
248
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name LIMIT 1";
249
		} else {
250
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name LIMIT 1";
251
		}
252
			try {
253
				$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...
254
				$sth->execute(array(':database' => $globalDBname,':table' => $table,':name' => $name));
255
			} catch(PDOException $e) {
256
				echo "error : ".$e->getMessage()."\n";
257
			}
258
			$result = $sth->fetch(PDO::FETCH_ASSOC);
259
			$sth->closeCursor();
260
			if ($result['nb'] > 0) return true;
261
			else return false;
262
/*		} else {
263
			$query = "SELECT * FROM ".$table." LIMIT 0";
264
			try {
265
				$results = $this->db->query($query);
266
			} catch(PDOException $e) {
267
				return "error : ".$e->getMessage()."\n";
268
			}
269
			$colcnt = $results->columnCount();
270
			for ($i = 0; $i < $colcnt; $i++) {
271
				$col = $results->getColumnMeta($i);
272
				if ($name == $col['name']) return true;
273
			}
274
			return false;
275
		}
276
*/
277
	}
278
279
	/*
280
	* Get schema version
281
	* @return integer schema version
282
	*/
283
	public function check_schema_version() {
284
		$version = 0;
285
		if ($this->tableExists('aircraft')) {
286
			if (!$this->tableExists('config')) {
287
	    			$version = '1';
288
	    			return $version;
289
			} else {
290
				$query = "SELECT value FROM config WHERE name = 'schema_version' LIMIT 1";
291
				try {
292
					$sth = $this->db->prepare($query);
293
					$sth->execute();
294
				} catch(PDOException $e) {
295
					return "error : ".$e->getMessage()."\n";
296
				}
297
				$result = $sth->fetch(PDO::FETCH_ASSOC);
298
				$sth->closeCursor();
299
				return $result['value'];
300
			}
301
		} else return $version;
302
	}
303
	
304
	/*
305
	* Check if schema version is latest_schema
306
	* @return Boolean if latest version or not
307
	*/
308
	public function latest() {
309
	    global $globalNoDB;
310
	    if (isset($globalNoDB) && $globalNoDB === TRUE) return true;
311
	    if ($this->check_schema_version() == $this->latest_schema) return true;
312
	    else return false;
313
	}
314
315
}
316
?>
317