Passed
Push — master ( 2a5ce0...65bdac )
by Alxarafe
23:02
created
dolibarr/htdocs/core/db/mssql.class.php 1 patch
Spacing   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 use Alxarafe\Helpers\Debug;
32 32
 
33 33
 //require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
34
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
34
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
35 35
 
36 36
 /**
37 37
  *	Classe de gestion de la database de dolibarr
@@ -39,15 +39,15 @@  discard block
 block discarded – undo
39 39
 class DoliDBMssql extends DoliDB
40 40
 {
41 41
 	//! Database type
42
-	public $type='mssql';
42
+	public $type = 'mssql';
43 43
 	//! Database label
44
-	const LABEL='MSSQL';
44
+	const LABEL = 'MSSQL';
45 45
 	//! Charset used to force charset when creating database
46
-	var $forcecharset='latin1';      // Can't be static as it may be forced with a dynamic value
46
+	var $forcecharset = 'latin1'; // Can't be static as it may be forced with a dynamic value
47 47
 	//! Collate used to force collate when creating database
48
-	var $forcecollate='latin1_swedish_ci';      // Can't be static as it may be forced with a dynamic value
48
+	var $forcecollate = 'latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value
49 49
 	//! Version min database
50
-	const VERSIONMIN='2000';
50
+	const VERSIONMIN = '2000';
51 51
 	/** @var resource Resultset of last query */
52 52
 	private $_results;
53 53
 
@@ -62,30 +62,30 @@  discard block
 block discarded – undo
62 62
 	 *	@param	    string	$name		Nom de la database
63 63
 	 *	@param	    int		$port		Port of database server
64 64
      */
65
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
65
+	function __construct($type, $host, $user, $pass, $name = '', $port = 0)
66 66
 	{
67 67
 		global $langs;
68 68
 
69
-		$this->database_user=$user;
70
-        $this->database_host=$host;
71
-        $this->database_port=$port;
72
-		$this->transaction_opened=0;
69
+		$this->database_user = $user;
70
+        $this->database_host = $host;
71
+        $this->database_port = $port;
72
+		$this->transaction_opened = 0;
73 73
 
74
-		if (! function_exists("mssql_connect"))
74
+		if (!function_exists("mssql_connect"))
75 75
 		{
76 76
 			$this->connected = false;
77 77
 			$this->ok = false;
78
-			$this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
79
-			dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP",LOG_ERR);
78
+			$this->error = "Mssql PHP functions for using MSSql driver are not available in this version of PHP";
79
+			dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP", LOG_ERR);
80 80
 			return $this->ok;
81 81
 		}
82 82
 
83
-		if (! $host)
83
+		if (!$host)
84 84
 		{
85 85
 			$this->connected = false;
86 86
 			$this->ok = false;
87
-			$this->error=$langs->trans("ErrorWrongHostParameter");
88
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
87
+			$this->error = $langs->trans("ErrorWrongHostParameter");
88
+			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters", LOG_ERR);
89 89
 			return $this->ok;
90 90
 		}
91 91
 
@@ -103,8 +103,8 @@  discard block
 block discarded – undo
103 103
 			// host, login ou password incorrect
104 104
 			$this->connected = false;
105 105
 			$this->ok = false;
106
-			$this->error=mssql_get_last_message();
107
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error,LOG_ERR);
106
+			$this->error = mssql_get_last_message();
107
+			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error, LOG_ERR);
108 108
 		}
109 109
 
110 110
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
 				$this->database_selected = false;
122 122
 				$this->database_name = '';
123 123
 				$this->ok = false;
124
-				$this->error=$this->error();
125
-				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
124
+				$this->error = $this->error();
125
+				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error, LOG_ERR);
126 126
 			}
127 127
 		}
128 128
 		else
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
142 142
      *  @return    string   		SQL request line converted
143 143
      */
144
-	static function convertSQLFromMysql($line,$type='ddl')
144
+	static function convertSQLFromMysql($line, $type = 'ddl')
145 145
 	{
146 146
 		return $line;
147 147
 	}
@@ -170,25 +170,25 @@  discard block
 block discarded – undo
170 170
 	 *	@return		false|resource|true	Database access handler
171 171
 	 *	@see		close
172 172
 	 */
173
-	function connect($host, $login, $passwd, $name, $port=0)
173
+	function connect($host, $login, $passwd, $name, $port = 0)
174 174
 	{
175 175
 		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
176
-		$newhost=$host;
177
-		if ($port) $newhost.=':'.$port;
178
-		$this->db  = @mssql_connect($newhost, $login, $passwd);
176
+		$newhost = $host;
177
+		if ($port) $newhost .= ':'.$port;
178
+		$this->db = @mssql_connect($newhost, $login, $passwd);
179 179
 		//force les enregistrement en latin1 si la base est en utf8 par defaut
180 180
 		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
181 181
 		// les nouvelles version de Dolibarr car force par l'install Dolibarr.
182 182
 		//$this->query('SET NAMES '.$this->forcecharset);
183 183
 		//print "Resultat fonction connect: ".$this->db;
184
-		$set_options=array('SET ANSI_PADDING ON;',
184
+		$set_options = array('SET ANSI_PADDING ON;',
185 185
 		    "SET ANSI_NULLS ON;",
186 186
 		    "SET ANSI_WARNINGS ON;",
187 187
 		    "SET ARITHABORT ON;",
188 188
 		    "SET CONCAT_NULL_YIELDS_NULL ON;",
189 189
 		    "SET QUOTED_IDENTIFIER ON;"
190 190
 		);
191
-		mssql_query(implode(' ',$set_options),$this->db);
191
+		mssql_query(implode(' ', $set_options), $this->db);
192 192
 
193 193
 		return $this->db;
194 194
 	}
@@ -200,10 +200,10 @@  discard block
 block discarded – undo
200 200
 	 */
201 201
 	function getVersion()
202 202
 	{
203
-		$resql=$this->query("SELECT @@VERSION");
203
+		$resql = $this->query("SELECT @@VERSION");
204 204
 		if ($resql)
205 205
 		{
206
-            $version=$this->fetch_array($resql);
206
+            $version = $this->fetch_array($resql);
207 207
             return $version['computed'];
208 208
 		}
209 209
 		else return '';
@@ -229,8 +229,8 @@  discard block
 block discarded – undo
229 229
     {
230 230
         if ($this->db)
231 231
         {
232
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
233
-          $this->connected=false;
232
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
233
+          $this->connected = false;
234 234
           return mssql_close($this->db);
235 235
         }
236 236
         return false;
@@ -245,16 +245,16 @@  discard block
 block discarded – undo
245 245
 	function begin()
246 246
 	{
247 247
 
248
-	    $res=mssql_query('select @@TRANCOUNT');
249
-	    $this->transaction_opened=mssql_result($res, 0, 0);
248
+	    $res = mssql_query('select @@TRANCOUNT');
249
+	    $this->transaction_opened = mssql_result($res, 0, 0);
250 250
 
251 251
 	    if ($this->transaction_opened == 0)
252 252
 		{
253 253
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
254
-			$ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
254
+			$ret = mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;", $this->db);
255 255
 			if ($ret)
256 256
 			{
257
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
257
+				dol_syslog("BEGIN Transaction", LOG_DEBUG);
258 258
 			}
259 259
 			return $ret;
260 260
 		}
@@ -270,18 +270,18 @@  discard block
 block discarded – undo
270 270
      * @param	string	$log        Add more log to default log line
271 271
      * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
272 272
 	 */
273
-	function commit($log='')
273
+	function commit($log = '')
274 274
 	{
275
-	    $res=mssql_query('select @@TRANCOUNT');
276
-	    $this->transaction_opened=mssql_result($res, 0, 0);
275
+	    $res = mssql_query('select @@TRANCOUNT');
276
+	    $this->transaction_opened = mssql_result($res, 0, 0);
277 277
 
278 278
 		if ($this->transaction_opened == 1)
279 279
 		{
280 280
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
281
-			$ret=mssql_query("COMMIT TRANSACTION",$this->db);
281
+			$ret = mssql_query("COMMIT TRANSACTION", $this->db);
282 282
 			if ($ret)
283 283
 			{
284
-				dol_syslog("COMMIT Transaction",LOG_DEBUG);
284
+				dol_syslog("COMMIT Transaction", LOG_DEBUG);
285 285
 				return true;
286 286
 			}
287 287
 			else
@@ -303,15 +303,15 @@  discard block
 block discarded – undo
303 303
 	 * @param	string	$log	Add more log to default log line
304 304
 	 * @return	bool             true si annulation ok ou transaction non ouverte, false en cas d'erreur
305 305
 	 */
306
-	function rollback($log='')
306
+	function rollback($log = '')
307 307
 	{
308
-	    $res=mssql_query('select @@TRANCOUNT');
309
-	    $this->transaction_opened=mssql_result($res, 0, 0);
308
+	    $res = mssql_query('select @@TRANCOUNT');
309
+	    $this->transaction_opened = mssql_result($res, 0, 0);
310 310
 
311 311
 		if ($this->transaction_opened == 1)
312 312
 		{
313
-			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
314
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
313
+			$ret = mssql_query("ROLLBACK TRANSACTION", $this->db);
314
+			dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
315 315
 			return $ret;
316 316
 		}
317 317
 		elseif ($this->transaction_opened > 1)
@@ -331,61 +331,61 @@  discard block
 block discarded – undo
331 331
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
332 332
      *  @return false|resource|true		Resultset of answer
333 333
 	 */
334
-	function query($query,$usesavepoint=0,$type='auto')
334
+	function query($query, $usesavepoint = 0, $type = 'auto')
335 335
 	{
336 336
 		$query = trim($query);
337 337
 
338
-        Debug::addMessage('SQL', 'MSSQL: ' . $query);
338
+        Debug::addMessage('SQL', 'MSSQL: '.$query);
339 339
 
340
-        if (preg_match('/^--/',$query)) return true;
340
+        if (preg_match('/^--/', $query)) return true;
341 341
 
342 342
 		// Conversion syntaxe MySql vers MSDE.
343 343
 		$query = str_ireplace("now()", "getdate()", $query);
344 344
 		// Erreur SQL: cannot update timestamp field
345 345
 		$query = str_ireplace(", tms = tms", "", $query);
346 346
 
347
-		$query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
347
+		$query = preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/", "$1[$2]$3", $query);
348 348
 
349
-		if ($type=="auto" || $type='dml')
349
+		if ($type == "auto" || $type = 'dml')
350 350
 		{
351
-    		$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
352
-    		$query=preg_replace('/double/i','float',$query);
353
-    		$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
354
-    		$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
355
-    		$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
356
-
357
-    		$matches=array();
358
-    		$original_query='';
359
-    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
351
+    		$query = preg_replace('/AUTO_INCREMENT/i', 'IDENTITY', $query);
352
+    		$query = preg_replace('/double/i', 'float', $query);
353
+    		$query = preg_replace('/float\((.*)\)/', 'numeric($1)', $query);
354
+    		$query = preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i', '$1', $query);
355
+    		$query = preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i', "$1VARCHAR(MAX)$3", $query);
356
+
357
+    		$matches = array();
358
+    		$original_query = '';
359
+    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query, $matches))
360 360
     		{
361
-                $original_query=$query;
362
-                $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
361
+                $original_query = $query;
362
+                $query = "CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
363 363
                 if ($matches[2]) {
364 364
                     //check if columun is nullable cause Sql server only allow 1 null value if unique index.
365
-                    $fields=explode(",",trim($matches[4]));
366
-                    $fields_clear=array_map('trim',$fields);
367
-                    $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
368
-                    $query_comp=array();
369
-                    foreach($infos as $fld) {
365
+                    $fields = explode(",", trim($matches[4]));
366
+                    $fields_clear = array_map('trim', $fields);
367
+                    $infos = $this->GetFieldInformation(trim($matches[1]), $fields_clear);
368
+                    $query_comp = array();
369
+                    foreach ($infos as $fld) {
370 370
                         if ($fld->IS_NULLABLE == 'YES') {
371
-                            $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
371
+                            $query_comp[] = $fld->COLUMN_NAME." IS NOT NULL";
372 372
                         }
373 373
                     }
374
-                    if (! empty($query_comp))
375
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
374
+                    if (!empty($query_comp))
375
+                        $query .= " WHERE ".implode(" AND ", $query_comp);
376 376
                 }
377 377
     		}
378 378
     		else
379 379
     		{
380 380
     		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
381 381
     		    {
382
-                    $original_query=$query;
383
-                    $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
382
+                    $original_query = $query;
383
+                    $query = "ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
384 384
     		    }
385 385
     		}
386 386
 		}
387 387
 
388
-		if ($type=="auto" || $type='ddl')
388
+		if ($type == "auto" || $type = 'ddl')
389 389
 		{
390 390
     		$itemfound = stripos($query, " limit ");
391 391
     		if ($itemfound !== false) {
@@ -416,21 +416,21 @@  discard block
 block discarded – undo
416 416
     			// Inserer la date en parametre et le reste de la requete
417 417
     			$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
418 418
     		}
419
-    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
419
+    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i', $query, $matches))
420 420
     	   {
421 421
     	       //var_dump($query);
422 422
     	       //var_dump($matches);
423 423
     	       //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
424
-    	       $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
424
+    	       $sql = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
425 425
     	       @mssql_query($sql, $this->db);
426
-    	       $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
426
+    	       $post_query = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
427 427
     	   }
428 428
 		}
429 429
 		//print "<!--".$query."-->";
430 430
 
431
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
431
+		if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
432 432
 
433
-		if (! $this->database_name)
433
+		if (!$this->database_name)
434 434
 		{
435 435
 			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
436 436
 			$ret = mssql_query($query, $this->db);
@@ -445,10 +445,10 @@  discard block
 block discarded – undo
445 445
 		    @mssql_query($post_query, $this->db);
446 446
 		}
447 447
 
448
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
448
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
449 449
 		{
450 450
 			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
451
-			if (! $ret)
451
+			if (!$ret)
452 452
 			{
453 453
 				$result = mssql_query("SELECT @@ERROR as code", $this->db);
454 454
 				$row = mssql_fetch_array($result);
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 				if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
462 462
 				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
463 463
 			}
464
-			$this->lastquery=$query;
464
+			$this->lastquery = $query;
465 465
 			$this->_results = $ret;
466 466
 		}
467 467
 
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 	{
480 480
         // phpcs:enable
481 481
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
482
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
482
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
483 483
 		return mssql_fetch_object($resultset);
484 484
 	}
485 485
 
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 	{
495 495
         // phpcs:enable
496 496
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
497
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
497
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
498 498
 		return mssql_fetch_array($resultset);
499 499
 	}
500 500
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 	{
511 511
         // phpcs:enable
512 512
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
513
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
513
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
514 514
 		return @mssql_fetch_row($resultset);
515 515
 	}
516 516
 
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 	{
527 527
         // phpcs:enable
528 528
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
529
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
529
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
530 530
 		return mssql_num_rows($resultset);
531 531
 	}
532 532
 
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 	{
543 543
         // phpcs:enable
544 544
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
545
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
545
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
546 546
 		// mssql necessite un link de base pour cette fonction contrairement
547 547
 		// a pqsql qui prend un resultset
548 548
 		$rsRows = mssql_query("select @@rowcount as rows", $this->db);
@@ -557,10 +557,10 @@  discard block
 block discarded – undo
557 557
 	 *	@param  resource	$resultset   Curseur de la requete voulue
558 558
 	 *	@return	bool
559 559
 	 */
560
-	function free($resultset=null)
560
+	function free($resultset = null)
561 561
 	{
562 562
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
563
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
563
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
564 564
 		// Si resultset en est un, on libere la memoire
565 565
 		if (is_resource($resultset)) mssql_free_result($resultset);
566 566
 	}
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 	 */
587 587
 	function idate($param)
588 588
 	{
589
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
589
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
590 590
 	}
591 591
 
592 592
 	/**
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 	 */
597 597
 	function errno()
598 598
 	{
599
-		if (! $this->connected)
599
+		if (!$this->connected)
600 600
 		{
601 601
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
602 602
 			return 'DB_ERROR_FAILED_TO_CONNECT';
@@ -637,8 +637,8 @@  discard block
 block discarded – undo
637 637
 			{
638 638
 				return $errorcode_map[$this->lasterrno];
639 639
 			}
640
-			$errno=$this->lasterrno;
641
-			return ($errno?'DB_ERROR_'.$errno:'0');
640
+			$errno = $this->lasterrno;
641
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
642 642
 		}
643 643
 	}
644 644
 
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 	 */
650 650
 	function error()
651 651
 	{
652
-		if (! $this->connected) {
652
+		if (!$this->connected) {
653 653
 			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
654 654
 			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
655 655
 		}
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 	 * @param	string	$fieldid	Field name
667 667
 	 * @return  int     			Id of row or -1 on error
668 668
 	 */
669
-	function last_insert_id($tab,$fieldid='rowid')
669
+	function last_insert_id($tab, $fieldid = 'rowid')
670 670
 	{
671 671
         // phpcs:enable
672 672
 		$res = $this->query("SELECT @@IDENTITY as id");
@@ -688,18 +688,18 @@  discard block
 block discarded – undo
688 688
      *  @param	int		$withQuotes     Return string with quotes
689 689
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
690 690
 	 */
691
-	function encrypt($fieldorvalue, $withQuotes=0)
691
+	function encrypt($fieldorvalue, $withQuotes = 0)
692 692
 	{
693 693
 		global $conf;
694 694
 
695 695
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
696
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
696
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
697 697
 
698 698
 		//Encryption key
699
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
699
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
700 700
 
701 701
 		$return = $fieldorvalue;
702
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
702
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
703 703
 	}
704 704
 
705 705
 	/**
@@ -713,10 +713,10 @@  discard block
 block discarded – undo
713 713
 		global $conf;
714 714
 
715 715
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
716
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
716
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
717 717
 
718 718
 		//Encryption key
719
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
719
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
720 720
 
721 721
 		$return = $value;
722 722
 		return $return;
@@ -732,10 +732,10 @@  discard block
 block discarded – undo
732 732
 	function DDLGetConnectId()
733 733
 	{
734 734
         // phpcs:enable
735
-		$resql=$this->query('SELECT CONNECTION_ID()');
735
+		$resql = $this->query('SELECT CONNECTION_ID()');
736 736
 		if ($resql)
737 737
 		{
738
-            $row=$this->fetch_row($resql);
738
+            $row = $this->fetch_row($resql);
739 739
             return $row[0];
740 740
 		}
741 741
 		else return '?';
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 	 * 	@param	string	$owner			Username of database owner
754 754
 	 * 	@return	false|resource|true		resource defined if OK, false if KO
755 755
 	 */
756
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
756
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
757 757
 	{
758 758
         // phpcs:enable
759 759
         /*if (empty($charset))   $charset=$this->forcecharset;
@@ -763,18 +763,18 @@  discard block
 block discarded – undo
763 763
 		$sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
764 764
         //TODO: Check if we need to force a charset
765 765
 		//$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
766
-		$ret=$this->query($sql);
766
+		$ret = $this->query($sql);
767 767
 
768 768
 		$this->select_db($database);
769
-		$sql="CREATE USER [$owner] FOR LOGIN [$owner]";
770
-		mssql_query($sql,$this->db);
771
-		$sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
772
-		mssql_query($sql,$this->db);
769
+		$sql = "CREATE USER [$owner] FOR LOGIN [$owner]";
770
+		mssql_query($sql, $this->db);
771
+		$sql = "ALTER ROLE [db_owner] ADD MEMBER [$owner]";
772
+		mssql_query($sql, $this->db);
773 773
 
774
-		$sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
775
-	    @mssql_query($sql,$this->db);
776
-	    $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
777
-	    @mssql_query($sql,$this->db);
774
+		$sql = "ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
775
+	    @mssql_query($sql, $this->db);
776
+	    $sql = "ALTER DATABASE [$database] SET ANSI_NULL ON;";
777
+	    @mssql_query($sql, $this->db);
778 778
 
779 779
 	    return $ret;
780 780
 	}
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
788 788
      *  @return	array					List of tables in an array
789 789
 	 */
790
-	function DDLListTables($database,$table='')
790
+	function DDLListTables($database, $table = '')
791 791
 	{
792 792
         // phpcs:enable
793 793
 		$this->_results = mssql_list_tables($database, $this->db);
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
 		// TODO: Implement
810 810
 		// May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
811 811
 
812
-		$infotables=array();
812
+		$infotables = array();
813 813
 		return $infotables;
814 814
 	}
815 815
 
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
827 827
 	 *	@return	    int						<0 if KO, >=0 if OK
828 828
 	 */
829
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
829
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
830 830
 	{
831 831
         // phpcs:enable
832 832
 		// FIXME: $fulltext_keys parameter is unused
@@ -834,58 +834,58 @@  discard block
 block discarded – undo
834 834
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
835 835
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
836 836
 		$sql = "create table ".$table."(";
837
-		$i=0;
838
-		foreach($fields as $field_name => $field_desc)
837
+		$i = 0;
838
+		foreach ($fields as $field_name => $field_desc)
839 839
 		{
840 840
 			$sqlfields[$i] = $field_name." ";
841 841
 			$sqlfields[$i]  .= $field_desc['type'];
842
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
842
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
843 843
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
844
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
844
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
845 845
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
846
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
846
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
847 847
 			{
848
-				if(preg_match("/null/i",$field_desc['default']))
848
+				if (preg_match("/null/i", $field_desc['default']))
849 849
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
850 850
 				else
851 851
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
852 852
 			}
853
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
853
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
854 854
 			$sqlfields[$i]  .= " ".$field_desc['null'];
855 855
 
856
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
856
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
857 857
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
858 858
 			$i++;
859 859
 		}
860
-		if($primary_key != "")
860
+		if ($primary_key != "")
861 861
 		$pk = "primary key(".$primary_key.")";
862 862
 
863
-		if(is_array($unique_keys))
863
+		if (is_array($unique_keys))
864 864
 		{
865 865
 			$i = 0;
866
-			foreach($unique_keys as $key => $value)
866
+			foreach ($unique_keys as $key => $value)
867 867
 			{
868 868
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
869 869
 				$i++;
870 870
 			}
871 871
 		}
872
-		if(is_array($keys))
872
+		if (is_array($keys))
873 873
 		{
874 874
 			$i = 0;
875
-			foreach($keys as $key => $value)
875
+			foreach ($keys as $key => $value)
876 876
 			{
877 877
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
878 878
 				$i++;
879 879
 			}
880 880
 		}
881
-		$sql .= implode(',',$sqlfields);
882
-		if($primary_key != "")
881
+		$sql .= implode(',', $sqlfields);
882
+		if ($primary_key != "")
883 883
 		$sql .= ",".$pk;
884
-		if(is_array($unique_keys))
885
-		$sql .= ",".implode(',',$sqluq);
886
-		if(is_array($keys))
887
-		$sql .= ",".implode(',',$sqlk);
888
-		$sql .=") type=".$type;
884
+		if (is_array($unique_keys))
885
+		$sql .= ",".implode(',', $sqluq);
886
+		if (is_array($keys))
887
+		$sql .= ",".implode(',', $sqlk);
888
+		$sql .= ") type=".$type;
889 889
 
890 890
 		dol_syslog($sql);
891 891
 		if (!$this->query($sql))
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
         // phpcs:enable
907 907
 		$sql = "DROP TABLE ".$table;
908 908
 
909
-		if (! $this->query($sql))
909
+		if (!$this->query($sql))
910 910
 			return -1;
911 911
 		else
912 912
 			return 1;
@@ -920,10 +920,10 @@  discard block
 block discarded – undo
920 920
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
921 921
 	 *	@return	false|resource|true	Resource
922 922
 	 */
923
-	function DDLDescTable($table,$field="")
923
+	function DDLDescTable($table, $field = "")
924 924
 	{
925 925
         // phpcs:enable
926
-		$sql="DESC ".$table." ".$field;
926
+		$sql = "DESC ".$table." ".$field;
927 927
 
928 928
 		dol_syslog($sql);
929 929
 		$this->_results = $this->query($sql);
@@ -940,25 +940,25 @@  discard block
 block discarded – undo
940 940
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
941 941
 	 *	@return	int							<0 if KO, >0 if OK
942 942
 	 */
943
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
943
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
944 944
 	{
945 945
         // phpcs:enable
946 946
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
947 947
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
948
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
948
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
949 949
 		$sql .= $field_desc['type'];
950
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
950
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
951 951
 		$sql  .= "(".$field_desc['value'].")";
952
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
952
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
953 953
 		$sql  .= " ".$field_desc['attribute'];
954
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
954
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
955 955
 		$sql  .= " ".$field_desc['null'];
956
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
957
-		if(preg_match("/null/i",$field_desc['default']))
956
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
957
+		if (preg_match("/null/i", $field_desc['default']))
958 958
 		$sql  .= " default ".$field_desc['default'];
959 959
 		else
960 960
 		$sql  .= " default '".$field_desc['default']."'";
961
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
961
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
962 962
 		$sql  .= " ".$field_desc['extra'];
963 963
 		$sql .= " ".$field_position;
964 964
 
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
 	 *	@param	string	$field_desc 		Array with description of field format
978 978
 	 *	@return	int							<0 if KO, >0 if OK
979 979
 	 */
980
-	function DDLUpdateField($table,$field_name,$field_desc)
980
+	function DDLUpdateField($table, $field_name, $field_desc)
981 981
 	{
982 982
         // phpcs:enable
983 983
 		$sql = "ALTER TABLE ".$table;
984 984
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
985 985
 		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
986
-			$sql.="(".$field_desc['value'].")";
986
+			$sql .= "(".$field_desc['value'].")";
987 987
 		}
988 988
 
989
-		dol_syslog($sql,LOG_DEBUG);
990
-		if (! $this->query($sql))
989
+		dol_syslog($sql, LOG_DEBUG);
990
+		if (!$this->query($sql))
991 991
 		return -1;
992 992
 		else
993 993
 		return 1;
@@ -1001,14 +1001,14 @@  discard block
 block discarded – undo
1001 1001
 	 *	@param	string	$field_name 	Name of field to drop
1002 1002
 	 *	@return	int						<0 if KO, >0 if OK
1003 1003
 	 */
1004
-	function DDLDropField($table,$field_name)
1004
+	function DDLDropField($table, $field_name)
1005 1005
 	{
1006 1006
         // phpcs:enable
1007
-		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1008
-		dol_syslog($sql,LOG_DEBUG);
1009
-		if (! $this->query($sql))
1007
+		$sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1008
+		dol_syslog($sql, LOG_DEBUG);
1009
+		if (!$this->query($sql))
1010 1010
 		{
1011
-			$this->error=$this->lasterror();
1011
+			$this->error = $this->lasterror();
1012 1012
 			return -1;
1013 1013
 		}
1014 1014
 		else return 1;
@@ -1024,13 +1024,13 @@  discard block
 block discarded – undo
1024 1024
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1025 1025
 	 *	@return	int									<0 if KO, >=0 if OK
1026 1026
 	 */
1027
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1027
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1028 1028
 	{
1029 1029
         // phpcs:enable
1030 1030
         $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
1031
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1032
-        $resql=$this->query($sql);
1033
-        if (! $resql)
1031
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1032
+        $resql = $this->query($sql);
1033
+        if (!$resql)
1034 1034
         {
1035 1035
             if ($this->lasterrno != '15025')
1036 1036
             {
@@ -1042,9 +1042,9 @@  discard block
 block discarded – undo
1042 1042
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1043 1043
             }
1044 1044
         }
1045
-        $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1046
-        $ressql=$this->query($sql);
1047
-        if (! $ressql)
1045
+        $sql = "SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1046
+        $ressql = $this->query($sql);
1047
+        if (!$ressql)
1048 1048
         {
1049 1049
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1050 1050
             return -1;
@@ -1054,9 +1054,9 @@  discard block
 block discarded – undo
1054 1054
             if ($num)
1055 1055
             {
1056 1056
                 $this->select_db($dolibarr_main_db_name);
1057
-                $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1057
+                $sql = "CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1058 1058
                 $this->query($sql);
1059
-                $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1059
+                $sql = "ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1060 1060
                 $this->query($sql);
1061 1061
             }
1062 1062
         }
@@ -1096,12 +1096,12 @@  discard block
 block discarded – undo
1096 1096
 	 */
1097 1097
 	function getDefaultCollationDatabase()
1098 1098
 	{
1099
-		$resql=$this->query("SELECT SERVERPROPERTY('collation')");
1099
+		$resql = $this->query("SELECT SERVERPROPERTY('collation')");
1100 1100
 		if (!$resql)
1101 1101
 		{
1102 1102
 			return $this->forcecollate;
1103 1103
 		}
1104
-		$liste=$this->fetch_array($resql);
1104
+		$liste = $this->fetch_array($resql);
1105 1105
 		return $liste['computed'];
1106 1106
 	}
1107 1107
 
@@ -1150,13 +1150,13 @@  discard block
 block discarded – undo
1150 1150
 	 * @param	string	$filter		Filter list on a particular value
1151 1151
 	 * @return	array				Array of key-values (key=>value)
1152 1152
 	 */
1153
-	function getServerParametersValues($filter='')
1153
+	function getServerParametersValues($filter = '')
1154 1154
 	{
1155 1155
 		// FIXME: Dummy method
1156 1156
 		// TODO: Implement
1157 1157
 		// May help: SELECT SERVERPROPERTY
1158 1158
 
1159
-		$result=array();
1159
+		$result = array();
1160 1160
 		return $result;
1161 1161
 	}
1162 1162
 
@@ -1166,7 +1166,7 @@  discard block
 block discarded – undo
1166 1166
 	 * @param	string	$filter		Filter list on a particular value
1167 1167
 	 * @return  array				Array of key-values (key=>value)
1168 1168
 	 */
1169
-	function getServerStatusValues($filter='')
1169
+	function getServerStatusValues($filter = '')
1170 1170
 	{
1171 1171
 		// FIXME: Dummy method
1172 1172
 		// TODO: Implement
@@ -1197,25 +1197,25 @@  discard block
 block discarded – undo
1197 1197
 	 * @param      mixed   $fields     String for one field or array of string for multiple field
1198 1198
 	 * @return false|object
1199 1199
 	 */
1200
-    function GetFieldInformation($table,$fields)
1200
+    function GetFieldInformation($table, $fields)
1201 1201
     {
1202 1202
         // phpcs:enable
1203
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1203
+	    $sql = "SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1204 1204
 	    if (is_array($fields))
1205 1205
 	    {
1206
-	        $where=" IN ('".implode("','",$fields)."')";
1206
+	        $where = " IN ('".implode("','", $fields)."')";
1207 1207
 	    }
1208 1208
 	    else
1209 1209
 	    {
1210
-	        $where="='".$this->escape($fields)."'";
1210
+	        $where = "='".$this->escape($fields)."'";
1211 1211
 	    }
1212
-	    $result=array();
1213
-	    $ret=mssql_query($sql.$where,$this->db);
1212
+	    $result = array();
1213
+	    $ret = mssql_query($sql.$where, $this->db);
1214 1214
 	    if ($ret)
1215 1215
 	    {
1216
-	        while($obj=mssql_fetch_object($ret))
1216
+	        while ($obj = mssql_fetch_object($ret))
1217 1217
 	        {
1218
-	            $result[]=$obj;
1218
+	            $result[] = $obj;
1219 1219
 	        }
1220 1220
 	    }
1221 1221
 	    else
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/sqlite3.class.php 1 patch
Spacing   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
  *	\brief      Class file to manage Dolibarr database access for a SQLite database
32 32
  */
33 33
 
34
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
34
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
35 35
 
36 36
 /**
37 37
  *	Class to manage Dolibarr database access for a SQLite database
@@ -39,17 +39,17 @@  discard block
 block discarded – undo
39 39
 class DoliDBSqlite3 extends DoliDB
40 40
 {
41 41
     //! Database type
42
-    public $type='sqlite3';
42
+    public $type = 'sqlite3';
43 43
     //! Database label
44
-    const LABEL='Sqlite3';
44
+    const LABEL = 'Sqlite3';
45 45
     //! Version min database
46
-    const VERSIONMIN='3.0.0';
46
+    const VERSIONMIN = '3.0.0';
47 47
 	/** @var SQLite3Result Resultset of last query */
48 48
 	private $_results;
49 49
 
50
-    const WEEK_MONDAY_FIRST=1;
50
+    const WEEK_MONDAY_FIRST = 1;
51 51
     const WEEK_YEAR = 2;
52
-    const WEEK_FIRST_WEEKDAY=4;
52
+    const WEEK_FIRST_WEEKDAY = 4;
53 53
 
54 54
 
55 55
     /**
@@ -63,19 +63,19 @@  discard block
 block discarded – undo
63 63
 	 *	@param	    string	$name		Nom de la database
64 64
 	 *	@param	    int		$port		Port of database server
65 65
      */
66
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
66
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
67 67
     {
68 68
         global $conf;
69 69
 
70 70
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
71
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
72
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
71
+        if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
72
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
73 73
 
74
-        $this->database_user=$user;
75
-        $this->database_host=$host;
76
-        $this->database_port=$port;
74
+        $this->database_user = $user;
75
+        $this->database_host = $host;
76
+        $this->database_port = $port;
77 77
 
78
-        $this->transaction_opened=0;
78
+        $this->transaction_opened = 0;
79 79
 
80 80
         //print "Name DB: $host,$user,$pass,$name<br>";
81 81
 
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
             $this->database_selected = false;
127 127
             $this->database_name = '';
128 128
             //$this->error=sqlite_connect_error();
129
-            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error,LOG_ERR);
129
+            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error, LOG_ERR);
130 130
         }
131 131
 
132 132
         return $this->ok;
@@ -140,14 +140,14 @@  discard block
 block discarded – undo
140 140
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
141 141
      *  @return    string   		SQL request line converted
142 142
      */
143
-    static function convertSQLFromMysql($line,$type='ddl')
143
+    static function convertSQLFromMysql($line, $type = 'ddl')
144 144
     {
145 145
         // Removed empty line if this is a comment line for SVN tagging
146
-        if (preg_match('/^--\s\$Id/i',$line)) {
146
+        if (preg_match('/^--\s\$Id/i', $line)) {
147 147
             return '';
148 148
         }
149 149
         // Return line if this is a comment
150
-        if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
150
+        if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
151 151
         {
152 152
             return $line;
153 153
         }
@@ -155,114 +155,114 @@  discard block
 block discarded – undo
155 155
         {
156 156
             if ($type == 'auto')
157 157
             {
158
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
159
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
160
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
158
+              if (preg_match('/ALTER TABLE/i', $line)) $type = 'dml';
159
+              else if (preg_match('/CREATE TABLE/i', $line)) $type = 'dml';
160
+              else if (preg_match('/DROP TABLE/i', $line)) $type = 'dml';
161 161
             }
162 162
 
163 163
             if ($type == 'dml')
164 164
             {
165
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
165
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
166 166
 
167 167
                 // we are inside create table statement so lets process datatypes
168
-                if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
169
-                    $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
170
-                    $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
171
-                    $line=preg_replace('/,$/','',$line);
168
+                if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
169
+                    $line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
170
+                    $line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
171
+                    $line = preg_replace('/,$/', '', $line);
172 172
                 }
173 173
 
174 174
                 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
175
-                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
176
-                    $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 integer PRIMARY KEY AUTOINCREMENT',$line);
175
+                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
176
+                    $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 integer PRIMARY KEY AUTOINCREMENT', $line);
177 177
                     //$line = "-- ".$line." replaced by --\n".$newline;
178
-                    $line=$newline;
178
+                    $line = $newline;
179 179
                 }
180 180
 
181 181
                 // tinyint type conversion
182
-                $line=str_replace('tinyint','smallint',$line);
182
+                $line = str_replace('tinyint', 'smallint', $line);
183 183
 
184 184
                 // nuke unsigned
185
-                $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
185
+                $line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
186 186
 
187 187
                 // blob -> text
188
-                $line=preg_replace('/\w*blob/i','text',$line);
188
+                $line = preg_replace('/\w*blob/i', 'text', $line);
189 189
 
190 190
                 // tinytext/mediumtext -> text
191
-                $line=preg_replace('/tinytext/i','text',$line);
192
-                $line=preg_replace('/mediumtext/i','text',$line);
191
+                $line = preg_replace('/tinytext/i', 'text', $line);
192
+                $line = preg_replace('/mediumtext/i', 'text', $line);
193 193
 
194 194
                 // change not null datetime field to null valid ones
195 195
                 // (to support remapping of "zero time" to null
196
-                $line=preg_replace('/datetime not null/i','datetime',$line);
197
-                $line=preg_replace('/datetime/i','timestamp',$line);
196
+                $line = preg_replace('/datetime not null/i', 'datetime', $line);
197
+                $line = preg_replace('/datetime/i', 'timestamp', $line);
198 198
 
199 199
                 // double -> numeric
200
-                $line=preg_replace('/^double/i','numeric',$line);
201
-                $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
200
+                $line = preg_replace('/^double/i', 'numeric', $line);
201
+                $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
202 202
                 // float -> numeric
203
-                $line=preg_replace('/^float/i','numeric',$line);
204
-                $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
203
+                $line = preg_replace('/^float/i', 'numeric', $line);
204
+                $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
205 205
 
206 206
                 // unique index(field1,field2)
207
-                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
207
+                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
208 208
                 {
209
-                    $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
209
+                    $line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
210 210
                 }
211 211
 
212 212
                 // We remove end of requests "AFTER fieldxxx"
213
-                $line=preg_replace('/AFTER [a-z0-9_]+/i','',$line);
213
+                $line = preg_replace('/AFTER [a-z0-9_]+/i', '', $line);
214 214
 
215 215
                 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
216
-                $line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line);
216
+                $line = preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i', 'DROP INDEX', $line);
217 217
 
218 218
                 // Translate order to rename fields
219
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
219
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
220 220
                 {
221 221
                     $line = "-- ".$line." replaced by --\n";
222
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
222
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
223 223
                 }
224 224
 
225 225
                 // Translate order to modify field format
226
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
226
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
227 227
                 {
228 228
                     $line = "-- ".$line." replaced by --\n";
229
-                    $newreg3=$reg[3];
230
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
231
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
232
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
233
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
234
-                    $newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3);
235
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
229
+                    $newreg3 = $reg[3];
230
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
231
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
232
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
233
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
234
+                    $newreg3 = preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i', '', $newreg3);
235
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
236 236
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
237 237
                 }
238 238
 
239 239
                 // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
240 240
                 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
241
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
241
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
242 242
                 {
243 243
                     $line = "-- ".$line." replaced by --\n";
244
-                    $line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
244
+                    $line .= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
245 245
                 }
246 246
 
247 247
                 // Translate order to drop foreign keys
248 248
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
249
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
249
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
250 250
                 {
251 251
                     $line = "-- ".$line." replaced by --\n";
252
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
252
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
253 253
                 }
254 254
 
255 255
                 // alter table add [unique] [index] (field1, field2 ...)
256 256
                 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
257
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
257
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
258 258
                 {
259
-                    $fieldlist=$reg[4];
260
-                    $idxname=$reg[3];
261
-                    $tablename=$reg[1];
259
+                    $fieldlist = $reg[4];
260
+                    $idxname = $reg[3];
261
+                    $tablename = $reg[1];
262 262
                     $line = "-- ".$line." replaced by --\n";
263
-                    $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
263
+                    $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
264 264
                 }
265
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i',$line, $reg)) {
265
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
266 266
                     // Pour l'instant les contraintes ne sont pas créées
267 267
                     dol_syslog(get_class().'::query line emptied');
268 268
                     $line = 'SELECT 0;';
@@ -275,24 +275,24 @@  discard block
 block discarded – undo
275 275
 
276 276
             // Delete using criteria on other table must not declare twice the deleted table
277 277
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
278
-            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
278
+            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
279 279
             {
280 280
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
281 281
                 {
282
-                    $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
282
+                    $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
283 283
                 }
284 284
             }
285 285
 
286 286
             // Remove () in the tables in FROM if one table
287
-            $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
287
+            $line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
288 288
             //print $line."\n";
289 289
 
290 290
             // Remove () in the tables in FROM if two table
291
-            $line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2',$line);
291
+            $line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2', $line);
292 292
             //print $line."\n";
293 293
 
294 294
             // Remove () in the tables in FROM if two table
295
-            $line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2, \\3',$line);
295
+            $line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2, \\3', $line);
296 296
             //print $line."\n";
297 297
 
298 298
             //print "type=".$type." newline=".$line."<br>\n";
@@ -329,14 +329,14 @@  discard block
 block discarded – undo
329 329
 	 *	@return		SQLite3				Database access handler
330 330
 	 *	@see		close
331 331
      */
332
-    function connect($host, $login, $passwd, $name, $port=0)
332
+    function connect($host, $login, $passwd, $name, $port = 0)
333 333
     {
334 334
         global $main_data_dir;
335 335
 
336
-        dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
336
+        dol_syslog(get_class($this)."::connect name=".$name, LOG_DEBUG);
337 337
 
338
-        $dir=$main_data_dir;
339
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
338
+        $dir = $main_data_dir;
339
+        if (empty($dir)) $dir = DOL_DATA_ROOT;
340 340
         // With sqlite, port must be in connect parameters
341 341
         //if (! $newport) $newport=3306;
342 342
         $database_name = $dir.'/database_'.$name.'.sdb';
@@ -346,9 +346,9 @@  discard block
 block discarded – undo
346 346
 			$this->db = new SQLite3($database_name);
347 347
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
348 348
         }
349
-        catch(Exception $e)
349
+        catch (Exception $e)
350 350
         {
351
-            $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
351
+            $this->error = self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
352 352
             return '';
353 353
         }
354 354
 
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
      */
365 365
     function getVersion()
366 366
     {
367
-    	$tmp=$this->db->version();
367
+    	$tmp = $this->db->version();
368 368
         return $tmp['versionString'];
369 369
     }
370 370
 
@@ -389,10 +389,10 @@  discard block
 block discarded – undo
389 389
     {
390 390
         if ($this->db)
391 391
         {
392
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
393
-            $this->connected=false;
392
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
393
+            $this->connected = false;
394 394
             $this->db->close();
395
-            unset($this->db);    // Clean this->db
395
+            unset($this->db); // Clean this->db
396 396
             return true;
397 397
         }
398 398
         return false;
@@ -407,17 +407,17 @@  discard block
 block discarded – undo
407 407
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
408 408
      *	@return	SQLite3Result			Resultset of answer
409 409
      */
410
-    function query($query,$usesavepoint=0,$type='auto')
410
+    function query($query, $usesavepoint = 0, $type = 'auto')
411 411
     {
412
-        $ret=null;
412
+        $ret = null;
413 413
         $query = trim($query);
414 414
 
415
-        Debug::addMessage('SQL', 'SqLite: ' . $query);
415
+        Debug::addMessage('SQL', 'SqLite: '.$query);
416 416
 
417 417
         $this->error = 0;
418 418
 
419 419
         // Convert MySQL syntax to SQLite syntax
420
-        if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i',$query, $reg)) {
420
+        if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $query, $reg)) {
421 421
             // Ajout d'une clef étrangère à la table
422 422
             // procédure de remplacement de la table pour ajouter la contrainte
423 423
             // Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
@@ -425,19 +425,19 @@  discard block
 block discarded – undo
425 425
             $foreignFields = $reg[5];
426 426
             $foreignTable = $reg[4];
427 427
             $localfields = $reg[3];
428
-            $constraintname=trim($reg[2]);
429
-            $tablename=trim($reg[1]);
428
+            $constraintname = trim($reg[2]);
429
+            $tablename = trim($reg[1]);
430 430
 
431
-            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='" . $tablename . "'");
431
+            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='".$tablename."'");
432 432
 
433 433
             // 1- Renommer la table avec un nom temporaire
434
-            $this->query('ALTER TABLE ' . $tablename . ' RENAME TO tmp_' . $tablename);
434
+            $this->query('ALTER TABLE '.$tablename.' RENAME TO tmp_'.$tablename);
435 435
 
436 436
             // 2- Recréer la table avec la contrainte ajoutée
437 437
 
438 438
             // on bricole la requete pour ajouter la contrainte
439 439
             $descTable = substr($descTable, 0, strlen($descTable) - 1);
440
-            $descTable .= ", CONSTRAINT " . $constraintname . " FOREIGN KEY (" . $localfields . ") REFERENCES " .$foreignTable . "(" . $foreignFields . ")";
440
+            $descTable .= ", CONSTRAINT ".$constraintname." FOREIGN KEY (".$localfields.") REFERENCES ".$foreignTable."(".$foreignFields.")";
441 441
 
442 442
             // fermeture de l'instruction
443 443
             $descTable .= ')';
@@ -446,15 +446,15 @@  discard block
 block discarded – undo
446 446
             $this->query($descTable);
447 447
 
448 448
             // 3- Transférer les données
449
-            $this->query('INSERT INTO ' . $tablename . ' SELECT * FROM tmp_' . $tablename);
449
+            $this->query('INSERT INTO '.$tablename.' SELECT * FROM tmp_'.$tablename);
450 450
 
451 451
             // 4- Supprimer la table temporaire
452
-            $this->query('DROP TABLE tmp_' . $tablename);
452
+            $this->query('DROP TABLE tmp_'.$tablename);
453 453
 
454 454
             // dummy statement
455
-            $query="SELECT 0";
455
+            $query = "SELECT 0";
456 456
         } else {
457
-            $query=$this->convertSQLFromMysql($query,$type);
457
+            $query = $this->convertSQLFromMysql($query, $type);
458 458
         }
459 459
         //print "After convertSQLFromMysql:\n".$query."<br>\n";
460 460
 
@@ -463,20 +463,20 @@  discard block
 block discarded – undo
463 463
         // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
464 464
         try {
465 465
             //$ret = $this->db->exec($query);
466
-            $ret = $this->db->query($query);        // $ret is a Sqlite3Result
466
+            $ret = $this->db->query($query); // $ret is a Sqlite3Result
467 467
             if ($ret) {
468 468
                 $ret->queryString = $query;
469 469
             }
470 470
         }
471
-        catch(Exception $e)
471
+        catch (Exception $e)
472 472
         {
473
-            $this->error=$this->db->lastErrorMsg();
473
+            $this->error = $this->db->lastErrorMsg();
474 474
         }
475 475
 
476
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
476
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
477 477
         {
478 478
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
479
-            if (! is_object($ret) || $this->error)
479
+            if (!is_object($ret) || $this->error)
480 480
             {
481 481
                 $this->lastqueryerror = $query;
482 482
                 $this->lasterror = $this->error();
@@ -486,13 +486,13 @@  discard block
 block discarded – undo
486 486
 
487 487
                 $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
488 488
 
489
-                if (preg_match('/[0-9]/',$this->lasterrno)) {
489
+                if (preg_match('/[0-9]/', $this->lasterrno)) {
490 490
                     $errormsg .= ' ('.$this->lasterrno.')';
491 491
                 }
492 492
 
493 493
                 dol_syslog($errormsg, LOG_ERR);
494 494
             }
495
-            $this->lastquery=$query;
495
+            $this->lastquery = $query;
496 496
             $this->_results = $ret;
497 497
         }
498 498
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
     {
511 511
         // phpcs:enable
512 512
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
513
-        if (! is_object($resultset)) { $resultset=$this->_results; }
513
+        if (!is_object($resultset)) { $resultset = $this->_results; }
514 514
         //return $resultset->fetch(PDO::FETCH_OBJ);
515 515
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
516 516
         if ($ret) {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
     {
532 532
         // phpcs:enable
533 533
         // If resultset not provided, we take the last used by connexion
534
-        if (! is_object($resultset)) { $resultset=$this->_results; }
534
+        if (!is_object($resultset)) { $resultset = $this->_results; }
535 535
         //return $resultset->fetch(PDO::FETCH_ASSOC);
536 536
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
537 537
 	    return $ret;
@@ -548,9 +548,9 @@  discard block
 block discarded – undo
548 548
     {
549 549
         // phpcs:enable
550 550
         // If resultset not provided, we take the last used by connexion
551
-        if (! is_bool($resultset))
551
+        if (!is_bool($resultset))
552 552
         {
553
-            if (! is_object($resultset)) { $resultset=$this->_results; }
553
+            if (!is_object($resultset)) { $resultset = $this->_results; }
554 554
             return $resultset->fetchArray(SQLITE3_NUM);
555 555
         }
556 556
         else
@@ -574,9 +574,9 @@  discard block
 block discarded – undo
574 574
         // FIXME: SQLite3Result does not have a queryString member
575 575
 
576 576
         // If resultset not provided, we take the last used by connexion
577
-        if (! is_object($resultset)) { $resultset=$this->_results; }
577
+        if (!is_object($resultset)) { $resultset = $this->_results; }
578 578
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
579
-            return $this->db->querySingle("SELECT count(*) FROM (" . $resultset->queryString . ") q");
579
+            return $this->db->querySingle("SELECT count(*) FROM (".$resultset->queryString.") q");
580 580
         }
581 581
         return 0;
582 582
     }
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
         // FIXME: SQLite3Result does not have a queryString member
596 596
 
597 597
         // If resultset not provided, we take the last used by connexion
598
-        if (! is_object($resultset)) { $resultset=$this->_results; }
598
+        if (!is_object($resultset)) { $resultset = $this->_results; }
599 599
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
600 600
             return $this->num_rows($resultset);
601 601
         }
@@ -611,10 +611,10 @@  discard block
 block discarded – undo
611 611
 	 *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
612 612
 	 *	@return	void
613 613
      */
614
-    function free($resultset=null)
614
+    function free($resultset = null)
615 615
     {
616 616
         // If resultset not provided, we take the last used by connexion
617
-        if (! is_object($resultset)) { $resultset=$this->_results; }
617
+        if (!is_object($resultset)) { $resultset = $this->_results; }
618 618
         // Si resultset en est un, on libere la memoire
619 619
         if ($resultset && is_object($resultset)) $resultset->finalize();
620 620
     }
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
      */
638 638
     function errno()
639 639
     {
640
-        if (! $this->connected) {
640
+        if (!$this->connected) {
641 641
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
642 642
             return 'DB_ERROR_FAILED_TO_CONNECT';
643 643
         }
@@ -675,23 +675,23 @@  discard block
 block discarded – undo
675 675
             {
676 676
                 return $errorcode_map[$this->db->errorCode()];
677 677
             }*/
678
-            $errno=$this->db->lastErrorCode();
679
-			if ($errno=='HY000' || $errno == 0)
678
+            $errno = $this->db->lastErrorCode();
679
+			if ($errno == 'HY000' || $errno == 0)
680 680
             {
681
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
682
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
683
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
681
+                if (preg_match('/table.*already exists/i', $this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
682
+                elseif (preg_match('/index.*already exists/i', $this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
683
+                elseif (preg_match('/syntax error/i', $this->error))          return 'DB_ERROR_SYNTAX';
684 684
             }
685
-            if ($errno=='23000')
685
+            if ($errno == '23000')
686 686
             {
687
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
688
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
687
+                if (preg_match('/column.* not unique/i', $this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
688
+                elseif (preg_match('/PRIMARY KEY must be unique/i', $this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
689 689
             }
690 690
             if ($errno > 1) {
691 691
                 // TODO Voir la liste des messages d'erreur
692 692
             }
693 693
 
694
-            return ($errno?'DB_ERROR_'.$errno:'0');
694
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
695 695
         }
696 696
     }
697 697
 
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
      */
703 703
     function error()
704 704
     {
705
-        if (! $this->connected) {
705
+        if (!$this->connected) {
706 706
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
707 707
             return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
708 708
         }
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 	 * @param	string	$fieldid	Field name
720 720
 	 * @return  int     			Id of row
721 721
      */
722
-    function last_insert_id($tab,$fieldid='rowid')
722
+    function last_insert_id($tab, $fieldid = 'rowid')
723 723
     {
724 724
         // phpcs:enable
725 725
         return $this->db->lastInsertRowId();
@@ -733,17 +733,17 @@  discard block
 block discarded – undo
733 733
      *  @param	int		$withQuotes     Return string with quotes
734 734
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
735 735
      */
736
-    function encrypt($fieldorvalue, $withQuotes=0)
736
+    function encrypt($fieldorvalue, $withQuotes = 0)
737 737
     {
738 738
         global $conf;
739 739
 
740 740
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
741
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
741
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
742 742
 
743 743
         //Encryption key
744
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
744
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
745 745
 
746
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
746
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
747 747
 
748 748
         if ($cryptType && !empty($cryptKey))
749 749
         {
@@ -771,10 +771,10 @@  discard block
 block discarded – undo
771 771
         global $conf;
772 772
 
773 773
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
774
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
774
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
775 775
 
776 776
         //Encryption key
777
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
777
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
778 778
 
779 779
         $return = $value;
780 780
 
@@ -819,24 +819,24 @@  discard block
 block discarded – undo
819 819
 	 * 	@param	string	$owner			Username of database owner
820 820
 	 * 	@return	SQLite3Result   		resource defined if OK, null if KO
821 821
      */
822
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
822
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
823 823
     {
824 824
         // phpcs:enable
825
-        if (empty($charset))   $charset=$this->forcecharset;
826
-        if (empty($collation)) $collation=$this->forcecollate;
825
+        if (empty($charset))   $charset = $this->forcecharset;
826
+        if (empty($collation)) $collation = $this->forcecollate;
827 827
 
828 828
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
829 829
         $sql = 'CREATE DATABASE '.$database;
830
-        $sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
830
+        $sql .= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
831 831
 
832
-        dol_syslog($sql,LOG_DEBUG);
833
-        $ret=$this->query($sql);
834
-        if (! $ret)
832
+        dol_syslog($sql, LOG_DEBUG);
833
+        $ret = $this->query($sql);
834
+        if (!$ret)
835 835
         {
836 836
             // We try again for compatibility with Mysql < 4.1.1
837 837
             $sql = 'CREATE DATABASE '.$database;
838
-            $ret=$this->query($sql);
839
-            dol_syslog($sql,LOG_DEBUG);
838
+            $ret = $this->query($sql);
839
+            dol_syslog($sql, LOG_DEBUG);
840 840
         }
841 841
         return $ret;
842 842
     }
@@ -849,19 +849,19 @@  discard block
 block discarded – undo
849 849
 	 *  @param	string		$table		Name of table filter ('xxx%')
850 850
 	 *  @return	array					List of tables in an array
851 851
      */
852
-    function DDLListTables($database, $table='')
852
+    function DDLListTables($database, $table = '')
853 853
     {
854 854
         // phpcs:enable
855
-        $listtables=array();
855
+        $listtables = array();
856 856
 
857 857
         $like = '';
858 858
         if ($table) $like = "LIKE '".$table."'";
859
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
859
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
860 860
         //print $sql;
861 861
         $result = $this->query($sql);
862 862
         if ($result)
863 863
         {
864
-            while($row = $this->fetch_row($result))
864
+            while ($row = $this->fetch_row($result))
865 865
             {
866 866
                 $listtables[] = $row[0];
867 867
             }
@@ -880,15 +880,15 @@  discard block
 block discarded – undo
880 880
     function DDLInfoTable($table)
881 881
     {
882 882
         // phpcs:enable
883
-        $infotables=array();
883
+        $infotables = array();
884 884
 
885
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
885
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
886 886
 
887
-        dol_syslog($sql,LOG_DEBUG);
887
+        dol_syslog($sql, LOG_DEBUG);
888 888
         $result = $this->query($sql);
889 889
         if ($result)
890 890
         {
891
-            while($row = $this->fetch_row($result))
891
+            while ($row = $this->fetch_row($result))
892 892
             {
893 893
                 $infotables[] = $row;
894 894
             }
@@ -909,7 +909,7 @@  discard block
 block discarded – undo
909 909
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
910 910
 	 *	@return	    int						<0 if KO, >=0 if OK
911 911
      */
912
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
912
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
913 913
     {
914 914
         // phpcs:enable
915 915
         // FIXME: $fulltext_keys parameter is unused
@@ -917,60 +917,60 @@  discard block
 block discarded – undo
917 917
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
918 918
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
919 919
         $sql = "create table ".$table."(";
920
-        $i=0;
921
-        foreach($fields as $field_name => $field_desc)
920
+        $i = 0;
921
+        foreach ($fields as $field_name => $field_desc)
922 922
         {
923 923
             $sqlfields[$i] = $field_name." ";
924 924
             $sqlfields[$i]  .= $field_desc['type'];
925
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
925
+            if (preg_match("/^[^\s]/i", $field_desc['value']))
926 926
             $sqlfields[$i]  .= "(".$field_desc['value'].")";
927
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
927
+            else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
928 928
             $sqlfields[$i]  .= " ".$field_desc['attribute'];
929
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
929
+            else if (preg_match("/^[^\s]/i", $field_desc['default']))
930 930
             {
931
-                if(preg_match("/null/i",$field_desc['default']))
931
+                if (preg_match("/null/i", $field_desc['default']))
932 932
                 $sqlfields[$i]  .= " default ".$field_desc['default'];
933 933
                 else
934 934
                 $sqlfields[$i]  .= " default '".$field_desc['default']."'";
935 935
             }
936
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
936
+            else if (preg_match("/^[^\s]/i", $field_desc['null']))
937 937
             $sqlfields[$i]  .= " ".$field_desc['null'];
938 938
 
939
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
939
+            else if (preg_match("/^[^\s]/i", $field_desc['extra']))
940 940
             $sqlfields[$i]  .= " ".$field_desc['extra'];
941 941
             $i++;
942 942
         }
943
-        if($primary_key != "")
943
+        if ($primary_key != "")
944 944
         $pk = "primary key(".$primary_key.")";
945 945
 
946
-        if(is_array($unique_keys))
946
+        if (is_array($unique_keys))
947 947
         {
948 948
             $i = 0;
949
-            foreach($unique_keys as $key => $value)
949
+            foreach ($unique_keys as $key => $value)
950 950
             {
951 951
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
952 952
                 $i++;
953 953
             }
954 954
         }
955
-        if(is_array($keys))
955
+        if (is_array($keys))
956 956
         {
957 957
             $i = 0;
958
-            foreach($keys as $key => $value)
958
+            foreach ($keys as $key => $value)
959 959
             {
960 960
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
961 961
                 $i++;
962 962
             }
963 963
         }
964
-        $sql .= implode(',',$sqlfields);
965
-        if($primary_key != "")
964
+        $sql .= implode(',', $sqlfields);
965
+        if ($primary_key != "")
966 966
         $sql .= ",".$pk;
967
-        if(is_array($unique_keys))
968
-        $sql .= ",".implode(',',$sqluq);
969
-        if(is_array($keys))
970
-        $sql .= ",".implode(',',$sqlk);
971
-        $sql .=") type=".$type;
967
+        if (is_array($unique_keys))
968
+        $sql .= ",".implode(',', $sqluq);
969
+        if (is_array($keys))
970
+        $sql .= ",".implode(',', $sqlk);
971
+        $sql .= ") type=".$type;
972 972
 
973
-        dol_syslog($sql,LOG_DEBUG);
973
+        dol_syslog($sql, LOG_DEBUG);
974 974
         if (!$this->query($sql))
975 975
             return -1;
976 976
         return 1;
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
         // phpcs:enable
989 989
     	$sql = "DROP TABLE ".$table;
990 990
 
991
-    	if (! $this->query($sql))
991
+    	if (!$this->query($sql))
992 992
     		return -1;
993 993
     	else
994 994
     		return 1;
@@ -1002,12 +1002,12 @@  discard block
 block discarded – undo
1002 1002
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1003 1003
 	 *	@return	SQLite3Result		Resource
1004 1004
      */
1005
-    function DDLDescTable($table,$field="")
1005
+    function DDLDescTable($table, $field = "")
1006 1006
     {
1007 1007
         // phpcs:enable
1008
-        $sql="DESC ".$table." ".$field;
1008
+        $sql = "DESC ".$table." ".$field;
1009 1009
 
1010
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
1010
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
1011 1011
         $this->_results = $this->query($sql);
1012 1012
         return $this->_results;
1013 1013
     }
@@ -1022,35 +1022,35 @@  discard block
 block discarded – undo
1022 1022
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1023 1023
 	 *	@return	int							<0 if KO, >0 if OK
1024 1024
      */
1025
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
1025
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1026 1026
     {
1027 1027
         // phpcs:enable
1028 1028
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1029 1029
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1030
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1031
-        $sql.= $field_desc['type'];
1032
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
1033
-        if (! in_array($field_desc['type'],array('date','datetime')))
1030
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1031
+        $sql .= $field_desc['type'];
1032
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
1033
+        if (!in_array($field_desc['type'], array('date', 'datetime')))
1034 1034
         {
1035
-            $sql.= "(".$field_desc['value'].")";
1035
+            $sql .= "(".$field_desc['value'].")";
1036 1036
         }
1037
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1038
-        $sql.= " ".$field_desc['attribute'];
1039
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1040
-        $sql.= " ".$field_desc['null'];
1041
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
1037
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1038
+        $sql .= " ".$field_desc['attribute'];
1039
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
1040
+        $sql .= " ".$field_desc['null'];
1041
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
1042 1042
         {
1043
-            if(preg_match("/null/i",$field_desc['default']))
1044
-            $sql.= " default ".$field_desc['default'];
1043
+            if (preg_match("/null/i", $field_desc['default']))
1044
+            $sql .= " default ".$field_desc['default'];
1045 1045
             else
1046
-            $sql.= " default '".$field_desc['default']."'";
1046
+            $sql .= " default '".$field_desc['default']."'";
1047 1047
         }
1048
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1049
-        $sql.= " ".$field_desc['extra'];
1050
-        $sql.= " ".$field_position;
1048
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
1049
+        $sql .= " ".$field_desc['extra'];
1050
+        $sql .= " ".$field_position;
1051 1051
 
1052
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1053
-        if(! $this->query($sql))
1052
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1053
+        if (!$this->query($sql))
1054 1054
         {
1055 1055
             return -1;
1056 1056
         }
@@ -1066,17 +1066,17 @@  discard block
 block discarded – undo
1066 1066
 	 *	@param	string	$field_desc 		Array with description of field format
1067 1067
 	 *	@return	int							<0 if KO, >0 if OK
1068 1068
      */
1069
-    function DDLUpdateField($table,$field_name,$field_desc)
1069
+    function DDLUpdateField($table, $field_name, $field_desc)
1070 1070
     {
1071 1071
         // phpcs:enable
1072 1072
         $sql = "ALTER TABLE ".$table;
1073 1073
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1074 1074
         if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1075
-            $sql.="(".$field_desc['value'].")";
1075
+            $sql .= "(".$field_desc['value'].")";
1076 1076
         }
1077 1077
 
1078
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1079
-        if (! $this->query($sql))
1078
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1079
+        if (!$this->query($sql))
1080 1080
             return -1;
1081 1081
         return 1;
1082 1082
     }
@@ -1089,14 +1089,14 @@  discard block
 block discarded – undo
1089 1089
 	 *	@param	string	$field_name 	Name of field to drop
1090 1090
 	 *	@return	int						<0 if KO, >0 if OK
1091 1091
      */
1092
-    function DDLDropField($table,$field_name)
1092
+    function DDLDropField($table, $field_name)
1093 1093
     {
1094 1094
         // phpcs:enable
1095
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1096
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1097
-        if (! $this->query($sql))
1095
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1096
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
1097
+        if (!$this->query($sql))
1098 1098
         {
1099
-            $this->error=$this->lasterror();
1099
+            $this->error = $this->lasterror();
1100 1100
             return -1;
1101 1101
         }
1102 1102
         return 1;
@@ -1113,38 +1113,38 @@  discard block
 block discarded – undo
1113 1113
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1114 1114
 	 *	@return	int									<0 if KO, >=0 if OK
1115 1115
      */
1116
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1116
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1117 1117
     {
1118 1118
         // phpcs:enable
1119 1119
         $sql = "INSERT INTO user ";
1120
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1121
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1122
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1120
+        $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1121
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1122
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1123 1123
 
1124
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1125
-        $resql=$this->query($sql);
1126
-        if (! $resql)
1124
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1125
+        $resql = $this->query($sql);
1126
+        if (!$resql)
1127 1127
         {
1128 1128
             return -1;
1129 1129
         }
1130 1130
 
1131 1131
         $sql = "INSERT INTO db ";
1132
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1133
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1134
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1132
+        $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1133
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1134
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1135 1135
 
1136 1136
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1137
-        $resql=$this->query($sql);
1138
-        if (! $resql)
1137
+        $resql = $this->query($sql);
1138
+        if (!$resql)
1139 1139
         {
1140 1140
             return -1;
1141 1141
         }
1142 1142
 
1143
-        $sql="FLUSH Privileges";
1143
+        $sql = "FLUSH Privileges";
1144 1144
 
1145 1145
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1146
-        $resql=$this->query($sql);
1147
-        if (! $resql)
1146
+        $resql = $this->query($sql);
1147
+        if (!$resql)
1148 1148
         {
1149 1149
             return -1;
1150 1150
         }
@@ -1169,7 +1169,7 @@  discard block
 block discarded – undo
1169 1169
     function getListOfCharacterSet()
1170 1170
     {
1171 1171
         $liste = array();
1172
-        $i=0;
1172
+        $i = 0;
1173 1173
         $liste[$i]['charset'] = 'UTF-8';
1174 1174
         $liste[$i]['description'] = 'UTF-8';
1175 1175
         return $liste;
@@ -1193,7 +1193,7 @@  discard block
 block discarded – undo
1193 1193
     function getListOfCollation()
1194 1194
     {
1195 1195
         $liste = array();
1196
-        $i=0;
1196
+        $i = 0;
1197 1197
         $liste[$i]['charset'] = 'UTF-8';
1198 1198
         $liste[$i]['description'] = 'UTF-8';
1199 1199
         return $liste;
@@ -1207,14 +1207,14 @@  discard block
 block discarded – undo
1207 1207
     function getPathOfDump()
1208 1208
     {
1209 1209
 	    // FIXME: not for SQLite
1210
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1210
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1211 1211
 
1212
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1212
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1213 1213
         if ($resql)
1214 1214
         {
1215
-            $liste=$this->fetch_array($resql);
1216
-            $basedir=$liste['Value'];
1217
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1215
+            $liste = $this->fetch_array($resql);
1216
+            $basedir = $liste['Value'];
1217
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1218 1218
         }
1219 1219
         return $fullpathofdump;
1220 1220
     }
@@ -1227,14 +1227,14 @@  discard block
 block discarded – undo
1227 1227
     function getPathOfRestore()
1228 1228
     {
1229 1229
 	    // FIXME: not for SQLite
1230
-        $fullpathofimport='/pathtomysql/mysql';
1230
+        $fullpathofimport = '/pathtomysql/mysql';
1231 1231
 
1232
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1232
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1233 1233
         if ($resql)
1234 1234
         {
1235
-            $liste=$this->fetch_array($resql);
1236
-            $basedir=$liste['Value'];
1237
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1235
+            $liste = $this->fetch_array($resql);
1236
+            $basedir = $liste['Value'];
1237
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1238 1238
         }
1239 1239
         return $fullpathofimport;
1240 1240
     }
@@ -1245,18 +1245,18 @@  discard block
 block discarded – undo
1245 1245
 	 * @param	string	$filter		Filter list on a particular value
1246 1246
 	 * @return	array				Array of key-values (key=>value)
1247 1247
      */
1248
-    function getServerParametersValues($filter='')
1248
+    function getServerParametersValues($filter = '')
1249 1249
     {
1250
-        $result=array();
1250
+        $result = array();
1251 1251
         static $pragmas;
1252
-        if (! isset($pragmas)) {
1252
+        if (!isset($pragmas)) {
1253 1253
             // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1254 1254
             // indépendante de la base de données.
1255 1255
             // cf. http://www.sqlite.org/pragma.html
1256 1256
             $pragmas = array(
1257 1257
                 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1258 1258
                 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1259
-				'compile_options', 'data_version',	/*'database_list',*/
1259
+				'compile_options', 'data_version', /*'database_list',*/
1260 1260
                 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1261 1261
                 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1262 1262
                 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
@@ -1271,9 +1271,9 @@  discard block
 block discarded – undo
1271 1271
         }
1272 1272
 
1273 1273
         // TODO prendre en compte le filtre
1274
-        foreach($pragmas as $var) {
1274
+        foreach ($pragmas as $var) {
1275 1275
             $sql = "PRAGMA $var";
1276
-            $resql=$this->query($sql);
1276
+            $resql = $this->query($sql);
1277 1277
             if ($resql)
1278 1278
             {
1279 1279
                 $obj = $this->fetch_row($resql);
@@ -1294,9 +1294,9 @@  discard block
 block discarded – undo
1294 1294
 	 * @param	string	$filter		Filter list on a particular value
1295 1295
 	 * @return  array				Array of key-values (key=>value)
1296 1296
      */
1297
-    function getServerStatusValues($filter='')
1297
+    function getServerStatusValues($filter = '')
1298 1298
     {
1299
-        $result=array();
1299
+        $result = array();
1300 1300
         /*
1301 1301
         $sql='SHOW STATUS';
1302 1302
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
@@ -1323,10 +1323,10 @@  discard block
 block discarded – undo
1323 1323
     {
1324 1324
         if ($this->db)
1325 1325
         {
1326
-        	$newname=preg_replace('/_/','',$name);
1327
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1326
+        	$newname = preg_replace('/_/', '', $name);
1327
+            $localname = __CLASS__.'::'.'db'.$newname;
1328 1328
             $reflectClass = new ReflectionClass(__CLASS__);
1329
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1329
+            $reflectFunction = $reflectClass->getMethod('db'.$newname);
1330 1330
             if ($arg_count < 0) {
1331 1331
                 $arg_count = $reflectFunction->getNumberOfParameters();
1332 1332
             }
@@ -1351,7 +1351,7 @@  discard block
 block discarded – undo
1351 1351
         // phpcs:enable
1352 1352
         $y = $year;
1353 1353
         if ($y == 0 && $month == 0) return 0;
1354
-        $num = (365* $y + 31 * ($month - 1) + $day);
1354
+        $num = (365 * $y + 31 * ($month - 1) + $day);
1355 1355
         if ($month <= 2) {
1356 1356
             $y--; }
1357 1357
         else {
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
     private static function calc_days_in_year($year)
1387 1387
     {
1388 1388
         // phpcs:enable
1389
-        return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1389
+        return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
1390 1390
     }
1391 1391
 
1392 1392
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -1403,41 +1403,41 @@  discard block
 block discarded – undo
1403 1403
     private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year)
1404 1404
     {
1405 1405
         // phpcs:enable
1406
-        $daynr=self::calc_daynr($year,$month,$day);
1407
-        $first_daynr=self::calc_daynr($year,1,1);
1408
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1409
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1410
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1406
+        $daynr = self::calc_daynr($year, $month, $day);
1407
+        $first_daynr = self::calc_daynr($year, 1, 1);
1408
+        $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1409
+        $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1410
+        $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1411 1411
 
1412
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1413
-        $calc_year=$year;
1412
+        $weekday = self::calc_weekday($first_daynr, !$monday_first);
1413
+        $calc_year = $year;
1414 1414
 
1415
-        if ($month == 1 && $day <= 7-$weekday)
1415
+        if ($month == 1 && $day <= 7 - $weekday)
1416 1416
         {
1417 1417
             if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1418 1418
                 return 0;
1419
-            $week_year= 1;
1419
+            $week_year = 1;
1420 1420
             $calc_year--;
1421
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1422
-            $weekday= ($weekday + 53*7- $days) % 7;
1421
+            $first_daynr -= ($days = self::calc_days_in_year($calc_year));
1422
+            $weekday = ($weekday + 53 * 7 - $days) % 7;
1423 1423
       }
1424 1424
 
1425 1425
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1426
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1426
+        $days = $daynr - ($first_daynr + (7 - $weekday));
1427 1427
       }
1428 1428
       else {
1429
-        $days= $daynr - ($first_daynr - $weekday);
1429
+        $days = $daynr - ($first_daynr - $weekday);
1430 1430
       }
1431 1431
 
1432
-      if ($week_year && $days >= 52*7)
1432
+      if ($week_year && $days >= 52 * 7)
1433 1433
       {
1434
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1434
+        $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
1435 1435
         if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1436 1436
         {
1437 1437
           $calc_year++;
1438 1438
           return 1;
1439 1439
         }
1440 1440
       }
1441
-      return floor($days/7+1);
1441
+      return floor($days / 7 + 1);
1442 1442
     }
1443 1443
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/mysqli.class.php 1 patch
Spacing   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 
32 32
 use Alxarafe\Helpers\Debug;
33 33
 
34
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
34
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
35 35
 
36 36
 /**
37 37
  *	Class to manage Dolibarr database access for a MySQL database using the MySQLi extension
@@ -41,11 +41,11 @@  discard block
 block discarded – undo
41 41
 	/** @var mysqli Database object */
42 42
 	public $db;
43 43
     //! Database type
44
-    public $type='mysqli';
44
+    public $type = 'mysqli';
45 45
     //! Database label
46
-    const LABEL='MySQL or MariaDB';
46
+    const LABEL = 'MySQL or MariaDB';
47 47
     //! Version min database
48
-    const VERSIONMIN='5.0.3';
48
+    const VERSIONMIN = '5.0.3';
49 49
 	/** @var mysqli_result Resultset of last query */
50 50
 	private $_results;
51 51
 
@@ -60,36 +60,36 @@  discard block
 block discarded – undo
60 60
 	 *	@param	    string	$name		Nom de la database
61 61
 	 *	@param	    int		$port		Port of database server
62 62
      */
63
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
63
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
64 64
     {
65
-        global $conf,$langs;
65
+        global $conf, $langs;
66 66
 
67 67
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
68
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
69
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
68
+        if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
69
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
70 70
 
71
-        $this->database_user=$user;
72
-        $this->database_host=$host;
73
-        $this->database_port=$port;
71
+        $this->database_user = $user;
72
+        $this->database_host = $host;
73
+        $this->database_port = $port;
74 74
 
75
-        $this->transaction_opened=0;
75
+        $this->transaction_opened = 0;
76 76
 
77 77
         //print "Name DB: $host,$user,$pass,$name<br>";
78 78
 
79
-        if (! class_exists('mysqli'))
79
+        if (!class_exists('mysqli'))
80 80
         {
81 81
             $this->connected = false;
82 82
             $this->ok = false;
83
-            $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
84
-            dol_syslog(get_class($this)."::DoliDBMysqli : Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.",LOG_ERR);
83
+            $this->error = "Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
84
+            dol_syslog(get_class($this)."::DoliDBMysqli : Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.", LOG_ERR);
85 85
         }
86 86
 
87
-        if (! $host)
87
+        if (!$host)
88 88
         {
89 89
             $this->connected = false;
90 90
             $this->ok = false;
91
-            $this->error=$langs->trans("ErrorWrongHostParameter");
92
-            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
91
+            $this->error = $langs->trans("ErrorWrongHostParameter");
92
+            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters", LOG_ERR);
93 93
         }
94 94
 
95 95
 		// Try server connection
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 			$this->connected = false;
101 101
 			$this->ok = false;
102 102
 			$this->error = $this->db->connect_error;
103
-			dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
103
+			dol_syslog(get_class($this)."::DoliDBMysqli Connect error: ".$this->error, LOG_ERR);
104 104
 		} else {
105 105
 			$this->connected = true;
106 106
 			$this->ok = true;
@@ -116,16 +116,16 @@  discard block
 block discarded – undo
116 116
                 $this->ok = true;
117 117
 
118 118
                 // If client is old latin, we force utf8
119
-                $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
120
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
119
+                $clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
120
+                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
121 121
 
122 122
 				if ($this->db->character_set_name() != $clientmustbe) {
123
-					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
123
+					$this->db->set_charset($clientmustbe); // This set charset, but with a bad collation
124 124
 
125 125
 					$collation = $conf->db->dolibarr_main_db_collation;
126
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
126
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
127 127
 
128
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
128
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
129 129
 				}
130 130
             }
131 131
             else
@@ -133,8 +133,8 @@  discard block
 block discarded – undo
133 133
                 $this->database_selected = false;
134 134
                 $this->database_name = '';
135 135
                 $this->ok = false;
136
-                $this->error=$this->error();
137
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
136
+                $this->error = $this->error();
137
+                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error, LOG_ERR);
138 138
             }
139 139
         }
140 140
         else
@@ -145,16 +145,16 @@  discard block
 block discarded – undo
145 145
             if ($this->connected)
146 146
             {
147 147
             	// If client is old latin, we force utf8
148
-            	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
149
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
148
+            	$clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
149
+            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
150 150
 
151 151
 				if ($this->db->character_set_name() != $clientmustbe) {
152
-					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
152
+					$this->db->set_charset($clientmustbe); // This set utf8_general_ci
153 153
 
154 154
 					$collation = $conf->db->dolibarr_main_db_collation;
155
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
155
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
156 156
 
157
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
157
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
158 158
 				}
159 159
 			}
160 160
         }
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
169 169
      *  @return    string   		SQL request line converted
170 170
      */
171
-    static function convertSQLFromMysql($line,$type='ddl')
171
+    static function convertSQLFromMysql($line, $type = 'ddl')
172 172
     {
173 173
         return $line;
174 174
     }
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 	 */
202 202
 	function connect($host, $login, $passwd, $name, $port = 0)
203 203
 	{
204
-		dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
204
+		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
205 205
 
206 206
 		// Can also be
207 207
 		// mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
@@ -240,8 +240,8 @@  discard block
 block discarded – undo
240 240
     {
241 241
         if ($this->db)
242 242
         {
243
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
244
-            $this->connected=false;
243
+	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
244
+            $this->connected = false;
245 245
             return $this->db->close();
246 246
         }
247 247
         return false;
@@ -256,17 +256,17 @@  discard block
 block discarded – undo
256 256
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
257 257
      *	@return	bool|mysqli_result		Resultset of answer
258 258
      */
259
-    function query($query,$usesavepoint=0,$type='auto')
259
+    function query($query, $usesavepoint = 0, $type = 'auto')
260 260
     {
261 261
     	global $conf;
262 262
 
263 263
         $query = trim($query);
264 264
 
265
-        Debug::addMessage('SQL', 'MySQL: ' . $query);
265
+        Debug::addMessage('SQL', 'MySQL: '.$query);
266 266
 
267
-        if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
267
+        if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
268 268
 
269
-        if (! $this->database_name)
269
+        if (!$this->database_name)
270 270
         {
271 271
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
272 272
             $ret = $this->db->query($query);
@@ -276,19 +276,19 @@  discard block
 block discarded – undo
276 276
             $ret = $this->db->query($query);
277 277
         }
278 278
 
279
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
279
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
280 280
         {
281 281
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
282
-            if (! $ret)
282
+            if (!$ret)
283 283
             {
284 284
                 $this->lastqueryerror = $query;
285 285
                 $this->lasterror = $this->error();
286 286
                 $this->lasterrno = $this->errno();
287 287
 
288
-				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);	// Log of request was not yet done previously
288
+				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
289 289
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
290 290
             }
291
-            $this->lastquery=$query;
291
+            $this->lastquery = $query;
292 292
             $this->_results = $ret;
293 293
         }
294 294
 
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
     {
307 307
         // phpcs:enable
308 308
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
309
-        if (! is_object($resultset)) { $resultset=$this->_results; }
309
+        if (!is_object($resultset)) { $resultset = $this->_results; }
310 310
 		return $resultset->fetch_object();
311 311
     }
312 312
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
     {
323 323
         // phpcs:enable
324 324
         // If resultset not provided, we take the last used by connexion
325
-        if (! is_object($resultset)) { $resultset=$this->_results; }
325
+        if (!is_object($resultset)) { $resultset = $this->_results; }
326 326
         return $resultset->fetch_array();
327 327
     }
328 328
 
@@ -337,9 +337,9 @@  discard block
 block discarded – undo
337 337
     {
338 338
         // phpcs:enable
339 339
         // If resultset not provided, we take the last used by connexion
340
-        if (! is_bool($resultset))
340
+        if (!is_bool($resultset))
341 341
         {
342
-            if (! is_object($resultset)) { $resultset=$this->_results; }
342
+            if (!is_object($resultset)) { $resultset = $this->_results; }
343 343
             return $resultset->fetch_row();
344 344
         }
345 345
         else
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
     {
362 362
         // phpcs:enable
363 363
         // If resultset not provided, we take the last used by connexion
364
-        if (! is_object($resultset)) { $resultset=$this->_results; }
364
+        if (!is_object($resultset)) { $resultset = $this->_results; }
365 365
         return $resultset->num_rows;
366 366
     }
367 367
 
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
     {
378 378
         // phpcs:enable
379 379
         // If resultset not provided, we take the last used by connexion
380
-        if (! is_object($resultset)) { $resultset=$this->_results; }
380
+        if (!is_object($resultset)) { $resultset = $this->_results; }
381 381
         // mysql necessite un link de base pour cette fonction contrairement
382 382
         // a pqsql qui prend un resultset
383 383
         return $this->db->affected_rows;
@@ -390,10 +390,10 @@  discard block
 block discarded – undo
390 390
      *	@param  mysqli_result	$resultset	Curseur de la requete voulue
391 391
      *	@return	void
392 392
      */
393
-    function free($resultset=null)
393
+    function free($resultset = null)
394 394
     {
395 395
         // If resultset not provided, we take the last used by connexion
396
-        if (! is_object($resultset)) { $resultset=$this->_results; }
396
+        if (!is_object($resultset)) { $resultset = $this->_results; }
397 397
         // Si resultset en est un, on libere la memoire
398 398
         if (is_object($resultset)) $resultset->free_result();
399 399
     }
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
      */
417 417
     function errno()
418 418
     {
419
-        if (! $this->connected) {
419
+        if (!$this->connected) {
420 420
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
421 421
             return 'DB_ERROR_FAILED_TO_CONNECT';
422 422
         } else {
@@ -448,15 +448,15 @@  discard block
 block discarded – undo
448 448
             1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
449 449
             1216 => 'DB_ERROR_NO_PARENT',
450 450
             1217 => 'DB_ERROR_CHILD_EXISTS',
451
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
451
+            1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
452 452
             1451 => 'DB_ERROR_CHILD_EXISTS'
453 453
             );
454 454
 
455 455
             if (isset($errorcode_map[$this->db->errno])) {
456 456
                 return $errorcode_map[$this->db->errno];
457 457
             }
458
-            $errno=$this->db->errno;
459
-            return ($errno?'DB_ERROR_'.$errno:'0');
458
+            $errno = $this->db->errno;
459
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
460 460
         }
461 461
     }
462 462
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
      */
468 468
     function error()
469 469
     {
470
-        if (! $this->connected) {
470
+        if (!$this->connected) {
471 471
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
472 472
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
473 473
         }
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 	 * @param	string	$fieldid	Field name
485 485
 	 * @return  int|string			Id of row
486 486
      */
487
-    function last_insert_id($tab,$fieldid='rowid')
487
+    function last_insert_id($tab, $fieldid = 'rowid')
488 488
     {
489 489
         // phpcs:enable
490 490
         return $this->db->insert_id;
@@ -499,17 +499,17 @@  discard block
 block discarded – undo
499 499
      * 	@return	string					XXX(field) or XXX('value') or field or 'value'
500 500
      *
501 501
      */
502
-    function encrypt($fieldorvalue, $withQuotes=0)
502
+    function encrypt($fieldorvalue, $withQuotes = 0)
503 503
     {
504 504
         global $conf;
505 505
 
506 506
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
507
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
507
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
508 508
 
509 509
         //Encryption key
510
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
510
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
511 511
 
512
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
512
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
513 513
 
514 514
         if ($cryptType && !empty($cryptKey))
515 515
         {
@@ -537,10 +537,10 @@  discard block
 block discarded – undo
537 537
         global $conf;
538 538
 
539 539
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
540
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
540
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
541 541
 
542 542
         //Encryption key
543
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
543
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
544 544
 
545 545
         $return = $value;
546 546
 
@@ -569,10 +569,10 @@  discard block
 block discarded – undo
569 569
     function DDLGetConnectId()
570 570
     {
571 571
         // phpcs:enable
572
-        $resql=$this->query('SELECT CONNECTION_ID()');
572
+        $resql = $this->query('SELECT CONNECTION_ID()');
573 573
         if ($resql)
574 574
         {
575
-            $row=$this->fetch_row($resql);
575
+            $row = $this->fetch_row($resql);
576 576
             return $row[0];
577 577
         }
578 578
         else return '?';
@@ -590,24 +590,24 @@  discard block
 block discarded – undo
590 590
 	 * 	@param	string	$owner			Username of database owner
591 591
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
592 592
      */
593
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
593
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
594 594
     {
595 595
         // phpcs:enable
596
-        if (empty($charset))   $charset=$this->forcecharset;
597
-        if (empty($collation)) $collation=$this->forcecollate;
596
+        if (empty($charset))   $charset = $this->forcecharset;
597
+        if (empty($collation)) $collation = $this->forcecollate;
598 598
 
599 599
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
600 600
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
601
-		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
601
+		$sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
602 602
 
603
-        dol_syslog($sql,LOG_DEBUG);
604
-        $ret=$this->query($sql);
605
-        if (! $ret)
603
+        dol_syslog($sql, LOG_DEBUG);
604
+        $ret = $this->query($sql);
605
+        if (!$ret)
606 606
         {
607 607
             // We try again for compatibility with Mysql < 4.1.1
608 608
             $sql = "CREATE DATABASE `".$this->escape($database)."`";
609
-            dol_syslog($sql,LOG_DEBUG);
610
-            $ret=$this->query($sql);
609
+            dol_syslog($sql, LOG_DEBUG);
610
+            $ret = $this->query($sql);
611 611
         }
612 612
         return $ret;
613 613
     }
@@ -620,19 +620,19 @@  discard block
 block discarded – undo
620 620
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
621 621
 	 *  @return	array					List of tables in an array
622 622
      */
623
-    function DDLListTables($database, $table='')
623
+    function DDLListTables($database, $table = '')
624 624
     {
625 625
         // phpcs:enable
626
-        $listtables=array();
626
+        $listtables = array();
627 627
 
628 628
         $like = '';
629 629
         if ($table) $like = "LIKE '".$table."'";
630
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
630
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
631 631
         //print $sql;
632 632
         $result = $this->query($sql);
633 633
         if ($result)
634 634
         {
635
-            while($row = $this->fetch_row($result))
635
+            while ($row = $this->fetch_row($result))
636 636
             {
637 637
                 $listtables[] = $row[0];
638 638
             }
@@ -650,15 +650,15 @@  discard block
 block discarded – undo
650 650
     function DDLInfoTable($table)
651 651
     {
652 652
         // phpcs:enable
653
-        $infotables=array();
653
+        $infotables = array();
654 654
 
655
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
655
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
656 656
 
657
-        dol_syslog($sql,LOG_DEBUG);
657
+        dol_syslog($sql, LOG_DEBUG);
658 658
         $result = $this->query($sql);
659 659
         if ($result)
660 660
         {
661
-            while($row = $this->fetch_row($result))
661
+            while ($row = $this->fetch_row($result))
662 662
             {
663 663
                 $infotables[] = $row;
664 664
             }
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
680 680
 	 *	@return	    int						<0 if KO, >=0 if OK
681 681
      */
682
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
682
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
683 683
     {
684 684
         // phpcs:enable
685 685
 	    // FIXME: $fulltext_keys parameter is unused
@@ -687,64 +687,64 @@  discard block
 block discarded – undo
687 687
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
688 688
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
689 689
         $sql = "CREATE TABLE ".$table."(";
690
-        $i=0;
691
-        foreach($fields as $field_name => $field_desc)
690
+        $i = 0;
691
+        foreach ($fields as $field_name => $field_desc)
692 692
         {
693 693
         	$sqlfields[$i] = $field_name." ";
694
-			$sqlfields[$i]  .= $field_desc['type'];
695
-			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
694
+			$sqlfields[$i] .= $field_desc['type'];
695
+			if (preg_match("/^[^\s]/i", $field_desc['value'])) {
696 696
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
697 697
 			}
698
-			if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
698
+			if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
699 699
 				$sqlfields[$i]  .= " ".$field_desc['attribute'];
700 700
 			}
701
-			if( preg_match("/^[^\s]/i",$field_desc['default']))
701
+			if (preg_match("/^[^\s]/i", $field_desc['default']))
702 702
 			{
703
-				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
703
+				if ((preg_match("/null/i", $field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i", $field_desc['default']))) {
704 704
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
705 705
 				}
706 706
 				else {
707 707
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
708 708
 				}
709 709
 			}
710
-			if( preg_match("/^[^\s]/i",$field_desc['null'])) {
710
+			if (preg_match("/^[^\s]/i", $field_desc['null'])) {
711 711
 				$sqlfields[$i]  .= " ".$field_desc['null'];
712 712
 			}
713
-			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
713
+			if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
714 714
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
715 715
 			}
716 716
             $i++;
717 717
         }
718
-        if($primary_key != "")
718
+        if ($primary_key != "")
719 719
         $pk = "primary key(".$primary_key.")";
720 720
 
721
-        if(is_array($unique_keys)) {
721
+        if (is_array($unique_keys)) {
722 722
             $i = 0;
723
-            foreach($unique_keys as $key => $value)
723
+            foreach ($unique_keys as $key => $value)
724 724
             {
725 725
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
726 726
                 $i++;
727 727
             }
728 728
         }
729
-        if(is_array($keys))
729
+        if (is_array($keys))
730 730
         {
731 731
             $i = 0;
732
-            foreach($keys as $key => $value)
732
+            foreach ($keys as $key => $value)
733 733
             {
734 734
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
735 735
                 $i++;
736 736
             }
737 737
         }
738
-        $sql .= implode(',',$sqlfields);
739
-        if($primary_key != "")
738
+        $sql .= implode(',', $sqlfields);
739
+        if ($primary_key != "")
740 740
         $sql .= ",".$pk;
741
-        if($unique_keys != "")
742
-        $sql .= ",".implode(',',$sqluq);
743
-        if(is_array($keys))
744
-        $sql .= ",".implode(',',$sqlk);
745
-        $sql .=") engine=".$type;
741
+        if ($unique_keys != "")
742
+        $sql .= ",".implode(',', $sqluq);
743
+        if (is_array($keys))
744
+        $sql .= ",".implode(',', $sqlk);
745
+        $sql .= ") engine=".$type;
746 746
 
747
-        if(! $this->query($sql))
747
+        if (!$this->query($sql))
748 748
         return -1;
749 749
         else
750 750
         return 1;
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
         // phpcs:enable
763 763
         $sql = "DROP TABLE ".$table;
764 764
 
765
-		if (! $this->query($sql))
765
+		if (!$this->query($sql))
766 766
  			return -1;
767 767
     	else
768 768
     		return 1;
@@ -776,12 +776,12 @@  discard block
 block discarded – undo
776 776
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
777 777
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
778 778
      */
779
-    function DDLDescTable($table,$field="")
779
+    function DDLDescTable($table, $field = "")
780 780
     {
781 781
         // phpcs:enable
782
-        $sql="DESC ".$table." ".$field;
782
+        $sql = "DESC ".$table." ".$field;
783 783
 
784
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
784
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
785 785
         $this->_results = $this->query($sql);
786 786
         return $this->_results;
787 787
     }
@@ -796,42 +796,42 @@  discard block
 block discarded – undo
796 796
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
797 797
 	 *	@return	int							<0 if KO, >0 if OK
798 798
      */
799
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
799
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
800 800
     {
801 801
         // phpcs:enable
802 802
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
803 803
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
804
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
805
-        $sql.= $field_desc['type'];
806
-        if (preg_match("/^[^\s]/i",$field_desc['value']))
804
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
805
+        $sql .= $field_desc['type'];
806
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
807 807
         {
808
-            if (! in_array($field_desc['type'],array('date','datetime')))
808
+            if (!in_array($field_desc['type'], array('date', 'datetime')))
809 809
             {
810
-                $sql.= "(".$field_desc['value'].")";
810
+                $sql .= "(".$field_desc['value'].")";
811 811
             }
812 812
         }
813
-        if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i",$field_desc['attribute']))
813
+        if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute']))
814 814
         {
815
-        	$sql.= " ".$field_desc['attribute'];
815
+        	$sql .= " ".$field_desc['attribute'];
816 816
         }
817
-        if (isset($field_desc['null']) && preg_match("/^[^\s]/i",$field_desc['null']))
817
+        if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null']))
818 818
         {
819
-        	$sql.= " ".$field_desc['null'];
819
+        	$sql .= " ".$field_desc['null'];
820 820
         }
821
-        if (isset($field_desc['default']) && preg_match("/^[^\s]/i",$field_desc['default']))
821
+        if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default']))
822 822
         {
823
-            if(preg_match("/null/i",$field_desc['default']))
824
-            $sql.= " default ".$field_desc['default'];
823
+            if (preg_match("/null/i", $field_desc['default']))
824
+            $sql .= " default ".$field_desc['default'];
825 825
             else
826
-            $sql.= " default '".$field_desc['default']."'";
826
+            $sql .= " default '".$field_desc['default']."'";
827 827
         }
828
-        if (isset($field_desc['extra']) && preg_match("/^[^\s]/i",$field_desc['extra']))
828
+        if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra']))
829 829
         {
830
-        	$sql.= " ".$field_desc['extra'];
830
+        	$sql .= " ".$field_desc['extra'];
831 831
         }
832
-        $sql.= " ".$field_position;
832
+        $sql .= " ".$field_position;
833 833
 
834
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
834
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
835 835
         if ($this->query($sql)) {
836 836
             return 1;
837 837
         }
@@ -847,39 +847,39 @@  discard block
 block discarded – undo
847 847
 	 *	@param	string	$field_desc 		Array with description of field format
848 848
 	 *	@return	int							<0 if KO, >0 if OK
849 849
      */
850
-    function DDLUpdateField($table,$field_name,$field_desc)
850
+    function DDLUpdateField($table, $field_name, $field_desc)
851 851
     {
852 852
         // phpcs:enable
853 853
         $sql = "ALTER TABLE ".$table;
854 854
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
855 855
         if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
856
-        	$sql.="(".$field_desc['value'].")";
856
+        	$sql .= "(".$field_desc['value'].")";
857 857
         }
858 858
         if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
859 859
         {
860 860
         	// We will try to change format of column to NOT NULL. To be sure the ALTER works, we try to update fields that are NULL
861 861
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
862 862
         	{
863
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
863
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
864 864
         		$this->query($sqlbis);
865 865
         	}
866 866
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
867 867
         	{
868
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
868
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
869 869
         		$this->query($sqlbis);
870 870
         	}
871 871
 
872
-        	$sql.=" NOT NULL";
872
+        	$sql .= " NOT NULL";
873 873
         }
874 874
 
875 875
         if ($field_desc['default'] != '')
876 876
         {
877
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
878
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
877
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
878
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
879 879
         }
880 880
 
881
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
882
-        if (! $this->query($sql))
881
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
882
+        if (!$this->query($sql))
883 883
         return -1;
884 884
         else
885 885
         return 1;
@@ -893,15 +893,15 @@  discard block
 block discarded – undo
893 893
 	 *	@param	string	$field_name 	Name of field to drop
894 894
 	 *	@return	int						<0 if KO, >0 if OK
895 895
      */
896
-    function DDLDropField($table,$field_name)
896
+    function DDLDropField($table, $field_name)
897 897
     {
898 898
         // phpcs:enable
899
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
900
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
899
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
900
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
901 901
         if ($this->query($sql)) {
902 902
             return 1;
903 903
         }
904
-        $this->error=$this->lasterror();
904
+        $this->error = $this->lasterror();
905 905
         return -1;
906 906
     }
907 907
 
@@ -916,13 +916,13 @@  discard block
 block discarded – undo
916 916
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
917 917
 	 *	@return	int									<0 if KO, >=0 if OK
918 918
      */
919
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
919
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
920 920
     {
921 921
         // phpcs:enable
922 922
         $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
923
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
924
-        $resql=$this->query($sql);
925
-        if (! $resql)
923
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
924
+        $resql = $this->query($sql);
925
+        if (!$resql)
926 926
         {
927 927
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
928 928
             {
@@ -935,18 +935,18 @@  discard block
 block discarded – undo
935 935
             }
936 936
         }
937 937
         $sql = "GRANT ALL PRIVILEGES ON ".$this->escape($dolibarr_main_db_name).".* TO '".$this->escape($dolibarr_main_db_user)."'@'".$this->escape($dolibarr_main_db_host)."' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
938
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
939
-        $resql=$this->query($sql);
940
-        if (! $resql)
938
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
939
+        $resql = $this->query($sql);
940
+        if (!$resql)
941 941
         {
942 942
             return -1;
943 943
         }
944 944
 
945
-        $sql="FLUSH Privileges";
945
+        $sql = "FLUSH Privileges";
946 946
 
947 947
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
948
-        $resql=$this->query($sql);
949
-        if (! $resql)
948
+        $resql = $this->query($sql);
949
+        if (!$resql)
950 950
         {
951 951
             return -1;
952 952
         }
@@ -963,13 +963,13 @@  discard block
 block discarded – undo
963 963
      */
964 964
     function getDefaultCharacterSetDatabase()
965 965
     {
966
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
966
+        $resql = $this->query('SHOW VARIABLES LIKE \'character_set_database\'');
967 967
         if (!$resql)
968 968
         {
969 969
             // version Mysql < 4.1.1
970 970
             return $this->forcecharset;
971 971
         }
972
-        $liste=$this->fetch_array($resql);
972
+        $liste = $this->fetch_array($resql);
973 973
         $tmpval = $liste['Value'];
974 974
 
975 975
         return $tmpval;
@@ -982,12 +982,12 @@  discard block
 block discarded – undo
982 982
      */
983 983
     function getListOfCharacterSet()
984 984
     {
985
-        $resql=$this->query('SHOW CHARSET');
985
+        $resql = $this->query('SHOW CHARSET');
986 986
         $liste = array();
987 987
         if ($resql)
988 988
         {
989 989
             $i = 0;
990
-            while ($obj = $this->fetch_object($resql) )
990
+            while ($obj = $this->fetch_object($resql))
991 991
             {
992 992
                 $liste[$i]['charset'] = $obj->Charset;
993 993
                 $liste[$i]['description'] = $obj->Description;
@@ -1009,13 +1009,13 @@  discard block
 block discarded – undo
1009 1009
      */
1010 1010
     function getDefaultCollationDatabase()
1011 1011
     {
1012
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
1012
+        $resql = $this->query('SHOW VARIABLES LIKE \'collation_database\'');
1013 1013
         if (!$resql)
1014 1014
         {
1015 1015
             // version Mysql < 4.1.1
1016 1016
             return $this->forcecollate;
1017 1017
         }
1018
-        $liste=$this->fetch_array($resql);
1018
+        $liste = $this->fetch_array($resql);
1019 1019
         $tmpval = $liste['Value'];
1020 1020
 
1021 1021
         return $tmpval;
@@ -1028,12 +1028,12 @@  discard block
 block discarded – undo
1028 1028
      */
1029 1029
     function getListOfCollation()
1030 1030
     {
1031
-        $resql=$this->query('SHOW COLLATION');
1031
+        $resql = $this->query('SHOW COLLATION');
1032 1032
         $liste = array();
1033 1033
         if ($resql)
1034 1034
         {
1035 1035
             $i = 0;
1036
-            while ($obj = $this->fetch_object($resql) )
1036
+            while ($obj = $this->fetch_object($resql))
1037 1037
             {
1038 1038
                 $liste[$i]['collation'] = $obj->Collation;
1039 1039
                 $i++;
@@ -1053,14 +1053,14 @@  discard block
 block discarded – undo
1053 1053
      */
1054 1054
     function getPathOfDump()
1055 1055
     {
1056
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1056
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1057 1057
 
1058
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1058
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1059 1059
         if ($resql)
1060 1060
         {
1061
-            $liste=$this->fetch_array($resql);
1062
-            $basedir=$liste['Value'];
1063
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1061
+            $liste = $this->fetch_array($resql);
1062
+            $basedir = $liste['Value'];
1063
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1064 1064
         }
1065 1065
         return $fullpathofdump;
1066 1066
     }
@@ -1072,14 +1072,14 @@  discard block
 block discarded – undo
1072 1072
      */
1073 1073
     function getPathOfRestore()
1074 1074
     {
1075
-        $fullpathofimport='/pathtomysql/mysql';
1075
+        $fullpathofimport = '/pathtomysql/mysql';
1076 1076
 
1077
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1077
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1078 1078
         if ($resql)
1079 1079
         {
1080
-            $liste=$this->fetch_array($resql);
1081
-            $basedir=$liste['Value'];
1082
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1080
+            $liste = $this->fetch_array($resql);
1081
+            $basedir = $liste['Value'];
1082
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1083 1083
         }
1084 1084
         return $fullpathofimport;
1085 1085
     }
@@ -1090,16 +1090,16 @@  discard block
 block discarded – undo
1090 1090
      * @param	string	$filter		Filter list on a particular value
1091 1091
 	 * @return	array				Array of key-values (key=>value)
1092 1092
      */
1093
-    function getServerParametersValues($filter='')
1093
+    function getServerParametersValues($filter = '')
1094 1094
     {
1095
-        $result=array();
1095
+        $result = array();
1096 1096
 
1097
-        $sql='SHOW VARIABLES';
1098
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1099
-        $resql=$this->query($sql);
1097
+        $sql = 'SHOW VARIABLES';
1098
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1099
+        $resql = $this->query($sql);
1100 1100
         if ($resql)
1101 1101
         {
1102
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1102
+        	while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1103 1103
         }
1104 1104
 
1105 1105
         return $result;
@@ -1111,16 +1111,16 @@  discard block
 block discarded – undo
1111 1111
      * @param	string	$filter		Filter list on a particular value
1112 1112
 	 * @return  array				Array of key-values (key=>value)
1113 1113
      */
1114
-    function getServerStatusValues($filter='')
1114
+    function getServerStatusValues($filter = '')
1115 1115
     {
1116
-        $result=array();
1116
+        $result = array();
1117 1117
 
1118
-        $sql='SHOW STATUS';
1119
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1120
-        $resql=$this->query($sql);
1118
+        $sql = 'SHOW STATUS';
1119
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1120
+        $resql = $this->query($sql);
1121 1121
         if ($resql)
1122 1122
         {
1123
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1123
+            while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1124 1124
         }
1125 1125
 
1126 1126
         return $result;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/pgsql.class.php 1 patch
Spacing   +263 added lines, -263 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 
36 36
 use Alxarafe\Helpers\Debug;
37 37
 
38
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
38
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
39 39
 
40 40
 /**
41 41
  *	Class to drive a Postgresql database for Dolibarr
@@ -43,15 +43,15 @@  discard block
 block discarded – undo
43 43
 class DoliDBPgsql extends DoliDB
44 44
 {
45 45
     //! Database type
46
-	public $type='pgsql';            // Name of manager
46
+	public $type = 'pgsql'; // Name of manager
47 47
     //! Database label
48
-	const LABEL='PostgreSQL';      // Label of manager
48
+	const LABEL = 'PostgreSQL'; // Label of manager
49 49
 	//! Charset
50
-	var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
50
+	var $forcecharset = 'UTF8'; // Can't be static as it may be forced with a dynamic value
51 51
     //! Collate used to force collate when creating database
52
-    var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
52
+    var $forcecollate = ''; // Can't be static as it may be forced with a dynamic value
53 53
 	//! Version min database
54
-	const VERSIONMIN='9.0.0';	// Version min database
54
+	const VERSIONMIN = '9.0.0'; // Version min database
55 55
 	/** @var resource Resultset of last query */
56 56
 	private $_results;
57 57
 
@@ -69,37 +69,37 @@  discard block
 block discarded – undo
69 69
 	 *	@param	    string	$name		Nom de la database
70 70
 	 *	@param	    int		$port		Port of database server
71 71
 	 */
72
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
72
+	function __construct($type, $host, $user, $pass, $name = '', $port = 0)
73 73
 	{
74
-		global $conf,$langs;
74
+		global $conf, $langs;
75 75
 
76 76
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
77
-		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
78
-		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
77
+		if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
78
+		if (!empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate = $conf->db->dolibarr_main_db_collation;
79 79
 
80
-		$this->database_user=$user;
81
-        $this->database_host=$host;
82
-        $this->database_port=$port;
80
+		$this->database_user = $user;
81
+        $this->database_host = $host;
82
+        $this->database_port = $port;
83 83
 
84
-		$this->transaction_opened=0;
84
+		$this->transaction_opened = 0;
85 85
 
86 86
 		//print "Name DB: $host,$user,$pass,$name<br>";
87 87
 
88
-		if (! function_exists("pg_connect"))
88
+		if (!function_exists("pg_connect"))
89 89
 		{
90 90
 			$this->connected = false;
91 91
 			$this->ok = false;
92
-			$this->error="Pgsql PHP functions are not available in this version of PHP";
93
-			dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP",LOG_ERR);
92
+			$this->error = "Pgsql PHP functions are not available in this version of PHP";
93
+			dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
94 94
 			return $this->ok;
95 95
 		}
96 96
 
97
-		if (! $host)
97
+		if (!$host)
98 98
 		{
99 99
 			$this->connected = false;
100 100
 			$this->ok = false;
101
-			$this->error=$langs->trans("ErrorWrongHostParameter");
102
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters",LOG_ERR);
101
+			$this->error = $langs->trans("ErrorWrongHostParameter");
102
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
103 103
 			return $this->ok;
104 104
 		}
105 105
 
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 			// host, login ou password incorrect
118 118
 			$this->connected = false;
119 119
 			$this->ok = false;
120
-			$this->error='Host, login or password incorrect';
121
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error,LOG_ERR);
120
+			$this->error = 'Host, login or password incorrect';
121
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error, LOG_ERR);
122 122
 		}
123 123
 
124 124
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -135,8 +135,8 @@  discard block
 block discarded – undo
135 135
 				$this->database_selected = false;
136 136
 				$this->database_name = '';
137 137
 				$this->ok = false;
138
-				$this->error=$this->error();
139
-				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
138
+				$this->error = $this->error();
139
+				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error, LOG_ERR);
140 140
 			}
141 141
 		}
142 142
 		else
@@ -157,14 +157,14 @@  discard block
 block discarded – undo
157 157
      *  @param	bool	$unescapeslashquot	Unescape slash quote with quote quote
158 158
      *  @return string   					SQL request line converted
159 159
      */
160
-	static function convertSQLFromMysql($line,$type='auto',$unescapeslashquot=false)
160
+	static function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
161 161
 	{
162 162
 		// Removed empty line if this is a comment line for SVN tagging
163
-		if (preg_match('/^--\s\$Id/i',$line)) {
163
+		if (preg_match('/^--\s\$Id/i', $line)) {
164 164
 			return '';
165 165
 		}
166 166
 		// Return line if this is a comment
167
-		if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
167
+		if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
168 168
 		{
169 169
 			return $line;
170 170
 		}
@@ -179,186 +179,186 @@  discard block
 block discarded – undo
179 179
 
180 180
 		    if ($type == 'auto')
181 181
 		    {
182
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
183
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
184
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
182
+              if (preg_match('/ALTER TABLE/i', $line)) $type = 'dml';
183
+              else if (preg_match('/CREATE TABLE/i', $line)) $type = 'dml';
184
+              else if (preg_match('/DROP TABLE/i', $line)) $type = 'dml';
185 185
 		    }
186 186
 
187
-    		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
187
+    		$line = preg_replace('/ as signed\)/i', ' as integer)', $line);
188 188
 
189 189
 		    if ($type == 'dml')
190 190
 		    {
191
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
191
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
192 192
 
193 193
 		        // we are inside create table statement so lets process datatypes
194
-    			if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
195
-    				$line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
196
-    				$line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
197
-    				$line=preg_replace('/,$/','',$line);
194
+    			if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
195
+    				$line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
196
+    				$line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
197
+    				$line = preg_replace('/,$/', '', $line);
198 198
     			}
199 199
 
200 200
     			// Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
201
-    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
202
-    				$newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
201
+    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
202
+    				$newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
203 203
                     //$line = "-- ".$line." replaced by --\n".$newline;
204
-                    $line=$newline;
204
+                    $line = $newline;
205 205
     			}
206 206
 
207 207
     			// tinyint type conversion
208
-    			$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
209
-    			$line=preg_replace('/tinyint/i','smallint',$line);
208
+    			$line = preg_replace('/tinyint\(?[0-9]*\)?/', 'smallint', $line);
209
+    			$line = preg_replace('/tinyint/i', 'smallint', $line);
210 210
 
211 211
     			// nuke unsigned
212
-    			$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
212
+    			$line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
213 213
 
214 214
     			// blob -> text
215
-    			$line=preg_replace('/\w*blob/i','text',$line);
215
+    			$line = preg_replace('/\w*blob/i', 'text', $line);
216 216
 
217 217
     			// tinytext/mediumtext -> text
218
-    			$line=preg_replace('/tinytext/i','text',$line);
219
-    			$line=preg_replace('/mediumtext/i','text',$line);
220
-    			$line=preg_replace('/longtext/i','text',$line);
218
+    			$line = preg_replace('/tinytext/i', 'text', $line);
219
+    			$line = preg_replace('/mediumtext/i', 'text', $line);
220
+    			$line = preg_replace('/longtext/i', 'text', $line);
221 221
 
222
-    			$line=preg_replace('/text\([0-9]+\)/i','text',$line);
222
+    			$line = preg_replace('/text\([0-9]+\)/i', 'text', $line);
223 223
 
224 224
     			// change not null datetime field to null valid ones
225 225
     			// (to support remapping of "zero time" to null
226
-    			$line=preg_replace('/datetime not null/i','datetime',$line);
227
-    			$line=preg_replace('/datetime/i','timestamp',$line);
226
+    			$line = preg_replace('/datetime not null/i', 'datetime', $line);
227
+    			$line = preg_replace('/datetime/i', 'timestamp', $line);
228 228
 
229 229
     			// double -> numeric
230
-    			$line=preg_replace('/^double/i','numeric',$line);
231
-    			$line=preg_replace('/(\s*)double/i','\\1numeric',$line);
230
+    			$line = preg_replace('/^double/i', 'numeric', $line);
231
+    			$line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
232 232
     			// float -> numeric
233
-    			$line=preg_replace('/^float/i','numeric',$line);
234
-    			$line=preg_replace('/(\s*)float/i','\\1numeric',$line);
233
+    			$line = preg_replace('/^float/i', 'numeric', $line);
234
+    			$line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
235 235
 
236 236
     			//Check tms timestamp field case (in Mysql this field is defautled to now and
237 237
     			// on update defaulted by now
238
-    			$line=preg_replace('/(\s*)tms(\s*)timestamp/i','\\1tms timestamp without time zone DEFAULT now() NOT NULL',$line);
238
+    			$line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
239 239
 
240 240
     			// nuke ON UPDATE CURRENT_TIMESTAMP
241
-    			$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
241
+    			$line = preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
242 242
 
243 243
     			// unique index(field1,field2)
244
-    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
244
+    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
245 245
     			{
246
-    				$line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
246
+    				$line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
247 247
     			}
248 248
 
249 249
     			// We remove end of requests "AFTER fieldxxx"
250
-    			$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
250
+    			$line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
251 251
 
252 252
     			// We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
253
-    			$line=preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i','DROP INDEX',$line);
253
+    			$line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
254 254
 
255 255
                 // Translate order to rename fields
256
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
256
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
257 257
                 {
258 258
                 	$line = "-- ".$line." replaced by --\n";
259
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
259
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
260 260
                 }
261 261
 
262 262
                 // Translate order to modify field format
263
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
263
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
264 264
                 {
265 265
                     $line = "-- ".$line." replaced by --\n";
266
-                    $newreg3=$reg[3];
267
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
268
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
269
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
270
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
271
-                    $newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
272
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
266
+                    $newreg3 = $reg[3];
267
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
268
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
269
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
270
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
271
+                    $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
272
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
273 273
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
274 274
                 }
275 275
 
276 276
                 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
277 277
     			// ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
278
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
278
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
279 279
     			{
280 280
     				$line = "-- ".$line." replaced by --\n";
281
-    				$line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
281
+    				$line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
282 282
     			}
283 283
 
284 284
                 // Translate order to drop primary keys
285 285
                 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
286
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg))
286
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg))
287 287
                 {
288 288
                     $line = "-- ".$line." replaced by --\n";
289
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
289
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
290 290
                 }
291 291
 
292 292
 		        // Translate order to drop foreign keys
293 293
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
294
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
294
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
295 295
                 {
296 296
                     $line = "-- ".$line." replaced by --\n";
297
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
297
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
298 298
                 }
299 299
 
300 300
                 // Translate order to add foreign keys
301 301
                 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
302
-                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
302
+                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
303 303
                 {
304
-                    $line=preg_replace('/;$/','',$line);
305
-                    $line.=" DEFERRABLE INITIALLY IMMEDIATE;";
304
+                    $line = preg_replace('/;$/', '', $line);
305
+                    $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
306 306
                 }
307 307
 
308 308
                 // alter table add [unique] [index] (field1, field2 ...)
309 309
     			// ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
310
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
310
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
311 311
     			{
312
-    				$fieldlist=$reg[4];
313
-    				$idxname=$reg[3];
314
-    				$tablename=$reg[1];
312
+    				$fieldlist = $reg[4];
313
+    				$idxname = $reg[3];
314
+    				$tablename = $reg[1];
315 315
     				$line = "-- ".$line." replaced by --\n";
316
-    				$line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
316
+    				$line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
317 317
     			}
318 318
             }
319 319
 
320 320
             // To have postgresql case sensitive
321
-            $line=str_replace(' LIKE \'',' ILIKE \'',$line);
322
-            $line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
321
+            $line = str_replace(' LIKE \'', ' ILIKE \'', $line);
322
+            $line = str_replace(' LIKE BINARY \'', ' LIKE \'', $line);
323 323
 
324 324
             // Replace INSERT IGNORE into INSERT
325
-            $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
325
+            $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
326 326
 
327 327
 			// Delete using criteria on other table must not declare twice the deleted table
328 328
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
329
-			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
329
+			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
330 330
 			{
331 331
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
332 332
 				{
333
-					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
333
+					$line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
334 334
 				}
335 335
 			}
336 336
 
337 337
 			// Remove () in the tables in FROM if 1 table
338
-			$line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
338
+			$line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
339 339
 			//print $line."\n";
340 340
 
341 341
 			// Remove () in the tables in FROM if 2 table
342
-			$line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2',$line);
342
+			$line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2', $line);
343 343
 			//print $line."\n";
344 344
 
345 345
 			// Remove () in the tables in FROM if 3 table
346
-			$line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2, \\3',$line);
346
+			$line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2, \\3', $line);
347 347
 			//print $line."\n";
348 348
 
349 349
 			// Remove () in the tables in FROM if 4 table
350
-			$line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2, \\3, \\4',$line);
350
+			$line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2, \\3, \\4', $line);
351 351
 			//print $line."\n";
352 352
 
353 353
 			// Remove () in the tables in FROM if 5 table
354
-			$line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2, \\3, \\4, \\5',$line);
354
+			$line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2, \\3, \\4, \\5', $line);
355 355
 			//print $line."\n";
356 356
 
357 357
 			// Replace espacing \' by ''.
358 358
 			// By default we do not (should be already done by db->escape function if required
359 359
 			// except for sql insert in data file that are mysql escaped so we removed them to
360 360
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
361
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
361
+			if ($unescapeslashquot) $line = preg_replace("/\\\'/", "''", $line);
362 362
 
363 363
 			//print "type=".$type." newline=".$line."<br>\n";
364 364
 		}
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 	 *	@return		false|resource			Database access handler
397 397
 	 *	@see		close
398 398
 	 */
399
-	function connect($host, $login, $passwd, $name, $port=0)
399
+	function connect($host, $login, $passwd, $name, $port = 0)
400 400
 	{
401 401
 		// use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
402 402
 
@@ -409,20 +409,20 @@  discard block
 block discarded – undo
409 409
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
410 410
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
411 411
 
412
-		if (! $name) $name="postgres";    // When try to connect using admin user
412
+		if (!$name) $name = "postgres"; // When try to connect using admin user
413 413
 
414 414
 		// try first Unix domain socket (local)
415
-		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
415
+		if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT'))
416 416
 		{
417
-			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'";    // $name may be empty
417
+			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
418 418
 			$this->db = @pg_connect($con_string);
419 419
 		}
420 420
 
421 421
 		// if local connection failed or not requested, use TCP/IP
422
-		if (! $this->db)
422
+		if (!$this->db)
423 423
 		{
424
-		    if (! $host) $host = "localhost";
425
-			if (! $port) $port = 5432;
424
+		    if (!$host) $host = "localhost";
425
+			if (!$port) $port = 5432;
426 426
 
427 427
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
428 428
 			$this->db = @pg_connect($con_string);
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 		if ($this->db)
433 433
 		{
434 434
 			$this->database_name = $name;
435
-			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);	// Set verbosity to max
435
+			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
436 436
 			pg_query($this->db, "set datestyle = 'ISO, YMD';");
437 437
 		}
438 438
 
@@ -446,10 +446,10 @@  discard block
 block discarded – undo
446 446
 	 */
447 447
 	function getVersion()
448 448
 	{
449
-		$resql=$this->query('SHOW server_version');
449
+		$resql = $this->query('SHOW server_version');
450 450
 		if ($resql)
451 451
 		{
452
-		  $liste=$this->fetch_array($resql);
452
+		  $liste = $this->fetch_array($resql);
453 453
 		  return $liste['server_version'];
454 454
 		}
455 455
 		return '';
@@ -475,8 +475,8 @@  discard block
 block discarded – undo
475 475
     {
476 476
         if ($this->db)
477 477
         {
478
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
479
-          $this->connected=false;
478
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
479
+          $this->connected = false;
480 480
           return pg_close($this->db);
481 481
         }
482 482
         return false;
@@ -490,30 +490,30 @@  discard block
 block discarded – undo
490 490
      * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
491 491
 	 * @return	false|resource			Resultset of answer
492 492
 	 */
493
-	function query($query,$usesavepoint=0,$type='auto')
493
+	function query($query, $usesavepoint = 0, $type = 'auto')
494 494
 	{
495 495
 		global $conf;
496 496
 
497 497
 		$query = trim($query);
498 498
 
499
-        Debug::addMessage('SQL', 'PgSQL: ' . $query);
499
+        Debug::addMessage('SQL', 'PgSQL: '.$query);
500 500
 
501 501
         // Convert MySQL syntax to PostgresSQL syntax
502
-        $query=$this->convertSQLFromMysql($query,$type,($this->unescapeslashquot && $this->standard_conforming_strings));
502
+        $query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
503 503
 		//print "After convertSQLFromMysql:\n".$query."<br>\n";
504 504
 
505
-		if (! empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
505
+		if (!empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
506 506
 		{
507 507
 			// Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
508
-			$loop=true;
508
+			$loop = true;
509 509
 			while ($loop)
510 510
 			{
511
-				if (preg_match('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/',$query))
511
+				if (preg_match('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/', $query))
512 512
 				{
513
-					$query=preg_replace('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/','\\1\'\\2\'',$query);
514
-					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
513
+					$query = preg_replace('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/', '\\1\'\\2\'', $query);
514
+					dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
515 515
 				}
516
-				else $loop=false;
516
+				else $loop = false;
517 517
 			}
518 518
 		}
519 519
 
@@ -522,14 +522,14 @@  discard block
 block discarded – undo
522 522
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
523 523
 		}
524 524
 
525
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
525
+		if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
526 526
 
527 527
 		$ret = @pg_query($this->db, $query);
528 528
 
529 529
 		//print $query;
530
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
530
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
531 531
 		{
532
-			if (! $ret)
532
+			if (!$ret)
533 533
 			{
534 534
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
535 535
 			    {
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
     				$this->lasterror = $this->error();
538 538
     				$this->lasterrno = $this->errno();
539 539
 
540
-    				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);	// Log of request was not yet done previously
540
+    				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
541 541
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
542 542
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
543 543
 			    }
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
548 548
 				}
549 549
 			}
550
-			$this->lastquery=$query;
550
+			$this->lastquery = $query;
551 551
 			$this->_results = $ret;
552 552
 		}
553 553
 
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 	{
566 566
         // phpcs:enable
567 567
         // If resultset not provided, we take the last used by connexion
568
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
568
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
569 569
 		return pg_fetch_object($resultset);
570 570
 	}
571 571
 
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
 	{
581 581
         // phpcs:enable
582 582
         // If resultset not provided, we take the last used by connexion
583
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
583
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
584 584
 		return pg_fetch_array($resultset);
585 585
 	}
586 586
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 	{
596 596
         // phpcs:enable
597 597
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
598
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
598
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
599 599
 		return pg_fetch_row($resultset);
600 600
 	}
601 601
 
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 	{
612 612
         // phpcs:enable
613 613
         // If resultset not provided, we take the last used by connexion
614
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
614
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
615 615
 		return pg_num_rows($resultset);
616 616
 	}
617 617
 
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
 	{
628 628
         // phpcs:enable
629 629
         // If resultset not provided, we take the last used by connexion
630
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
630
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
631 631
 		// pgsql necessite un resultset pour cette fonction contrairement
632 632
 		// a mysql qui prend un link de base
633 633
 		return pg_affected_rows($resultset);
@@ -640,10 +640,10 @@  discard block
 block discarded – undo
640 640
 	 * @param	resource	$resultset  Result set of request
641 641
 	 * @return	void
642 642
 	 */
643
-	function free($resultset=null)
643
+	function free($resultset = null)
644 644
 	{
645 645
         // If resultset not provided, we take the last used by connexion
646
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
646
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
647 647
 		// Si resultset en est un, on libere la memoire
648 648
 		if (is_resource($resultset)) pg_free_result($resultset);
649 649
 	}
@@ -656,11 +656,11 @@  discard block
 block discarded – undo
656 656
      *	@param	int		$offset     Numero of line from where starting fetch
657 657
      *	@return	string      		String with SQL syntax to add a limit and offset
658 658
 	 */
659
-	function plimit($limit=0,$offset=0)
659
+	function plimit($limit = 0, $offset = 0)
660 660
 	{
661 661
 		global $conf;
662 662
         if (empty($limit)) return "";
663
-		if ($limit < 0) $limit=$conf->liste_limit;
663
+		if ($limit < 0) $limit = $conf->liste_limit;
664 664
 		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
665 665
 		else return " LIMIT $limit ";
666 666
 	}
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 	 */
687 687
 	function idate($param)
688 688
 	{
689
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
689
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
690 690
 	}
691 691
 
692 692
 	/**
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 	 *  @param	string	$resko          resultat si test non egal
698 698
 	 *  @return	string          		chaine formate SQL
699 699
 	 */
700
-	function ifsql($test,$resok,$resko)
700
+	function ifsql($test, $resok, $resko)
701 701
 	{
702 702
 		return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
703 703
 	}
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
 	 */
710 710
 	function errno()
711 711
 	{
712
-		if (! $this->connected) {
712
+		if (!$this->connected) {
713 713
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
714 714
 			return 'DB_ERROR_FAILED_TO_CONNECT';
715 715
 		}
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
 			42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
732 732
 			'42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
733 733
 			'23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
734
-			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP',		// May also be Type xxx does not exists
734
+			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
735 735
 			'42601' => 'DB_ERROR_SYNTAX',
736 736
 			'42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
737 737
 			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
@@ -745,18 +745,18 @@  discard block
 block discarded – undo
745 745
 			'42P04' => 'DB_DATABASE_ALREADY_EXISTS'
746 746
 			);
747 747
 
748
-			$errorlabel=pg_last_error($this->db);
749
-			$errorcode='';
750
-			if (preg_match('/: *([0-9P]+):/',$errorlabel,$reg))
748
+			$errorlabel = pg_last_error($this->db);
749
+			$errorcode = '';
750
+			if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg))
751 751
 			{
752
-				$errorcode=$reg[1];
752
+				$errorcode = $reg[1];
753 753
 				if (isset($errorcode_map[$errorcode]))
754 754
 				{
755 755
 					return $errorcode_map[$errorcode];
756 756
 				}
757 757
 			}
758
-			$errno=$errorcode?$errorcode:$errorlabel;
759
-			return ($errno?'DB_ERROR_'.$errno:'0');
758
+			$errno = $errorcode ? $errorcode : $errorlabel;
759
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
760 760
 		}
761 761
 		//                '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
762 762
 		//                '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
@@ -786,18 +786,18 @@  discard block
 block discarded – undo
786 786
 	 * @param	string	$fieldid	Field name
787 787
 	 * @return  string     			Id of row
788 788
 	 */
789
-	function last_insert_id($tab,$fieldid='rowid')
789
+	function last_insert_id($tab, $fieldid = 'rowid')
790 790
 	{
791 791
         // phpcs:enable
792 792
 		//$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
793
-		$result = pg_query($this->db,"SELECT currval('".$tab."_".$fieldid."_seq')");
794
-		if (! $result)
793
+		$result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
794
+		if (!$result)
795 795
 		{
796 796
 			print pg_last_error($this->db);
797 797
 			exit;
798 798
 		}
799 799
 		//$nbre = pg_num_rows($result);
800
-		$row = pg_fetch_result($result,0,0);
800
+		$row = pg_fetch_result($result, 0, 0);
801 801
 		return $row;
802 802
 	}
803 803
 
@@ -809,18 +809,18 @@  discard block
 block discarded – undo
809 809
      *  @param	int		$withQuotes     Return string with quotes
810 810
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
811 811
 	 */
812
-	function encrypt($fieldorvalue, $withQuotes=0)
812
+	function encrypt($fieldorvalue, $withQuotes = 0)
813 813
 	{
814 814
 		global $conf;
815 815
 
816 816
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
817
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
817
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
818 818
 
819 819
 		//Encryption key
820
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
820
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
821 821
 
822 822
 		$return = $fieldorvalue;
823
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
823
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
824 824
 	}
825 825
 
826 826
 
@@ -835,10 +835,10 @@  discard block
 block discarded – undo
835 835
 		global $conf;
836 836
 
837 837
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
838
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
838
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
839 839
 
840 840
 		//Encryption key
841
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
841
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
842 842
 
843 843
 		$return = $value;
844 844
 		return $return;
@@ -871,18 +871,18 @@  discard block
 block discarded – undo
871 871
 	 * 	@param	string	$owner			Username of database owner
872 872
 	 * 	@return	false|resource				resource defined if OK, null if KO
873 873
 	 */
874
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
874
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
875 875
 	{
876 876
         // phpcs:enable
877
-	    if (empty($charset))   $charset=$this->forcecharset;
878
-		if (empty($collation)) $collation=$this->forcecollate;
877
+	    if (empty($charset))   $charset = $this->forcecharset;
878
+		if (empty($collation)) $collation = $this->forcecollate;
879 879
 
880 880
 		// Test charset match LC_TYPE (pgsql error otherwise)
881 881
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
882 882
 
883
-		$sql='CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
884
-		dol_syslog($sql,LOG_DEBUG);
885
-		$ret=$this->query($sql);
883
+		$sql = 'CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
884
+		dol_syslog($sql, LOG_DEBUG);
885
+		$ret = $this->query($sql);
886 886
 		return $ret;
887 887
 	}
888 888
 
@@ -894,17 +894,17 @@  discard block
 block discarded – undo
894 894
 	 *  @param	string		$table		Name of table filter ('xxx%')
895 895
 	 *  @return	array					List of tables in an array
896 896
 	 */
897
-	function DDLListTables($database, $table='')
897
+	function DDLListTables($database, $table = '')
898 898
     {
899 899
         // phpcs:enable
900
-		$listtables=array();
900
+		$listtables = array();
901 901
 
902 902
 		$like = '';
903 903
 		if ($table) $like = " AND table_name LIKE '".$table."'";
904 904
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
905 905
         if ($result)
906 906
         {
907
-    		while($row = $this->fetch_row($result))
907
+    		while ($row = $this->fetch_row($result))
908 908
     		{
909 909
     			$listtables[] = $row[0];
910 910
     		}
@@ -923,29 +923,29 @@  discard block
 block discarded – undo
923 923
 	function DDLInfoTable($table)
924 924
 	{
925 925
         // phpcs:enable
926
-		$infotables=array();
927
-
928
-		$sql="SELECT ";
929
-		$sql.="	infcol.column_name as \"Column\",";
930
-		$sql.="	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
931
-		$sql.="		ELSE infcol.udt_name";
932
-		$sql.="	END as \"Type\",";
933
-		$sql.="	infcol.collation_name as \"Collation\",";
934
-		$sql.="	infcol.is_nullable as \"Null\",";
935
-		$sql.="	'' as \"Key\",";
936
-		$sql.="	infcol.column_default as \"Default\",";
937
-		$sql.="	'' as \"Extra\",";
938
-		$sql.="	'' as \"Privileges\"";
939
-		$sql.="	FROM information_schema.columns infcol";
940
-		$sql.="	WHERE table_schema='public' ";
941
-		$sql.="	AND table_name='".$table."'";
942
-		$sql.="	ORDER BY ordinal_position;";
943
-
944
-		dol_syslog($sql,LOG_DEBUG);
926
+		$infotables = array();
927
+
928
+		$sql = "SELECT ";
929
+		$sql .= "	infcol.column_name as \"Column\",";
930
+		$sql .= "	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
931
+		$sql .= "		ELSE infcol.udt_name";
932
+		$sql .= "	END as \"Type\",";
933
+		$sql .= "	infcol.collation_name as \"Collation\",";
934
+		$sql .= "	infcol.is_nullable as \"Null\",";
935
+		$sql .= "	'' as \"Key\",";
936
+		$sql .= "	infcol.column_default as \"Default\",";
937
+		$sql .= "	'' as \"Extra\",";
938
+		$sql .= "	'' as \"Privileges\"";
939
+		$sql .= "	FROM information_schema.columns infcol";
940
+		$sql .= "	WHERE table_schema='public' ";
941
+		$sql .= "	AND table_name='".$table."'";
942
+		$sql .= "	ORDER BY ordinal_position;";
943
+
944
+		dol_syslog($sql, LOG_DEBUG);
945 945
 		$result = $this->query($sql);
946 946
 		if ($result)
947 947
 		{
948
-    		 while($row = $this->fetch_row($result))
948
+    		 while ($row = $this->fetch_row($result))
949 949
     		 {
950 950
     			$infotables[] = $row;
951 951
     		 }
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
968 968
 	 *	@return	    int						<0 if KO, >=0 if OK
969 969
 	 */
970
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
970
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
971 971
 	{
972 972
         // phpcs:enable
973 973
 		// FIXME: $fulltext_keys parameter is unused
@@ -975,61 +975,61 @@  discard block
 block discarded – undo
975 975
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
976 976
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
977 977
 		$sql = "create table ".$table."(";
978
-		$i=0;
979
-		foreach($fields as $field_name => $field_desc)
978
+		$i = 0;
979
+		foreach ($fields as $field_name => $field_desc)
980 980
 		{
981 981
 			$sqlfields[$i] = $field_name." ";
982 982
 			$sqlfields[$i]  .= $field_desc['type'];
983
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
983
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
984 984
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
985
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
985
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
986 986
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
987
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
987
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
988 988
 			{
989
-				if(preg_match("/null/i",$field_desc['default']))
989
+				if (preg_match("/null/i", $field_desc['default']))
990 990
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
991 991
 				else
992 992
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
993 993
 			}
994
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
994
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
995 995
 			$sqlfields[$i]  .= " ".$field_desc['null'];
996 996
 
997
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
997
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
998 998
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
999 999
 			$i++;
1000 1000
 		}
1001
-		if($primary_key != "")
1001
+		if ($primary_key != "")
1002 1002
 		$pk = "primary key(".$primary_key.")";
1003 1003
 
1004
-		if(is_array($unique_keys))
1004
+		if (is_array($unique_keys))
1005 1005
 		{
1006 1006
 			$i = 0;
1007
-			foreach($unique_keys as $key => $value)
1007
+			foreach ($unique_keys as $key => $value)
1008 1008
 			{
1009 1009
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
1010 1010
 				$i++;
1011 1011
 			}
1012 1012
 		}
1013
-		if(is_array($keys))
1013
+		if (is_array($keys))
1014 1014
 		{
1015 1015
 			$i = 0;
1016
-			foreach($keys as $key => $value)
1016
+			foreach ($keys as $key => $value)
1017 1017
 			{
1018 1018
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
1019 1019
 				$i++;
1020 1020
 			}
1021 1021
 		}
1022
-		$sql .= implode(',',$sqlfields);
1023
-		if($primary_key != "")
1022
+		$sql .= implode(',', $sqlfields);
1023
+		if ($primary_key != "")
1024 1024
 		$sql .= ",".$pk;
1025
-		if(is_array($unique_keys))
1026
-		$sql .= ",".implode(',',$sqluq);
1027
-		if(is_array($keys))
1028
-		$sql .= ",".implode(',',$sqlk);
1029
-		$sql .=") type=".$type;
1030
-
1031
-		dol_syslog($sql,LOG_DEBUG);
1032
-		if(! $this->query($sql))
1025
+		if (is_array($unique_keys))
1026
+		$sql .= ",".implode(',', $sqluq);
1027
+		if (is_array($keys))
1028
+		$sql .= ",".implode(',', $sqlk);
1029
+		$sql .= ") type=".$type;
1030
+
1031
+		dol_syslog($sql, LOG_DEBUG);
1032
+		if (!$this->query($sql))
1033 1033
 		return -1;
1034 1034
 		else
1035 1035
 		return 1;
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
         // phpcs:enable
1048 1048
 		$sql = "DROP TABLE ".$table;
1049 1049
 
1050
-		if (! $this->query($sql))
1050
+		if (!$this->query($sql))
1051 1051
 			return -1;
1052 1052
 		else
1053 1053
 			return 1;
@@ -1063,15 +1063,15 @@  discard block
 block discarded – undo
1063 1063
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1064 1064
 	 *	@return	int									<0 if KO, >=0 if OK
1065 1065
 	 */
1066
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1066
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1067 1067
 	{
1068 1068
         // phpcs:enable
1069 1069
 		// Note: using ' on user does not works with pgsql
1070 1070
 		$sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1071 1071
 
1072
-		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1073
-		$resql=$this->query($sql);
1074
-		if (! $resql)
1072
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1073
+		$resql = $this->query($sql);
1074
+		if (!$resql)
1075 1075
 		{
1076 1076
 			return -1;
1077 1077
 		}
@@ -1087,14 +1087,14 @@  discard block
 block discarded – undo
1087 1087
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1088 1088
 	 *	@return	false|resource		Resultset x (x->attname)
1089 1089
 	 */
1090
-	function DDLDescTable($table,$field="")
1090
+	function DDLDescTable($table, $field = "")
1091 1091
 	{
1092 1092
         // phpcs:enable
1093
-		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1094
-		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1095
-		if ($field) $sql.= " AND attname = '".$field."'";
1093
+		$sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1094
+		$sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1095
+		if ($field) $sql .= " AND attname = '".$field."'";
1096 1096
 
1097
-		dol_syslog($sql,LOG_DEBUG);
1097
+		dol_syslog($sql, LOG_DEBUG);
1098 1098
 		$this->_results = $this->query($sql);
1099 1099
 		return $this->_results;
1100 1100
 	}
@@ -1109,32 +1109,32 @@  discard block
 block discarded – undo
1109 1109
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1110 1110
 	 *	@return	int							<0 if KO, >0 if OK
1111 1111
 	 */
1112
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
1112
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1113 1113
 	{
1114 1114
         // phpcs:enable
1115 1115
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1116 1116
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1117
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1117
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1118 1118
 		$sql .= $field_desc['type'];
1119
-		if (preg_match("/^[^\s]/i",$field_desc['value']))
1120
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1119
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
1120
+		    if (!in_array($field_desc['type'], array('int', 'date', 'datetime')))
1121 1121
 		    {
1122
-		        $sql.= "(".$field_desc['value'].")";
1122
+		        $sql .= "(".$field_desc['value'].")";
1123 1123
 		    }
1124
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1124
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1125 1125
             $sql .= " ".$field_desc['attribute'];
1126
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1126
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
1127 1127
             $sql .= " ".$field_desc['null'];
1128
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1129
-            if (preg_match("/null/i",$field_desc['default']))
1128
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
1129
+            if (preg_match("/null/i", $field_desc['default']))
1130 1130
                 $sql .= " default ".$field_desc['default'];
1131 1131
 		    else
1132 1132
                 $sql .= " default '".$field_desc['default']."'";
1133
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1133
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
1134 1134
             $sql .= " ".$field_desc['extra'];
1135 1135
 		$sql .= " ".$field_position;
1136 1136
 
1137
-		dol_syslog($sql,LOG_DEBUG);
1137
+		dol_syslog($sql, LOG_DEBUG);
1138 1138
 		if (!$this->query($sql))
1139 1139
             return -1;
1140 1140
 		return 1;
@@ -1149,13 +1149,13 @@  discard block
 block discarded – undo
1149 1149
 	 *	@param	string	$field_desc 		Array with description of field format
1150 1150
 	 *	@return	int							<0 if KO, >0 if OK
1151 1151
 	 */
1152
-	function DDLUpdateField($table,$field_name,$field_desc)
1152
+	function DDLUpdateField($table, $field_name, $field_desc)
1153 1153
 	{
1154 1154
         // phpcs:enable
1155 1155
 		$sql = "ALTER TABLE ".$table;
1156 1156
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1157 1157
 		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1158
-			$sql.="(".$field_desc['value'].")";
1158
+			$sql .= "(".$field_desc['value'].")";
1159 1159
 		}
1160 1160
 
1161 1161
 		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
@@ -1163,24 +1163,24 @@  discard block
 block discarded – undo
1163 1163
         	// We will try to change format of column to NOT NULL. To be sure the ALTER works, we try to update fields that are NULL
1164 1164
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1165 1165
         	{
1166
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1166
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1167 1167
         		$this->query($sqlbis);
1168 1168
         	}
1169 1169
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1170 1170
         	{
1171
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1171
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1172 1172
         		$this->query($sqlbis);
1173 1173
         	}
1174 1174
 		}
1175 1175
 
1176 1176
 		if ($field_desc['default'] != '')
1177 1177
 		{
1178
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1179
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1178
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
1179
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
1180 1180
 		}
1181 1181
 
1182
-		dol_syslog($sql,LOG_DEBUG);
1183
-		if (! $this->query($sql))
1182
+		dol_syslog($sql, LOG_DEBUG);
1183
+		if (!$this->query($sql))
1184 1184
 			return -1;
1185 1185
 		return 1;
1186 1186
 	}
@@ -1193,14 +1193,14 @@  discard block
 block discarded – undo
1193 1193
 	 *	@param	string	$field_name 	Name of field to drop
1194 1194
 	 *	@return	int						<0 if KO, >0 if OK
1195 1195
 	 */
1196
-	function DDLDropField($table,$field_name)
1196
+	function DDLDropField($table, $field_name)
1197 1197
 	{
1198 1198
         // phpcs:enable
1199
-		$sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1200
-		dol_syslog($sql,LOG_DEBUG);
1201
-		if (! $this->query($sql))
1199
+		$sql = "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1200
+		dol_syslog($sql, LOG_DEBUG);
1201
+		if (!$this->query($sql))
1202 1202
 		{
1203
-			$this->error=$this->lasterror();
1203
+			$this->error = $this->lasterror();
1204 1204
 			return -1;
1205 1205
 		}
1206 1206
 		return 1;
@@ -1213,10 +1213,10 @@  discard block
 block discarded – undo
1213 1213
 	 */
1214 1214
 	function getDefaultCharacterSetDatabase()
1215 1215
 	{
1216
-		$resql=$this->query('SHOW SERVER_ENCODING');
1216
+		$resql = $this->query('SHOW SERVER_ENCODING');
1217 1217
 		if ($resql)
1218 1218
 		{
1219
-            $liste=$this->fetch_array($resql);
1219
+            $liste = $this->fetch_array($resql);
1220 1220
 		    return $liste['server_encoding'];
1221 1221
 		}
1222 1222
 		else return '';
@@ -1229,7 +1229,7 @@  discard block
 block discarded – undo
1229 1229
 	 */
1230 1230
 	function getListOfCharacterSet()
1231 1231
 	{
1232
-		$resql=$this->query('SHOW SERVER_ENCODING');
1232
+		$resql = $this->query('SHOW SERVER_ENCODING');
1233 1233
 		$liste = array();
1234 1234
 		if ($resql)
1235 1235
 		{
@@ -1254,10 +1254,10 @@  discard block
 block discarded – undo
1254 1254
 	 */
1255 1255
 	function getDefaultCollationDatabase()
1256 1256
 	{
1257
-		$resql=$this->query('SHOW LC_COLLATE');
1257
+		$resql = $this->query('SHOW LC_COLLATE');
1258 1258
 		if ($resql)
1259 1259
 		{
1260
-		    $liste=$this->fetch_array($resql);
1260
+		    $liste = $this->fetch_array($resql);
1261 1261
 			return $liste['lc_collate'];
1262 1262
 		}
1263 1263
 		else return '';
@@ -1270,12 +1270,12 @@  discard block
 block discarded – undo
1270 1270
 	 */
1271 1271
 	function getListOfCollation()
1272 1272
 	{
1273
-		$resql=$this->query('SHOW LC_COLLATE');
1273
+		$resql = $this->query('SHOW LC_COLLATE');
1274 1274
 		$liste = array();
1275 1275
 		if ($resql)
1276 1276
 		{
1277 1277
 			$i = 0;
1278
-			while ($obj = $this->fetch_object($resql) )
1278
+			while ($obj = $this->fetch_object($resql))
1279 1279
 			{
1280 1280
 				$liste[$i]['collation'] = $obj->lc_collate;
1281 1281
 				$i++;
@@ -1294,21 +1294,21 @@  discard block
 block discarded – undo
1294 1294
 	 */
1295 1295
 	function getPathOfDump()
1296 1296
 	{
1297
-		$fullpathofdump='/pathtopgdump/pg_dump';
1297
+		$fullpathofdump = '/pathtopgdump/pg_dump';
1298 1298
 
1299 1299
 		if (file_exists('/usr/bin/pg_dump'))
1300 1300
 		{
1301
-		    $fullpathofdump='/usr/bin/pg_dump';
1301
+		    $fullpathofdump = '/usr/bin/pg_dump';
1302 1302
 		}
1303 1303
 		else
1304 1304
 		{
1305 1305
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1306
-		    $resql=$this->query('SHOW data_directory');
1306
+		    $resql = $this->query('SHOW data_directory');
1307 1307
     		if ($resql)
1308 1308
     		{
1309
-    			$liste=$this->fetch_array($resql);
1310
-    			$basedir=$liste['data_directory'];
1311
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1309
+    			$liste = $this->fetch_array($resql);
1310
+    			$basedir = $liste['data_directory'];
1311
+    			$fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1312 1312
     		}
1313 1313
 		}
1314 1314
 
@@ -1323,23 +1323,23 @@  discard block
 block discarded – undo
1323 1323
 	function getPathOfRestore()
1324 1324
 	{
1325 1325
 		//$tool='pg_restore';
1326
-		$tool='psql';
1326
+		$tool = 'psql';
1327 1327
 
1328
-		$fullpathofdump='/pathtopgrestore/'.$tool;
1328
+		$fullpathofdump = '/pathtopgrestore/'.$tool;
1329 1329
 
1330 1330
         if (file_exists('/usr/bin/'.$tool))
1331 1331
         {
1332
-            $fullpathofdump='/usr/bin/'.$tool;
1332
+            $fullpathofdump = '/usr/bin/'.$tool;
1333 1333
         }
1334 1334
         else
1335 1335
         {
1336 1336
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1337
-            $resql=$this->query('SHOW data_directory');
1337
+            $resql = $this->query('SHOW data_directory');
1338 1338
             if ($resql)
1339 1339
             {
1340
-                $liste=$this->fetch_array($resql);
1341
-                $basedir=$liste['data_directory'];
1342
-                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1340
+                $liste = $this->fetch_array($resql);
1341
+                $basedir = $liste['data_directory'];
1342
+                $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1343 1343
             }
1344 1344
         }
1345 1345
 
@@ -1352,16 +1352,16 @@  discard block
 block discarded – undo
1352 1352
 	 * @param	string	$filter		Filter list on a particular value
1353 1353
 	 * @return	array				Array of key-values (key=>value)
1354 1354
 	 */
1355
-	function getServerParametersValues($filter='')
1355
+	function getServerParametersValues($filter = '')
1356 1356
 	{
1357
-		$result=array();
1357
+		$result = array();
1358 1358
 
1359
-		$resql='select name,setting from pg_settings';
1360
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1361
-		$resql=$this->query($resql);
1359
+		$resql = 'select name,setting from pg_settings';
1360
+		if ($filter) $resql .= " WHERE name = '".$this->escape($filter)."'";
1361
+		$resql = $this->query($resql);
1362 1362
 		if ($resql)
1363 1363
 		{
1364
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1364
+			while ($obj = $this->fetch_object($resql)) $result[$obj->name] = $obj->setting;
1365 1365
 		}
1366 1366
 
1367 1367
 		return $result;
@@ -1373,7 +1373,7 @@  discard block
 block discarded – undo
1373 1373
 	 * @param	string	$filter		Filter list on a particular value
1374 1374
 	 * @return  array				Array of key-values (key=>value)
1375 1375
 	 */
1376
-	function getServerStatusValues($filter='')
1376
+	function getServerStatusValues($filter = '')
1377 1377
 	{
1378 1378
 		/* This is to return current running requests.
1379 1379
 		$sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
Please login to merge, or discard this patch.