Passed
Push — master ( db7d4f...be8d41 )
by Alxarafe
21:50
created
htdocs/core/triggers/interface_50_modBlockedlog_ActionsBlockedLog.class.php 3 patches
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -30,121 +30,121 @@
 block discarded – undo
30 30
  */
31 31
 class InterfaceActionsBlockedLog extends DolibarrTriggers
32 32
 {
33
-	public $family = 'system';
34
-	public $description = "Triggers of this module add action for BlockedLog module.";
35
-
36
-	/**
37
-	 * Version of the trigger
38
-	 * @var string
39
-	 */
40
-	public $version = self::VERSION_DOLIBARR;
41
-
42
-	/**
43
-	 * @var string Image of the trigger
44
-	 */
45
-	public $picto = 'technic';
46
-
47
-	/**
48
-	 * Function called on Dolibarrr payment or invoice event.
49
-	 *
50
-	 * @param string		$action		Event action code
51
-	 * @param Object		$object     Object
52
-	 * @param User		    $user       Object user
53
-	 * @param Translate 	$langs      Object langs
54
-	 * @param conf		    $conf       Object conf
55
-	 * @return int         				<0 if KO, 0 if no triggered ran, >0 if OK
56
-	 */
57
-	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
58
-	{
59
-		if (empty($conf->blockedlog->enabled)) return 0;     // Module not active, we do nothing
60
-
61
-		// Test if event/record is qualified
62
-		$listofqualifiedelement = array('facture', 'don', 'payment', 'payment_donation', 'subscription', 'payment_various', 'cashcontrol');
63
-		if (! in_array($object->element, $listofqualifiedelement)) return 1;
64
-
65
-		dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
66
-
67
-		require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
68
-		$b=new BlockedLog($this->db);
69
-
70
-		// Tracked events
71
-		if (! in_array($action, array_keys($b->trackedevents)))
72
-		{
73
-			return 0;
74
-		}
75
-
76
-		// Event/record is qualified
77
-		$qualified = 0;
78
-		$amounts = 0;
79
-		if ($action==='BILL_VALIDATE' || $action==='BILL_DELETE' || $action === 'BILL_SENTBYMAIL'
80
-			|| $action==='BILL_SUPPLIER_VALIDATE' || $action==='BILL_SUPPLIER_DELETE' || $action === 'BILL_SUPPLIER_SENTBYMAIL'
81
-			|| $action==='MEMBER_SUBSCRIPTION_CREATE' || $action==='MEMBER_SUBSCRIPTION_MODIFY' || $action==='MEMBER_SUBSCRIPTION_DELETE'
82
-			|| $action==='DON_VALIDATE' || $action==='DON_MODIFY' || $action==='DON_DELETE'
83
-			|| $action==='CASHCONTROL_VALIDATE'
84
-			|| (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_DOWNLOAD') || (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_PREVIEW')
85
-		)
86
-		{
87
-			$qualified++;
88
-
89
-			if (in_array($action, array(
90
-				'MEMBER_SUBSCRIPTION_CREATE','MEMBER_SUBSCRIPTION_MODIFY','MEMBER_SUBSCRIPTION_DELETE',
91
-				'DON_VALIDATE','DON_MODIFY','DON_DELETE'))) $amounts = (double) $object->amount;
92
-			elseif ($action == 'CASHCONTROL_VALIDATE')
93
-			{
94
-				$amounts = (double) $object->cash + (double) $object->cheque + (double) $object->card;
95
-			}
96
-			else $amounts = (double) $object->total_ttc;
97
-		}
98
-		/*if ($action === 'BILL_PAYED' || $action==='BILL_UNPAYED'
33
+    public $family = 'system';
34
+    public $description = "Triggers of this module add action for BlockedLog module.";
35
+
36
+    /**
37
+     * Version of the trigger
38
+     * @var string
39
+     */
40
+    public $version = self::VERSION_DOLIBARR;
41
+
42
+    /**
43
+     * @var string Image of the trigger
44
+     */
45
+    public $picto = 'technic';
46
+
47
+    /**
48
+     * Function called on Dolibarrr payment or invoice event.
49
+     *
50
+     * @param string		$action		Event action code
51
+     * @param Object		$object     Object
52
+     * @param User		    $user       Object user
53
+     * @param Translate 	$langs      Object langs
54
+     * @param conf		    $conf       Object conf
55
+     * @return int         				<0 if KO, 0 if no triggered ran, >0 if OK
56
+     */
57
+    public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
58
+    {
59
+        if (empty($conf->blockedlog->enabled)) return 0;     // Module not active, we do nothing
60
+
61
+        // Test if event/record is qualified
62
+        $listofqualifiedelement = array('facture', 'don', 'payment', 'payment_donation', 'subscription', 'payment_various', 'cashcontrol');
63
+        if (! in_array($object->element, $listofqualifiedelement)) return 1;
64
+
65
+        dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
66
+
67
+        require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
68
+        $b=new BlockedLog($this->db);
69
+
70
+        // Tracked events
71
+        if (! in_array($action, array_keys($b->trackedevents)))
72
+        {
73
+            return 0;
74
+        }
75
+
76
+        // Event/record is qualified
77
+        $qualified = 0;
78
+        $amounts = 0;
79
+        if ($action==='BILL_VALIDATE' || $action==='BILL_DELETE' || $action === 'BILL_SENTBYMAIL'
80
+            || $action==='BILL_SUPPLIER_VALIDATE' || $action==='BILL_SUPPLIER_DELETE' || $action === 'BILL_SUPPLIER_SENTBYMAIL'
81
+            || $action==='MEMBER_SUBSCRIPTION_CREATE' || $action==='MEMBER_SUBSCRIPTION_MODIFY' || $action==='MEMBER_SUBSCRIPTION_DELETE'
82
+            || $action==='DON_VALIDATE' || $action==='DON_MODIFY' || $action==='DON_DELETE'
83
+            || $action==='CASHCONTROL_VALIDATE'
84
+            || (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_DOWNLOAD') || (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_PREVIEW')
85
+        )
86
+        {
87
+            $qualified++;
88
+
89
+            if (in_array($action, array(
90
+                'MEMBER_SUBSCRIPTION_CREATE','MEMBER_SUBSCRIPTION_MODIFY','MEMBER_SUBSCRIPTION_DELETE',
91
+                'DON_VALIDATE','DON_MODIFY','DON_DELETE'))) $amounts = (double) $object->amount;
92
+            elseif ($action == 'CASHCONTROL_VALIDATE')
93
+            {
94
+                $amounts = (double) $object->cash + (double) $object->cheque + (double) $object->card;
95
+            }
96
+            else $amounts = (double) $object->total_ttc;
97
+        }
98
+        /*if ($action === 'BILL_PAYED' || $action==='BILL_UNPAYED'
99 99
 		 || $action === 'BILL_SUPPLIER_PAYED' || $action === 'BILL_SUPPLIER_UNPAYED')
100 100
 		{
101 101
 			$qualified++;
102 102
 			$amounts=  (double) $object->total_ttc;
103 103
 		}*/
104
-		if ($action === 'PAYMENT_CUSTOMER_CREATE' || $action === 'PAYMENT_SUPPLIER_CREATE' || $action === 'DONATION_PAYMENT_CREATE'
105
-			|| $action === 'PAYMENT_CUSTOMER_DELETE' || $action === 'PAYMENT_SUPPLIER_DELETE' || $action === 'DONATION_PAYMENT_DELETE')
106
-		{
107
-			$qualified++;
108
-			$amounts = 0;
109
-			if(!empty($object->amounts)) {
110
-				foreach($object->amounts as $amount) {
111
-					$amounts += price2num($amount);
112
-				}
113
-			}
114
-		}
115
-		elseif (strpos($action,'PAYMENT')!==false && ! in_array($action, array('PAYMENT_ADD_TO_BANK')))
116
-		{
117
-			$qualified++;
118
-			$amounts = (double) $object->amount;
119
-		}
120
-
121
-		// Another protection.
122
-		// May be used when event is DOC_DOWNLOAD or DOC_PREVIEW and element is not an invoice
123
-		if (! $qualified)
124
-		{
125
-			return 0; // not implemented action log
126
-		}
127
-
128
-		$result = $b->setObjectData($object, $action, $amounts, $user);		// Set field date_object, ref_object, fk_object, element, object_data
129
-
130
-		if ($result < 0)
131
-		{
132
-			$this->error = $b->error;
133
-			$this->errors = $b->errors;
134
-			return -1;
135
-		}
136
-
137
-		$res = $b->create($user);
138
-
139
-		if ($res < 0)
140
-		{
141
-			$this->error = $b->error;
142
-			$this->errors = $b->errors;
143
-			return -1;
144
-		}
145
-		else
146
-		{
147
-			return 1;
148
-		}
104
+        if ($action === 'PAYMENT_CUSTOMER_CREATE' || $action === 'PAYMENT_SUPPLIER_CREATE' || $action === 'DONATION_PAYMENT_CREATE'
105
+            || $action === 'PAYMENT_CUSTOMER_DELETE' || $action === 'PAYMENT_SUPPLIER_DELETE' || $action === 'DONATION_PAYMENT_DELETE')
106
+        {
107
+            $qualified++;
108
+            $amounts = 0;
109
+            if(!empty($object->amounts)) {
110
+                foreach($object->amounts as $amount) {
111
+                    $amounts += price2num($amount);
112
+                }
113
+            }
114
+        }
115
+        elseif (strpos($action,'PAYMENT')!==false && ! in_array($action, array('PAYMENT_ADD_TO_BANK')))
116
+        {
117
+            $qualified++;
118
+            $amounts = (double) $object->amount;
119
+        }
120
+
121
+        // Another protection.
122
+        // May be used when event is DOC_DOWNLOAD or DOC_PREVIEW and element is not an invoice
123
+        if (! $qualified)
124
+        {
125
+            return 0; // not implemented action log
126
+        }
127
+
128
+        $result = $b->setObjectData($object, $action, $amounts, $user);		// Set field date_object, ref_object, fk_object, element, object_data
129
+
130
+        if ($result < 0)
131
+        {
132
+            $this->error = $b->error;
133
+            $this->errors = $b->errors;
134
+            return -1;
135
+        }
136
+
137
+        $res = $b->create($user);
138
+
139
+        if ($res < 0)
140
+        {
141
+            $this->error = $b->error;
142
+            $this->errors = $b->errors;
143
+            return -1;
144
+        }
145
+        else
146
+        {
147
+            return 1;
148
+        }
149 149
     }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -56,19 +56,19 @@  discard block
 block discarded – undo
56 56
 	 */
57 57
 	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
58 58
 	{
59
-		if (empty($conf->blockedlog->enabled)) return 0;     // Module not active, we do nothing
59
+		if (empty($conf->blockedlog->enabled)) return 0; // Module not active, we do nothing
60 60
 
61 61
 		// Test if event/record is qualified
62 62
 		$listofqualifiedelement = array('facture', 'don', 'payment', 'payment_donation', 'subscription', 'payment_various', 'cashcontrol');
63
-		if (! in_array($object->element, $listofqualifiedelement)) return 1;
63
+		if (!in_array($object->element, $listofqualifiedelement)) return 1;
64 64
 
65 65
 		dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
66 66
 
67 67
 		require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
68
-		$b=new BlockedLog($this->db);
68
+		$b = new BlockedLog($this->db);
69 69
 
70 70
 		// Tracked events
71
-		if (! in_array($action, array_keys($b->trackedevents)))
71
+		if (!in_array($action, array_keys($b->trackedevents)))
72 72
 		{
73 73
 			return 0;
74 74
 		}
@@ -76,19 +76,19 @@  discard block
 block discarded – undo
76 76
 		// Event/record is qualified
77 77
 		$qualified = 0;
78 78
 		$amounts = 0;
79
-		if ($action==='BILL_VALIDATE' || $action==='BILL_DELETE' || $action === 'BILL_SENTBYMAIL'
80
-			|| $action==='BILL_SUPPLIER_VALIDATE' || $action==='BILL_SUPPLIER_DELETE' || $action === 'BILL_SUPPLIER_SENTBYMAIL'
81
-			|| $action==='MEMBER_SUBSCRIPTION_CREATE' || $action==='MEMBER_SUBSCRIPTION_MODIFY' || $action==='MEMBER_SUBSCRIPTION_DELETE'
82
-			|| $action==='DON_VALIDATE' || $action==='DON_MODIFY' || $action==='DON_DELETE'
83
-			|| $action==='CASHCONTROL_VALIDATE'
84
-			|| (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_DOWNLOAD') || (in_array($object->element, array('facture','suplier_invoice')) && $action === 'DOC_PREVIEW')
79
+		if ($action === 'BILL_VALIDATE' || $action === 'BILL_DELETE' || $action === 'BILL_SENTBYMAIL'
80
+			|| $action === 'BILL_SUPPLIER_VALIDATE' || $action === 'BILL_SUPPLIER_DELETE' || $action === 'BILL_SUPPLIER_SENTBYMAIL'
81
+			|| $action === 'MEMBER_SUBSCRIPTION_CREATE' || $action === 'MEMBER_SUBSCRIPTION_MODIFY' || $action === 'MEMBER_SUBSCRIPTION_DELETE'
82
+			|| $action === 'DON_VALIDATE' || $action === 'DON_MODIFY' || $action === 'DON_DELETE'
83
+			|| $action === 'CASHCONTROL_VALIDATE'
84
+			|| (in_array($object->element, array('facture', 'suplier_invoice')) && $action === 'DOC_DOWNLOAD') || (in_array($object->element, array('facture', 'suplier_invoice')) && $action === 'DOC_PREVIEW')
85 85
 		)
86 86
 		{
87 87
 			$qualified++;
88 88
 
89 89
 			if (in_array($action, array(
90
-				'MEMBER_SUBSCRIPTION_CREATE','MEMBER_SUBSCRIPTION_MODIFY','MEMBER_SUBSCRIPTION_DELETE',
91
-				'DON_VALIDATE','DON_MODIFY','DON_DELETE'))) $amounts = (double) $object->amount;
90
+				'MEMBER_SUBSCRIPTION_CREATE', 'MEMBER_SUBSCRIPTION_MODIFY', 'MEMBER_SUBSCRIPTION_DELETE',
91
+				'DON_VALIDATE', 'DON_MODIFY', 'DON_DELETE'))) $amounts = (double) $object->amount;
92 92
 			elseif ($action == 'CASHCONTROL_VALIDATE')
93 93
 			{
94 94
 				$amounts = (double) $object->cash + (double) $object->cheque + (double) $object->card;
@@ -106,13 +106,13 @@  discard block
 block discarded – undo
106 106
 		{
107 107
 			$qualified++;
108 108
 			$amounts = 0;
109
-			if(!empty($object->amounts)) {
110
-				foreach($object->amounts as $amount) {
109
+			if (!empty($object->amounts)) {
110
+				foreach ($object->amounts as $amount) {
111 111
 					$amounts += price2num($amount);
112 112
 				}
113 113
 			}
114 114
 		}
115
-		elseif (strpos($action,'PAYMENT')!==false && ! in_array($action, array('PAYMENT_ADD_TO_BANK')))
115
+		elseif (strpos($action, 'PAYMENT') !== false && !in_array($action, array('PAYMENT_ADD_TO_BANK')))
116 116
 		{
117 117
 			$qualified++;
118 118
 			$amounts = (double) $object->amount;
@@ -120,12 +120,12 @@  discard block
 block discarded – undo
120 120
 
121 121
 		// Another protection.
122 122
 		// May be used when event is DOC_DOWNLOAD or DOC_PREVIEW and element is not an invoice
123
-		if (! $qualified)
123
+		if (!$qualified)
124 124
 		{
125 125
 			return 0; // not implemented action log
126 126
 		}
127 127
 
128
-		$result = $b->setObjectData($object, $action, $amounts, $user);		// Set field date_object, ref_object, fk_object, element, object_data
128
+		$result = $b->setObjectData($object, $action, $amounts, $user); // Set field date_object, ref_object, fk_object, element, object_data
129 129
 
130 130
 		if ($result < 0)
131 131
 		{
Please login to merge, or discard this patch.
Braces   +14 added lines, -9 removed lines patch added patch discarded remove patch
@@ -56,11 +56,16 @@  discard block
 block discarded – undo
56 56
 	 */
57 57
 	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
58 58
 	{
59
-		if (empty($conf->blockedlog->enabled)) return 0;     // Module not active, we do nothing
59
+		if (empty($conf->blockedlog->enabled)) {
60
+		    return 0;
61
+		}
62
+		// Module not active, we do nothing
60 63
 
61 64
 		// Test if event/record is qualified
62 65
 		$listofqualifiedelement = array('facture', 'don', 'payment', 'payment_donation', 'subscription', 'payment_various', 'cashcontrol');
63
-		if (! in_array($object->element, $listofqualifiedelement)) return 1;
66
+		if (! in_array($object->element, $listofqualifiedelement)) {
67
+		    return 1;
68
+		}
64 69
 
65 70
 		dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
66 71
 
@@ -88,12 +93,14 @@  discard block
 block discarded – undo
88 93
 
89 94
 			if (in_array($action, array(
90 95
 				'MEMBER_SUBSCRIPTION_CREATE','MEMBER_SUBSCRIPTION_MODIFY','MEMBER_SUBSCRIPTION_DELETE',
91
-				'DON_VALIDATE','DON_MODIFY','DON_DELETE'))) $amounts = (double) $object->amount;
92
-			elseif ($action == 'CASHCONTROL_VALIDATE')
96
+				'DON_VALIDATE','DON_MODIFY','DON_DELETE'))) {
97
+			    $amounts = (double) $object->amount;
98
+			} elseif ($action == 'CASHCONTROL_VALIDATE')
93 99
 			{
94 100
 				$amounts = (double) $object->cash + (double) $object->cheque + (double) $object->card;
101
+			} else {
102
+			    $amounts = (double) $object->total_ttc;
95 103
 			}
96
-			else $amounts = (double) $object->total_ttc;
97 104
 		}
98 105
 		/*if ($action === 'BILL_PAYED' || $action==='BILL_UNPAYED'
99 106
 		 || $action === 'BILL_SUPPLIER_PAYED' || $action === 'BILL_SUPPLIER_UNPAYED')
@@ -111,8 +118,7 @@  discard block
 block discarded – undo
111 118
 					$amounts += price2num($amount);
112 119
 				}
113 120
 			}
114
-		}
115
-		elseif (strpos($action,'PAYMENT')!==false && ! in_array($action, array('PAYMENT_ADD_TO_BANK')))
121
+		} elseif (strpos($action,'PAYMENT')!==false && ! in_array($action, array('PAYMENT_ADD_TO_BANK')))
116 122
 		{
117 123
 			$qualified++;
118 124
 			$amounts = (double) $object->amount;
@@ -141,8 +147,7 @@  discard block
 block discarded – undo
141 147
 			$this->error = $b->error;
142 148
 			$this->errors = $b->errors;
143 149
 			return -1;
144
-		}
145
-		else
150
+		} else
146 151
 		{
147 152
 			return 1;
148 153
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/mssql.class.php 3 patches
Indentation   +967 added lines, -967 removed lines patch added patch discarded remove patch
@@ -31,101 +31,101 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class DoliDBMssql extends DoliDB
33 33
 {
34
-	//! Database type
35
-	public $type='mssql';
36
-	//! Database label
37
-	const LABEL='MSSQL';
38
-	//! Charset used to force charset when creating database
39
-	var $forcecharset='latin1';      // Can't be static as it may be forced with a dynamic value
40
-	//! Collate used to force collate when creating database
41
-	var $forcecollate='latin1_swedish_ci';      // Can't be static as it may be forced with a dynamic value
42
-	//! Version min database
43
-	const VERSIONMIN='2000';
44
-	/** @var resource Resultset of last query */
45
-	private $_results;
34
+    //! Database type
35
+    public $type='mssql';
36
+    //! Database label
37
+    const LABEL='MSSQL';
38
+    //! Charset used to force charset when creating database
39
+    var $forcecharset='latin1';      // Can't be static as it may be forced with a dynamic value
40
+    //! Collate used to force collate when creating database
41
+    var $forcecollate='latin1_swedish_ci';      // Can't be static as it may be forced with a dynamic value
42
+    //! Version min database
43
+    const VERSIONMIN='2000';
44
+    /** @var resource Resultset of last query */
45
+    private $_results;
46 46
 
47 47
     /**
48
-	 *	Constructor.
49
-	 *	This create an opened connexion to a database server and eventually to a database
50
-	 *
51
-	 *	@param      string	$type		Type of database (mysql, pgsql...)
52
-	 *	@param	    string	$host		Address of database server
53
-	 *	@param	    string	$user		Nom de l'utilisateur autorise
54
-	 *	@param	    string	$pass		Mot de passe
55
-	 *	@param	    string	$name		Nom de la database
56
-	 *	@param	    int		$port		Port of database server
48
+     *	Constructor.
49
+     *	This create an opened connexion to a database server and eventually to a database
50
+     *
51
+     *	@param      string	$type		Type of database (mysql, pgsql...)
52
+     *	@param	    string	$host		Address of database server
53
+     *	@param	    string	$user		Nom de l'utilisateur autorise
54
+     *	@param	    string	$pass		Mot de passe
55
+     *	@param	    string	$name		Nom de la database
56
+     *	@param	    int		$port		Port of database server
57 57
      */
58
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
59
-	{
60
-		global $langs;
58
+    function __construct($type, $host, $user, $pass, $name='', $port=0)
59
+    {
60
+        global $langs;
61 61
 
62
-		$this->database_user=$user;
62
+        $this->database_user=$user;
63 63
         $this->database_host=$host;
64 64
         $this->database_port=$port;
65
-		$this->transaction_opened=0;
66
-
67
-		if (! function_exists("mssql_connect"))
68
-		{
69
-			$this->connected = false;
70
-			$this->ok = false;
71
-			$this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
72
-			dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP",LOG_ERR);
73
-			return $this->ok;
74
-		}
75
-
76
-		if (! $host)
77
-		{
78
-			$this->connected = false;
79
-			$this->ok = false;
80
-			$this->error=$langs->trans("ErrorWrongHostParameter");
81
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
82
-			return $this->ok;
83
-		}
84
-
85
-		// Essai connexion serveur
86
-		$this->db = $this->connect($host, $user, $pass, $name, $port);
87
-		if ($this->db)
88
-		{
89
-			// Si client connecte avec charset different de celui de la base Dolibarr
90
-			// (La base Dolibarr a ete forcee en this->forcecharset a l'install)
91
-			$this->connected = true;
92
-			$this->ok = true;
93
-		}
94
-		else
95
-		{
96
-			// host, login ou password incorrect
97
-			$this->connected = false;
98
-			$this->ok = false;
99
-			$this->error=mssql_get_last_message();
100
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error,LOG_ERR);
101
-		}
102
-
103
-		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
104
-		if ($this->connected && $name)
105
-		{
106
-			if ($this->select_db($name))
107
-			{
108
-				$this->database_selected = true;
109
-				$this->database_name = $name;
110
-				$this->ok = true;
111
-			}
112
-			else
113
-			{
114
-				$this->database_selected = false;
115
-				$this->database_name = '';
116
-				$this->ok = false;
117
-				$this->error=$this->error();
118
-				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
119
-			}
120
-		}
121
-		else
122
-		{
123
-			// Pas de selection de base demandee, ok ou ko
124
-			$this->database_selected = false;
125
-		}
126
-
127
-		return $this->ok;
128
-	}
65
+        $this->transaction_opened=0;
66
+
67
+        if (! function_exists("mssql_connect"))
68
+        {
69
+            $this->connected = false;
70
+            $this->ok = false;
71
+            $this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
72
+            dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP",LOG_ERR);
73
+            return $this->ok;
74
+        }
75
+
76
+        if (! $host)
77
+        {
78
+            $this->connected = false;
79
+            $this->ok = false;
80
+            $this->error=$langs->trans("ErrorWrongHostParameter");
81
+            dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
82
+            return $this->ok;
83
+        }
84
+
85
+        // Essai connexion serveur
86
+        $this->db = $this->connect($host, $user, $pass, $name, $port);
87
+        if ($this->db)
88
+        {
89
+            // Si client connecte avec charset different de celui de la base Dolibarr
90
+            // (La base Dolibarr a ete forcee en this->forcecharset a l'install)
91
+            $this->connected = true;
92
+            $this->ok = true;
93
+        }
94
+        else
95
+        {
96
+            // host, login ou password incorrect
97
+            $this->connected = false;
98
+            $this->ok = false;
99
+            $this->error=mssql_get_last_message();
100
+            dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error,LOG_ERR);
101
+        }
102
+
103
+        // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
104
+        if ($this->connected && $name)
105
+        {
106
+            if ($this->select_db($name))
107
+            {
108
+                $this->database_selected = true;
109
+                $this->database_name = $name;
110
+                $this->ok = true;
111
+            }
112
+            else
113
+            {
114
+                $this->database_selected = false;
115
+                $this->database_name = '';
116
+                $this->ok = false;
117
+                $this->error=$this->error();
118
+                dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
119
+            }
120
+        }
121
+        else
122
+        {
123
+            // Pas de selection de base demandee, ok ou ko
124
+            $this->database_selected = false;
125
+        }
126
+
127
+        return $this->ok;
128
+    }
129 129
 
130 130
     /**
131 131
      *  Convert a SQL request in Mysql syntax to native syntax
@@ -134,83 +134,83 @@  discard block
 block discarded – undo
134 134
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
135 135
      *  @return    string   		SQL request line converted
136 136
      */
137
-	static function convertSQLFromMysql($line,$type='ddl')
138
-	{
139
-		return $line;
140
-	}
137
+    static function convertSQLFromMysql($line,$type='ddl')
138
+    {
139
+        return $line;
140
+    }
141 141
 
142 142
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
143
-	/**
144
-	 *	Select a database
145
-	 *
146
-	 *	@param	    string	$database	Name of database
147
-	 *	@return	    boolean  		    true if OK, false if KO
148
-	 */
149
-	function select_db($database)
150
-	{
143
+    /**
144
+     *	Select a database
145
+     *
146
+     *	@param	    string	$database	Name of database
147
+     *	@return	    boolean  		    true if OK, false if KO
148
+     */
149
+    function select_db($database)
150
+    {
151 151
         // phpcs:enable
152
-		return @mssql_select_db($database, $this->db);
153
-	}
154
-
155
-	/**
156
-	 *	Connexion to server
157
-	 *
158
-	 *	@param	    string	$host		database server host
159
-	 *	@param	    string	$login		login
160
-	 *	@param	    string	$passwd		password
161
-	 *	@param		string	$name		name of database (not used for mysql, used for pgsql)
162
-	 *	@param		int		$port		Port of database server
163
-	 *	@return		false|resource|true	Database access handler
164
-	 *	@see		close
165
-	 */
166
-	function connect($host, $login, $passwd, $name, $port=0)
167
-	{
168
-		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
169
-		$newhost=$host;
170
-		if ($port) $newhost.=':'.$port;
171
-		$this->db  = @mssql_connect($newhost, $login, $passwd);
172
-		//force les enregistrement en latin1 si la base est en utf8 par defaut
173
-		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
174
-		// les nouvelles version de Dolibarr car force par l'install Dolibarr.
175
-		//$this->query('SET NAMES '.$this->forcecharset);
176
-		//print "Resultat fonction connect: ".$this->db;
177
-		$set_options=array('SET ANSI_PADDING ON;',
178
-		    "SET ANSI_NULLS ON;",
179
-		    "SET ANSI_WARNINGS ON;",
180
-		    "SET ARITHABORT ON;",
181
-		    "SET CONCAT_NULL_YIELDS_NULL ON;",
182
-		    "SET QUOTED_IDENTIFIER ON;"
183
-		);
184
-		mssql_query(implode(' ',$set_options),$this->db);
185
-
186
-		return $this->db;
187
-	}
188
-
189
-	/**
190
-	 *	Return version of database server
191
-	 *
192
-	 *	@return	        string      Version string
193
-	 */
194
-	function getVersion()
195
-	{
196
-		$resql=$this->query("SELECT @@VERSION");
197
-		if ($resql)
198
-		{
152
+        return @mssql_select_db($database, $this->db);
153
+    }
154
+
155
+    /**
156
+     *	Connexion to server
157
+     *
158
+     *	@param	    string	$host		database server host
159
+     *	@param	    string	$login		login
160
+     *	@param	    string	$passwd		password
161
+     *	@param		string	$name		name of database (not used for mysql, used for pgsql)
162
+     *	@param		int		$port		Port of database server
163
+     *	@return		false|resource|true	Database access handler
164
+     *	@see		close
165
+     */
166
+    function connect($host, $login, $passwd, $name, $port=0)
167
+    {
168
+        dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
169
+        $newhost=$host;
170
+        if ($port) $newhost.=':'.$port;
171
+        $this->db  = @mssql_connect($newhost, $login, $passwd);
172
+        //force les enregistrement en latin1 si la base est en utf8 par defaut
173
+        // Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
174
+        // les nouvelles version de Dolibarr car force par l'install Dolibarr.
175
+        //$this->query('SET NAMES '.$this->forcecharset);
176
+        //print "Resultat fonction connect: ".$this->db;
177
+        $set_options=array('SET ANSI_PADDING ON;',
178
+            "SET ANSI_NULLS ON;",
179
+            "SET ANSI_WARNINGS ON;",
180
+            "SET ARITHABORT ON;",
181
+            "SET CONCAT_NULL_YIELDS_NULL ON;",
182
+            "SET QUOTED_IDENTIFIER ON;"
183
+        );
184
+        mssql_query(implode(' ',$set_options),$this->db);
185
+
186
+        return $this->db;
187
+    }
188
+
189
+    /**
190
+     *	Return version of database server
191
+     *
192
+     *	@return	        string      Version string
193
+     */
194
+    function getVersion()
195
+    {
196
+        $resql=$this->query("SELECT @@VERSION");
197
+        if ($resql)
198
+        {
199 199
             $version=$this->fetch_array($resql);
200 200
             return $version['computed'];
201
-		}
202
-		else return '';
203
-	}
204
-
205
-	/**
206
-	 *	Return version of database client driver
207
-	 *
208
-	 *	@return	        string      Version string
209
-	 */
210
-	function getDriverInfo()
211
-	{
212
-		return 'php mssql driver';
213
-	}
201
+        }
202
+        else return '';
203
+    }
204
+
205
+    /**
206
+     *	Return version of database client driver
207
+     *
208
+     *	@return	        string      Version string
209
+     */
210
+    function getDriverInfo()
211
+    {
212
+        return 'php mssql driver';
213
+    }
214 214
 
215 215
     /**
216 216
      *  Close database connexion
@@ -222,100 +222,100 @@  discard block
 block discarded – undo
222 222
     {
223 223
         if ($this->db)
224 224
         {
225
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
226
-          $this->connected=false;
227
-          return mssql_close($this->db);
225
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
226
+            $this->connected=false;
227
+            return mssql_close($this->db);
228 228
         }
229 229
         return false;
230 230
     }
231 231
 
232 232
 
233
-	/**
234
-	 * Start transaction
235
-	 *
236
-	 * @return	    bool         true if transaction successfuly opened or already opened, false if error
237
-	 */
238
-	function begin()
239
-	{
240
-
241
-	    $res=mssql_query('select @@TRANCOUNT');
242
-	    $this->transaction_opened=mssql_result($res, 0, 0);
243
-
244
-	    if ($this->transaction_opened == 0)
245
-		{
246
-		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
247
-			$ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
248
-			if ($ret)
249
-			{
250
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
251
-			}
252
-			return $ret;
253
-		}
254
-		else
255
-		{
256
-			return true;
257
-		}
258
-	}
259
-
260
-	/**
233
+    /**
234
+     * Start transaction
235
+     *
236
+     * @return	    bool         true if transaction successfuly opened or already opened, false if error
237
+     */
238
+    function begin()
239
+    {
240
+
241
+        $res=mssql_query('select @@TRANCOUNT');
242
+        $this->transaction_opened=mssql_result($res, 0, 0);
243
+
244
+        if ($this->transaction_opened == 0)
245
+        {
246
+            //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
247
+            $ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
248
+            if ($ret)
249
+            {
250
+                dol_syslog("BEGIN Transaction",LOG_DEBUG);
251
+            }
252
+            return $ret;
253
+        }
254
+        else
255
+        {
256
+            return true;
257
+        }
258
+    }
259
+
260
+    /**
261 261
      * Validate a database transaction
262 262
      *
263 263
      * @param	string	$log        Add more log to default log line
264 264
      * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
265
-	 */
266
-	function commit($log='')
267
-	{
268
-	    $res=mssql_query('select @@TRANCOUNT');
269
-	    $this->transaction_opened=mssql_result($res, 0, 0);
270
-
271
-		if ($this->transaction_opened == 1)
272
-		{
273
-		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
274
-			$ret=mssql_query("COMMIT TRANSACTION",$this->db);
275
-			if ($ret)
276
-			{
277
-				dol_syslog("COMMIT Transaction",LOG_DEBUG);
278
-				return true;
279
-			}
280
-			else
281
-			{
282
-				return false;
283
-			}
284
-		}
285
-		elseif ($this->transaction_opened > 1)
286
-		{
287
-			return true;
288
-		}
289
-		trigger_error("Commit requested but no transaction remain");
290
-		return false;
291
-	}
292
-
293
-	/**
294
-	 * Annulation d'une transaction et retour aux anciennes valeurs
295
-	 *
296
-	 * @param	string	$log	Add more log to default log line
297
-	 * @return	bool             true si annulation ok ou transaction non ouverte, false en cas d'erreur
298
-	 */
299
-	function rollback($log='')
300
-	{
301
-	    $res=mssql_query('select @@TRANCOUNT');
302
-	    $this->transaction_opened=mssql_result($res, 0, 0);
303
-
304
-		if ($this->transaction_opened == 1)
305
-		{
306
-			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
307
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
308
-			return $ret;
309
-		}
310
-		elseif ($this->transaction_opened > 1)
311
-		{
312
-			return true;
313
-		}
314
-		trigger_error("Rollback requested but no transaction remain");
315
-		return false;
316
-	}
317
-
318
-	/**
265
+     */
266
+    function commit($log='')
267
+    {
268
+        $res=mssql_query('select @@TRANCOUNT');
269
+        $this->transaction_opened=mssql_result($res, 0, 0);
270
+
271
+        if ($this->transaction_opened == 1)
272
+        {
273
+            //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
274
+            $ret=mssql_query("COMMIT TRANSACTION",$this->db);
275
+            if ($ret)
276
+            {
277
+                dol_syslog("COMMIT Transaction",LOG_DEBUG);
278
+                return true;
279
+            }
280
+            else
281
+            {
282
+                return false;
283
+            }
284
+        }
285
+        elseif ($this->transaction_opened > 1)
286
+        {
287
+            return true;
288
+        }
289
+        trigger_error("Commit requested but no transaction remain");
290
+        return false;
291
+    }
292
+
293
+    /**
294
+     * Annulation d'une transaction et retour aux anciennes valeurs
295
+     *
296
+     * @param	string	$log	Add more log to default log line
297
+     * @return	bool             true si annulation ok ou transaction non ouverte, false en cas d'erreur
298
+     */
299
+    function rollback($log='')
300
+    {
301
+        $res=mssql_query('select @@TRANCOUNT');
302
+        $this->transaction_opened=mssql_result($res, 0, 0);
303
+
304
+        if ($this->transaction_opened == 1)
305
+        {
306
+            $ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
307
+            dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
308
+            return $ret;
309
+        }
310
+        elseif ($this->transaction_opened > 1)
311
+        {
312
+            return true;
313
+        }
314
+        trigger_error("Rollback requested but no transaction remain");
315
+        return false;
316
+    }
317
+
318
+    /**
319 319
      *  Execute a SQL request and return the resultset
320 320
      *
321 321
      *  @param	string	$query          SQL query string
@@ -323,32 +323,32 @@  discard block
 block discarded – undo
323 323
      *                   		 		Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
324 324
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
325 325
      *  @return false|resource|true		Resultset of answer
326
-	 */
327
-	function query($query,$usesavepoint=0,$type='auto')
328
-	{
329
-		$query = trim($query);
330
-
331
-		if (preg_match('/^--/',$query)) return true;
332
-
333
-		// Conversion syntaxe MySql vers MSDE.
334
-		$query = str_ireplace("now()", "getdate()", $query);
335
-		// Erreur SQL: cannot update timestamp field
336
-		$query = str_ireplace(", tms = tms", "", $query);
337
-
338
-		$query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
339
-
340
-		if ($type=="auto" || $type='dml')
341
-		{
342
-    		$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
343
-    		$query=preg_replace('/double/i','float',$query);
344
-    		$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
345
-    		$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
346
-    		$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
347
-
348
-    		$matches=array();
349
-    		$original_query='';
350
-    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
351
-    		{
326
+     */
327
+    function query($query,$usesavepoint=0,$type='auto')
328
+    {
329
+        $query = trim($query);
330
+
331
+        if (preg_match('/^--/',$query)) return true;
332
+
333
+        // Conversion syntaxe MySql vers MSDE.
334
+        $query = str_ireplace("now()", "getdate()", $query);
335
+        // Erreur SQL: cannot update timestamp field
336
+        $query = str_ireplace(", tms = tms", "", $query);
337
+
338
+        $query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
339
+
340
+        if ($type=="auto" || $type='dml')
341
+        {
342
+            $query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
343
+            $query=preg_replace('/double/i','float',$query);
344
+            $query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
345
+            $query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
346
+            $query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
347
+
348
+            $matches=array();
349
+            $original_query='';
350
+            if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
351
+            {
352 352
                 $original_query=$query;
353 353
                 $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
354 354
                 if ($matches[2]) {
@@ -365,658 +365,658 @@  discard block
 block discarded – undo
365 365
                     if (! empty($query_comp))
366 366
                         $query.=" WHERE ".implode(" AND ",$query_comp);
367 367
                 }
368
-    		}
369
-    		else
370
-    		{
371
-    		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
372
-    		    {
368
+            }
369
+            else
370
+            {
371
+                if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
372
+                {
373 373
                     $original_query=$query;
374 374
                     $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
375
-    		    }
376
-    		}
377
-		}
378
-
379
-		if ($type=="auto" || $type='ddl')
380
-		{
381
-    		$itemfound = stripos($query, " limit ");
382
-    		if ($itemfound !== false) {
383
-    			// Extraire le nombre limite
384
-    			$number = stristr($query, " limit ");
385
-    			$number = substr($number, 7);
386
-    			// Inserer l'instruction TOP et le nombre limite
387
-    			$query = str_ireplace("select ", "select top ".$number." ", $query);
388
-    			// Supprimer l'instruction MySql
389
-    			$query = str_ireplace(" limit ".$number, "", $query);
390
-    		}
391
-
392
-    		$itemfound = stripos($query, " week(");
393
-    		if ($itemfound !== false) {
394
-    			// Recreer une requete sans instruction Mysql
395
-    			$positionMySql = stripos($query, " week(");
396
-    			$newquery = substr($query, 0, $positionMySql);
397
-
398
-    			// Recuperer la date passee en parametre
399
-    			$extractvalue = stristr($query, " week(");
400
-    			$extractvalue = substr($extractvalue, 6);
401
-    			$positionMySql = stripos($extractvalue, ")");
402
-    			// Conserver la fin de la requete
403
-    			$endofquery = substr($extractvalue, $positionMySql);
404
-    			$extractvalue = substr($extractvalue, 0, $positionMySql);
405
-
406
-    			// Remplacer l'instruction MySql en Sql Server
407
-    			// Inserer la date en parametre et le reste de la requete
408
-    			$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
409
-    		}
410
-    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
411
-    	   {
412
-    	       //var_dump($query);
413
-    	       //var_dump($matches);
414
-    	       //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
415
-    	       $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
416
-    	       @mssql_query($sql, $this->db);
417
-    	       $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
418
-    	   }
419
-		}
420
-		//print "<!--".$query."-->";
421
-
422
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
423
-
424
-		if (! $this->database_name)
425
-		{
426
-			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
427
-			$ret = mssql_query($query, $this->db);
428
-		}
429
-		else
430
-		{
431
-			$ret = mssql_query($query, $this->db);
432
-		}
433
-
434
-		if (!empty($post_query))
435
-		{
436
-		    @mssql_query($post_query, $this->db);
437
-		}
438
-
439
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
440
-		{
441
-			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
442
-			if (! $ret)
443
-			{
444
-				$result = mssql_query("SELECT @@ERROR as code", $this->db);
445
-				$row = mssql_fetch_array($result);
375
+                }
376
+            }
377
+        }
378
+
379
+        if ($type=="auto" || $type='ddl')
380
+        {
381
+            $itemfound = stripos($query, " limit ");
382
+            if ($itemfound !== false) {
383
+                // Extraire le nombre limite
384
+                $number = stristr($query, " limit ");
385
+                $number = substr($number, 7);
386
+                // Inserer l'instruction TOP et le nombre limite
387
+                $query = str_ireplace("select ", "select top ".$number." ", $query);
388
+                // Supprimer l'instruction MySql
389
+                $query = str_ireplace(" limit ".$number, "", $query);
390
+            }
391
+
392
+            $itemfound = stripos($query, " week(");
393
+            if ($itemfound !== false) {
394
+                // Recreer une requete sans instruction Mysql
395
+                $positionMySql = stripos($query, " week(");
396
+                $newquery = substr($query, 0, $positionMySql);
397
+
398
+                // Recuperer la date passee en parametre
399
+                $extractvalue = stristr($query, " week(");
400
+                $extractvalue = substr($extractvalue, 6);
401
+                $positionMySql = stripos($extractvalue, ")");
402
+                // Conserver la fin de la requete
403
+                $endofquery = substr($extractvalue, $positionMySql);
404
+                $extractvalue = substr($extractvalue, 0, $positionMySql);
405
+
406
+                // Remplacer l'instruction MySql en Sql Server
407
+                // Inserer la date en parametre et le reste de la requete
408
+                $query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
409
+            }
410
+            if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
411
+            {
412
+                //var_dump($query);
413
+                //var_dump($matches);
414
+                //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
415
+                $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
416
+                @mssql_query($sql, $this->db);
417
+                $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
418
+            }
419
+        }
420
+        //print "<!--".$query."-->";
421
+
422
+        if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
423
+
424
+        if (! $this->database_name)
425
+        {
426
+            // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
427
+            $ret = mssql_query($query, $this->db);
428
+        }
429
+        else
430
+        {
431
+            $ret = mssql_query($query, $this->db);
432
+        }
433
+
434
+        if (!empty($post_query))
435
+        {
436
+            @mssql_query($post_query, $this->db);
437
+        }
438
+
439
+        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
440
+        {
441
+            // Si requete utilisateur, on la sauvegarde ainsi que son resultset
442
+            if (! $ret)
443
+            {
444
+                $result = mssql_query("SELECT @@ERROR as code", $this->db);
445
+                $row = mssql_fetch_array($result);
446 446
 
447 447
                 $this->lastqueryerror = $query;
448
-				$this->lasterror = $this->error();
449
-				$this->lasterrno = $row["code"];
448
+                $this->lasterror = $this->error();
449
+                $this->lasterrno = $row["code"];
450 450
 
451
-				dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
452
-				if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
453
-				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
454
-			}
455
-			$this->lastquery=$query;
456
-			$this->_results = $ret;
457
-		}
451
+                dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
452
+                if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
453
+                dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
454
+            }
455
+            $this->lastquery=$query;
456
+            $this->_results = $ret;
457
+        }
458 458
 
459
-		return $ret;
460
-	}
459
+        return $ret;
460
+    }
461 461
 
462 462
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
463
-	/**
464
-	 *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
465
-	 *
466
-	 *	@param	resource	$resultset  Curseur de la requete voulue
467
-	 *	@return	object|false			Object result line or false if KO or end of cursor
468
-	 */
469
-	function fetch_object($resultset)
470
-	{
463
+    /**
464
+     *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
465
+     *
466
+     *	@param	resource	$resultset  Curseur de la requete voulue
467
+     *	@return	object|false			Object result line or false if KO or end of cursor
468
+     */
469
+    function fetch_object($resultset)
470
+    {
471 471
         // phpcs:enable
472
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
473
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
474
-		return mssql_fetch_object($resultset);
475
-	}
472
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
473
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
474
+        return mssql_fetch_object($resultset);
475
+    }
476 476
 
477 477
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
478
-	/**
478
+    /**
479 479
      *	Return datas as an array
480 480
      *
481 481
      *	@param	resource	$resultset  Resultset of request
482 482
      *	@return	array|false				Array or false if KO or end of cursor
483
-	 */
484
-	function fetch_array($resultset)
485
-	{
483
+     */
484
+    function fetch_array($resultset)
485
+    {
486 486
         // phpcs:enable
487
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
488
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
489
-		return mssql_fetch_array($resultset);
490
-	}
487
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
488
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
489
+        return mssql_fetch_array($resultset);
490
+    }
491 491
 
492 492
 
493 493
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
494
-	/**
494
+    /**
495 495
      *	Return datas as an array
496 496
      *
497 497
      *	@param	resource	$resultset  Resultset of request
498 498
      *	@return	array|false				Array or false if KO or end of cursor
499
-	 */
500
-	function fetch_row($resultset)
501
-	{
499
+     */
500
+    function fetch_row($resultset)
501
+    {
502 502
         // phpcs:enable
503
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
504
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
505
-		return @mssql_fetch_row($resultset);
506
-	}
503
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
504
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
505
+        return @mssql_fetch_row($resultset);
506
+    }
507 507
 
508 508
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
509
-	/**
509
+    /**
510 510
      *	Return number of lines for result of a SELECT
511 511
      *
512 512
      *	@param	resource	$resultset  Resulset of requests
513 513
      *	@return int		    			Nb of lines
514 514
      *	@see    affected_rows
515
-	 */
516
-	function num_rows($resultset)
517
-	{
515
+     */
516
+    function num_rows($resultset)
517
+    {
518 518
         // phpcs:enable
519
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
520
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
521
-		return mssql_num_rows($resultset);
522
-	}
519
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
520
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
521
+        return mssql_num_rows($resultset);
522
+    }
523 523
 
524 524
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
525
-	/**
526
-	 *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
527
-	 *
528
-	 *	@param	resource	$resultset   Curseur de la requete voulue
529
-	 *	@return int		    Nombre de lignes
530
-	 *	@see    num_rows
531
-	 */
532
-	function affected_rows($resultset)
533
-	{
525
+    /**
526
+     *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
527
+     *
528
+     *	@param	resource	$resultset   Curseur de la requete voulue
529
+     *	@return int		    Nombre de lignes
530
+     *	@see    num_rows
531
+     */
532
+    function affected_rows($resultset)
533
+    {
534 534
         // phpcs:enable
535
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
536
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
537
-		// mssql necessite un link de base pour cette fonction contrairement
538
-		// a pqsql qui prend un resultset
539
-		$rsRows = mssql_query("select @@rowcount as rows", $this->db);
540
-		return mssql_result($rsRows, 0, "rows");
541
-		//return mssql_affected_rows($this->db);
542
-	}
543
-
544
-
545
-	/**
546
-	 *	Free last resultset used.
547
-	 *
548
-	 *	@param  resource	$resultset   Curseur de la requete voulue
549
-	 *	@return	bool
550
-	 */
551
-	function free($resultset=null)
552
-	{
553
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
554
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
555
-		// Si resultset en est un, on libere la memoire
556
-		if (is_resource($resultset)) mssql_free_result($resultset);
557
-	}
558
-
559
-	/**
560
-	 *	Escape a string to insert data
561
-	 *
562
-	 *  @param	string	$stringtoencode		String to escape
563
-	 *  @return	string						String escaped
564
-	 */
565
-	function escape($stringtoencode)
566
-	{
567
-		return addslashes($stringtoencode);
568
-	}
569
-
570
-
571
-	/**
572
-	 *   Convert (by PHP) a GM Timestamp date into a PHP server TZ to insert into a date field.
573
-	 *   Function to use to build INSERT, UPDATE or WHERE predica
574
-	 *
575
-	 *   @param	    string	$param      Date TMS to convert
576
-	 *   @return	string      		Date in a string YYYY-MM-DD HH:MM:SS
577
-	 */
578
-	function idate($param)
579
-	{
580
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
581
-	}
582
-
583
-	/**
535
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
536
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
537
+        // mssql necessite un link de base pour cette fonction contrairement
538
+        // a pqsql qui prend un resultset
539
+        $rsRows = mssql_query("select @@rowcount as rows", $this->db);
540
+        return mssql_result($rsRows, 0, "rows");
541
+        //return mssql_affected_rows($this->db);
542
+    }
543
+
544
+
545
+    /**
546
+     *	Free last resultset used.
547
+     *
548
+     *	@param  resource	$resultset   Curseur de la requete voulue
549
+     *	@return	bool
550
+     */
551
+    function free($resultset=null)
552
+    {
553
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
554
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
555
+        // Si resultset en est un, on libere la memoire
556
+        if (is_resource($resultset)) mssql_free_result($resultset);
557
+    }
558
+
559
+    /**
560
+     *	Escape a string to insert data
561
+     *
562
+     *  @param	string	$stringtoencode		String to escape
563
+     *  @return	string						String escaped
564
+     */
565
+    function escape($stringtoencode)
566
+    {
567
+        return addslashes($stringtoencode);
568
+    }
569
+
570
+
571
+    /**
572
+     *   Convert (by PHP) a GM Timestamp date into a PHP server TZ to insert into a date field.
573
+     *   Function to use to build INSERT, UPDATE or WHERE predica
574
+     *
575
+     *   @param	    string	$param      Date TMS to convert
576
+     *   @return	string      		Date in a string YYYY-MM-DD HH:MM:SS
577
+     */
578
+    function idate($param)
579
+    {
580
+        return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
581
+    }
582
+
583
+    /**
584 584
      *	Return generic error code of last operation.
585 585
      *
586 586
      *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
587
-	 */
588
-	function errno()
589
-	{
590
-		if (! $this->connected)
591
-		{
592
-			// Si il y a eu echec de connexion, $this->db n'est pas valide.
593
-			return 'DB_ERROR_FAILED_TO_CONNECT';
594
-		}
595
-		else
596
-		{
597
-			// Constants to convert a MSSql error code to a generic Dolibarr error code
598
-			$errorcode_map = array(
599
-			1004 => 'DB_ERROR_CANNOT_CREATE',
600
-			1005 => 'DB_ERROR_CANNOT_CREATE',
601
-			1006 => 'DB_ERROR_CANNOT_CREATE',
602
-			1007 => 'DB_ERROR_ALREADY_EXISTS',
603
-			1008 => 'DB_ERROR_CANNOT_DROP',
604
-			1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
605
-			1046 => 'DB_ERROR_NODBSELECTED',
606
-			1048 => 'DB_ERROR_CONSTRAINT',
607
-			2714 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
608
-			1051 => 'DB_ERROR_NOSUCHTABLE',
609
-			1054 => 'DB_ERROR_NOSUCHFIELD',
610
-			1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
611
-			1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
612
-			2627 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
613
-			102  => 'DB_ERROR_SYNTAX',
614
-			8120 => 'DB_ERROR_GROUP_BY_SYNTAX',
615
-			1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
616
-			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
617
-			1091 => 'DB_ERROR_NOSUCHFIELD',
618
-			1100 => 'DB_ERROR_NOT_LOCKED',
619
-			1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
620
-			1146 => 'DB_ERROR_NOSUCHTABLE',
621
-			1216 => 'DB_ERROR_NO_PARENT',
622
-			1217 => 'DB_ERROR_CHILD_EXISTS',
623
-			1451 => 'DB_ERROR_CHILD_EXISTS',
624
-			1913 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
625
-			);
626
-
627
-			if (isset($errorcode_map[$this->lasterrno]))
628
-			{
629
-				return $errorcode_map[$this->lasterrno];
630
-			}
631
-			$errno=$this->lasterrno;
632
-			return ($errno?'DB_ERROR_'.$errno:'0');
633
-		}
634
-	}
635
-
636
-	/**
637
-	 *	Return description of last error
638
-	 *
639
-	 *	@return	string		Error text
640
-	 */
641
-	function error()
642
-	{
643
-		if (! $this->connected) {
644
-			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
645
-			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
646
-		}
647
-		else {
648
-			return mssql_get_last_message();
649
-		}
650
-	}
587
+     */
588
+    function errno()
589
+    {
590
+        if (! $this->connected)
591
+        {
592
+            // Si il y a eu echec de connexion, $this->db n'est pas valide.
593
+            return 'DB_ERROR_FAILED_TO_CONNECT';
594
+        }
595
+        else
596
+        {
597
+            // Constants to convert a MSSql error code to a generic Dolibarr error code
598
+            $errorcode_map = array(
599
+            1004 => 'DB_ERROR_CANNOT_CREATE',
600
+            1005 => 'DB_ERROR_CANNOT_CREATE',
601
+            1006 => 'DB_ERROR_CANNOT_CREATE',
602
+            1007 => 'DB_ERROR_ALREADY_EXISTS',
603
+            1008 => 'DB_ERROR_CANNOT_DROP',
604
+            1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
605
+            1046 => 'DB_ERROR_NODBSELECTED',
606
+            1048 => 'DB_ERROR_CONSTRAINT',
607
+            2714 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
608
+            1051 => 'DB_ERROR_NOSUCHTABLE',
609
+            1054 => 'DB_ERROR_NOSUCHFIELD',
610
+            1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
611
+            1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
612
+            2627 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
613
+            102  => 'DB_ERROR_SYNTAX',
614
+            8120 => 'DB_ERROR_GROUP_BY_SYNTAX',
615
+            1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
616
+            1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
617
+            1091 => 'DB_ERROR_NOSUCHFIELD',
618
+            1100 => 'DB_ERROR_NOT_LOCKED',
619
+            1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
620
+            1146 => 'DB_ERROR_NOSUCHTABLE',
621
+            1216 => 'DB_ERROR_NO_PARENT',
622
+            1217 => 'DB_ERROR_CHILD_EXISTS',
623
+            1451 => 'DB_ERROR_CHILD_EXISTS',
624
+            1913 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
625
+            );
626
+
627
+            if (isset($errorcode_map[$this->lasterrno]))
628
+            {
629
+                return $errorcode_map[$this->lasterrno];
630
+            }
631
+            $errno=$this->lasterrno;
632
+            return ($errno?'DB_ERROR_'.$errno:'0');
633
+        }
634
+    }
635
+
636
+    /**
637
+     *	Return description of last error
638
+     *
639
+     *	@return	string		Error text
640
+     */
641
+    function error()
642
+    {
643
+        if (! $this->connected) {
644
+            // Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
645
+            return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
646
+        }
647
+        else {
648
+            return mssql_get_last_message();
649
+        }
650
+    }
651 651
 
652 652
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
653
-	/**
654
-	 * Get last ID after an insert INSERT
655
-	 *
656
-	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
657
-	 * @param	string	$fieldid	Field name
658
-	 * @return  int     			Id of row or -1 on error
659
-	 */
660
-	function last_insert_id($tab,$fieldid='rowid')
661
-	{
653
+    /**
654
+     * Get last ID after an insert INSERT
655
+     *
656
+     * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
657
+     * @param	string	$fieldid	Field name
658
+     * @return  int     			Id of row or -1 on error
659
+     */
660
+    function last_insert_id($tab,$fieldid='rowid')
661
+    {
662 662
         // phpcs:enable
663
-		$res = $this->query("SELECT @@IDENTITY as id");
664
-		if ($res && $data = $this->fetch_array($res))
665
-		{
666
-			return $data["id"];
667
-		}
668
-		else
669
-		{
670
-			return -1;
671
-		}
672
-	}
673
-
674
-	/**
663
+        $res = $this->query("SELECT @@IDENTITY as id");
664
+        if ($res && $data = $this->fetch_array($res))
665
+        {
666
+            return $data["id"];
667
+        }
668
+        else
669
+        {
670
+            return -1;
671
+        }
672
+    }
673
+
674
+    /**
675 675
      *  Encrypt sensitive data in database
676 676
      *  Warning: This function includes the escape, so it must use direct value
677 677
      *
678 678
      *  @param  string  $fieldorvalue   Field name or value to encrypt
679 679
      *  @param	int		$withQuotes     Return string with quotes
680 680
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
681
-	 */
682
-	function encrypt($fieldorvalue, $withQuotes=0)
683
-	{
684
-		global $conf;
681
+     */
682
+    function encrypt($fieldorvalue, $withQuotes=0)
683
+    {
684
+        global $conf;
685 685
 
686
-		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
687
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
686
+        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
687
+        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
688 688
 
689
-		//Encryption key
690
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
689
+        //Encryption key
690
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
691 691
 
692
-		$return = $fieldorvalue;
693
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
694
-	}
692
+        $return = $fieldorvalue;
693
+        return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
694
+    }
695 695
 
696
-	/**
696
+    /**
697 697
      *	Decrypt sensitive data in database
698 698
      *
699 699
      *	@param	string	$value			Value to decrypt
700 700
      * 	@return	string					Decrypted value if used
701
-	 */
702
-	function decrypt($value)
703
-	{
704
-		global $conf;
701
+     */
702
+    function decrypt($value)
703
+    {
704
+        global $conf;
705 705
 
706
-		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
707
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
706
+        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
707
+        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
708 708
 
709
-		//Encryption key
710
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
709
+        //Encryption key
710
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
711 711
 
712
-		$return = $value;
713
-		return $return;
714
-	}
712
+        $return = $value;
713
+        return $return;
714
+    }
715 715
 
716 716
 
717 717
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
718
-	/**
719
-	 * Return connexion ID
720
-	 *
721
-	 * @return	        string      Id connexion
722
-	 */
723
-	function DDLGetConnectId()
724
-	{
718
+    /**
719
+     * Return connexion ID
720
+     *
721
+     * @return	        string      Id connexion
722
+     */
723
+    function DDLGetConnectId()
724
+    {
725 725
         // phpcs:enable
726
-		$resql=$this->query('SELECT CONNECTION_ID()');
727
-		if ($resql)
728
-		{
726
+        $resql=$this->query('SELECT CONNECTION_ID()');
727
+        if ($resql)
728
+        {
729 729
             $row=$this->fetch_row($resql);
730 730
             return $row[0];
731
-		}
732
-		else return '?';
733
-	}
731
+        }
732
+        else return '?';
733
+    }
734 734
 
735 735
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
736
-	/**
737
-	 *	Create a new database
738
-	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
739
-	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
740
-	 *
741
-	 *	@param	string	$database		Database name to create
742
-	 * 	@param	string	$charset		Charset used to store data
743
-	 * 	@param	string	$collation		Charset used to sort data
744
-	 * 	@param	string	$owner			Username of database owner
745
-	 * 	@return	false|resource|true		resource defined if OK, false if KO
746
-	 */
747
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
748
-	{
736
+    /**
737
+     *	Create a new database
738
+     *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
739
+     *	We force to create database with charset this->forcecharset and collate this->forcecollate
740
+     *
741
+     *	@param	string	$database		Database name to create
742
+     * 	@param	string	$charset		Charset used to store data
743
+     * 	@param	string	$collation		Charset used to sort data
744
+     * 	@param	string	$owner			Username of database owner
745
+     * 	@return	false|resource|true		resource defined if OK, false if KO
746
+     */
747
+    function DDLCreateDb($database,$charset='',$collation='',$owner='')
748
+    {
749 749
         // phpcs:enable
750 750
         /*if (empty($charset))   $charset=$this->forcecharset;
751 751
         if (empty($collation)) $collation=$this->forcecollate;
752 752
         */
753 753
 
754
-		$sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
754
+        $sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
755 755
         //TODO: Check if we need to force a charset
756
-		//$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
757
-		$ret=$this->query($sql);
756
+        //$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
757
+        $ret=$this->query($sql);
758 758
 
759
-		$this->select_db($database);
760
-		$sql="CREATE USER [$owner] FOR LOGIN [$owner]";
761
-		mssql_query($sql,$this->db);
762
-		$sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
763
-		mssql_query($sql,$this->db);
759
+        $this->select_db($database);
760
+        $sql="CREATE USER [$owner] FOR LOGIN [$owner]";
761
+        mssql_query($sql,$this->db);
762
+        $sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
763
+        mssql_query($sql,$this->db);
764 764
 
765
-		$sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
766
-	    @mssql_query($sql,$this->db);
767
-	    $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
768
-	    @mssql_query($sql,$this->db);
765
+        $sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
766
+        @mssql_query($sql,$this->db);
767
+        $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
768
+        @mssql_query($sql,$this->db);
769 769
 
770
-	    return $ret;
771
-	}
770
+        return $ret;
771
+    }
772 772
 
773 773
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
774
-	/**
775
-	 *  List tables into a database
776
-	 *
777
-	 *  @param	string		$database	Name of database
778
-	 *  @param	string		$table		Nmae of table filter ('xxx%')
774
+    /**
775
+     *  List tables into a database
776
+     *
777
+     *  @param	string		$database	Name of database
778
+     *  @param	string		$table		Nmae of table filter ('xxx%')
779 779
      *  @return	array					List of tables in an array
780
-	 */
781
-	function DDLListTables($database,$table='')
782
-	{
780
+     */
781
+    function DDLListTables($database,$table='')
782
+    {
783 783
         // phpcs:enable
784
-		$this->_results = mssql_list_tables($database, $this->db);
785
-		return $this->_results;
786
-	}
784
+        $this->_results = mssql_list_tables($database, $this->db);
785
+        return $this->_results;
786
+    }
787 787
 
788 788
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
789
-	/**
790
-	 *	List information of columns into a table.
791
-	 *
792
-	 *	@param	string	$table		Name of table
793
-	 *	@return	array				Tableau des informations des champs de la table
794
-	 */
795
-	function DDLInfoTable($table)
796
-	{
789
+    /**
790
+     *	List information of columns into a table.
791
+     *
792
+     *	@param	string	$table		Name of table
793
+     *	@return	array				Tableau des informations des champs de la table
794
+     */
795
+    function DDLInfoTable($table)
796
+    {
797 797
         // phpcs:enable
798 798
 
799
-		// FIXME: Dummy method
800
-		// TODO: Implement
801
-		// May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
799
+        // FIXME: Dummy method
800
+        // TODO: Implement
801
+        // May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
802 802
 
803
-		$infotables=array();
804
-		return $infotables;
805
-	}
803
+        $infotables=array();
804
+        return $infotables;
805
+    }
806 806
 
807 807
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
808
-	/**
809
-	 *	Create a table into database
810
-	 *
811
-	 *	@param	    string	$table 			Nom de la table
812
-	 *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
813
-	 *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
814
-	 *	@param	    string	$type 			Type de la table
815
-	 *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
816
-	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
817
-	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
818
-	 *	@return	    int						<0 if KO, >=0 if OK
819
-	 */
820
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
821
-	{
808
+    /**
809
+     *	Create a table into database
810
+     *
811
+     *	@param	    string	$table 			Nom de la table
812
+     *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
813
+     *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
814
+     *	@param	    string	$type 			Type de la table
815
+     *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
816
+     *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
817
+     *	@param	    array	$keys 			Tableau des champs cles noms => valeur
818
+     *	@return	    int						<0 if KO, >=0 if OK
819
+     */
820
+    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
821
+    {
822 822
         // phpcs:enable
823
-		// FIXME: $fulltext_keys parameter is unused
824
-
825
-		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
826
-		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
827
-		$sql = "create table ".$table."(";
828
-		$i=0;
829
-		foreach($fields as $field_name => $field_desc)
830
-		{
831
-			$sqlfields[$i] = $field_name." ";
832
-			$sqlfields[$i]  .= $field_desc['type'];
833
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
834
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
835
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
836
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
837
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
838
-			{
839
-				if(preg_match("/null/i",$field_desc['default']))
840
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
841
-				else
842
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
843
-			}
844
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
845
-			$sqlfields[$i]  .= " ".$field_desc['null'];
846
-
847
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
848
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
849
-			$i++;
850
-		}
851
-		if($primary_key != "")
852
-		$pk = "primary key(".$primary_key.")";
853
-
854
-		if(is_array($unique_keys))
855
-		{
856
-			$i = 0;
857
-			foreach($unique_keys as $key => $value)
858
-			{
859
-				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
860
-				$i++;
861
-			}
862
-		}
863
-		if(is_array($keys))
864
-		{
865
-			$i = 0;
866
-			foreach($keys as $key => $value)
867
-			{
868
-				$sqlk[$i] = "KEY ".$key." (".$value.")";
869
-				$i++;
870
-			}
871
-		}
872
-		$sql .= implode(',',$sqlfields);
873
-		if($primary_key != "")
874
-		$sql .= ",".$pk;
875
-		if(is_array($unique_keys))
876
-		$sql .= ",".implode(',',$sqluq);
877
-		if(is_array($keys))
878
-		$sql .= ",".implode(',',$sqlk);
879
-		$sql .=") type=".$type;
880
-
881
-		dol_syslog($sql);
882
-		if(! $this -> query($sql))
883
-		return -1;
884
-		else
885
-		return 1;
886
-	}
823
+        // FIXME: $fulltext_keys parameter is unused
824
+
825
+        // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
826
+        // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
827
+        $sql = "create table ".$table."(";
828
+        $i=0;
829
+        foreach($fields as $field_name => $field_desc)
830
+        {
831
+            $sqlfields[$i] = $field_name." ";
832
+            $sqlfields[$i]  .= $field_desc['type'];
833
+            if( preg_match("/^[^\s]/i",$field_desc['value']))
834
+            $sqlfields[$i]  .= "(".$field_desc['value'].")";
835
+            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
836
+            $sqlfields[$i]  .= " ".$field_desc['attribute'];
837
+            else if( preg_match("/^[^\s]/i",$field_desc['default']))
838
+            {
839
+                if(preg_match("/null/i",$field_desc['default']))
840
+                $sqlfields[$i]  .= " default ".$field_desc['default'];
841
+                else
842
+                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
843
+            }
844
+            else if( preg_match("/^[^\s]/i",$field_desc['null']))
845
+            $sqlfields[$i]  .= " ".$field_desc['null'];
846
+
847
+            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
848
+            $sqlfields[$i]  .= " ".$field_desc['extra'];
849
+            $i++;
850
+        }
851
+        if($primary_key != "")
852
+        $pk = "primary key(".$primary_key.")";
853
+
854
+        if(is_array($unique_keys))
855
+        {
856
+            $i = 0;
857
+            foreach($unique_keys as $key => $value)
858
+            {
859
+                $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
860
+                $i++;
861
+            }
862
+        }
863
+        if(is_array($keys))
864
+        {
865
+            $i = 0;
866
+            foreach($keys as $key => $value)
867
+            {
868
+                $sqlk[$i] = "KEY ".$key." (".$value.")";
869
+                $i++;
870
+            }
871
+        }
872
+        $sql .= implode(',',$sqlfields);
873
+        if($primary_key != "")
874
+        $sql .= ",".$pk;
875
+        if(is_array($unique_keys))
876
+        $sql .= ",".implode(',',$sqluq);
877
+        if(is_array($keys))
878
+        $sql .= ",".implode(',',$sqlk);
879
+        $sql .=") type=".$type;
880
+
881
+        dol_syslog($sql);
882
+        if(! $this -> query($sql))
883
+        return -1;
884
+        else
885
+        return 1;
886
+    }
887 887
 
888 888
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
889
-	/**
890
-	 *	Drop a table into database
891
-	 *
892
-	 *	@param	    string	$table 			Name of table
893
-	 *	@return	    int						<0 if KO, >=0 if OK
894
-	 */
895
-	function DDLDropTable($table)
896
-	{
889
+    /**
890
+     *	Drop a table into database
891
+     *
892
+     *	@param	    string	$table 			Name of table
893
+     *	@return	    int						<0 if KO, >=0 if OK
894
+     */
895
+    function DDLDropTable($table)
896
+    {
897 897
         // phpcs:enable
898
-		$sql = "DROP TABLE ".$table;
898
+        $sql = "DROP TABLE ".$table;
899 899
 
900
-		if (! $this->query($sql))
901
-			return -1;
902
-		else
903
-			return 1;
904
-	}
900
+        if (! $this->query($sql))
901
+            return -1;
902
+        else
903
+            return 1;
904
+    }
905 905
 
906 906
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
907
-	/**
908
-	 *	Return a pointer of line with description of a table or field
909
-	 *
910
-	 *	@param	string		$table	Name of table
911
-	 *	@param	string		$field	Optionnel : Name of field if we want description of field
912
-	 *	@return	false|resource|true	Resource
913
-	 */
914
-	function DDLDescTable($table,$field="")
915
-	{
907
+    /**
908
+     *	Return a pointer of line with description of a table or field
909
+     *
910
+     *	@param	string		$table	Name of table
911
+     *	@param	string		$field	Optionnel : Name of field if we want description of field
912
+     *	@return	false|resource|true	Resource
913
+     */
914
+    function DDLDescTable($table,$field="")
915
+    {
916 916
         // phpcs:enable
917
-		$sql="DESC ".$table." ".$field;
917
+        $sql="DESC ".$table." ".$field;
918 918
 
919
-		dol_syslog($sql);
920
-		$this->_results = $this->query($sql);
921
-		return $this->_results;
922
-	}
919
+        dol_syslog($sql);
920
+        $this->_results = $this->query($sql);
921
+        return $this->_results;
922
+    }
923 923
 
924 924
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
925
-	/**
926
-	 *	Create a new field into table
927
-	 *
928
-	 *	@param	string	$table 				Name of table
929
-	 *	@param	string	$field_name 		Name of field to add
930
-	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
931
-	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
932
-	 *	@return	int							<0 if KO, >0 if OK
933
-	 */
934
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
935
-	{
925
+    /**
926
+     *	Create a new field into table
927
+     *
928
+     *	@param	string	$table 				Name of table
929
+     *	@param	string	$field_name 		Name of field to add
930
+     *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
931
+     *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
932
+     *	@return	int							<0 if KO, >0 if OK
933
+     */
934
+    function DDLAddField($table,$field_name,$field_desc,$field_position="")
935
+    {
936 936
         // phpcs:enable
937
-		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
938
-		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
939
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
940
-		$sql .= $field_desc['type'];
941
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
942
-		$sql  .= "(".$field_desc['value'].")";
943
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
944
-		$sql  .= " ".$field_desc['attribute'];
945
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
946
-		$sql  .= " ".$field_desc['null'];
947
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
948
-		if(preg_match("/null/i",$field_desc['default']))
949
-		$sql  .= " default ".$field_desc['default'];
950
-		else
951
-		$sql  .= " default '".$field_desc['default']."'";
952
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
953
-		$sql  .= " ".$field_desc['extra'];
954
-		$sql .= " ".$field_position;
955
-
956
-		if(! $this -> query($sql))
957
-		return -1;
958
-		else
959
-		return 1;
960
-	}
937
+        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
938
+        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
939
+        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
940
+        $sql .= $field_desc['type'];
941
+        if( preg_match("/^[^\s]/i",$field_desc['value']))
942
+        $sql  .= "(".$field_desc['value'].")";
943
+        if( preg_match("/^[^\s]/i",$field_desc['attribute']))
944
+        $sql  .= " ".$field_desc['attribute'];
945
+        if( preg_match("/^[^\s]/i",$field_desc['null']))
946
+        $sql  .= " ".$field_desc['null'];
947
+        if( preg_match("/^[^\s]/i",$field_desc['default']))
948
+        if(preg_match("/null/i",$field_desc['default']))
949
+        $sql  .= " default ".$field_desc['default'];
950
+        else
951
+        $sql  .= " default '".$field_desc['default']."'";
952
+        if( preg_match("/^[^\s]/i",$field_desc['extra']))
953
+        $sql  .= " ".$field_desc['extra'];
954
+        $sql .= " ".$field_position;
955
+
956
+        if(! $this -> query($sql))
957
+        return -1;
958
+        else
959
+        return 1;
960
+    }
961 961
 
962 962
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
963
-	/**
964
-	 *	Update format of a field into a table
965
-	 *
966
-	 *	@param	string	$table 				Name of table
967
-	 *	@param	string	$field_name 		Name of field to modify
968
-	 *	@param	string	$field_desc 		Array with description of field format
969
-	 *	@return	int							<0 if KO, >0 if OK
970
-	 */
971
-	function DDLUpdateField($table,$field_name,$field_desc)
972
-	{
963
+    /**
964
+     *	Update format of a field into a table
965
+     *
966
+     *	@param	string	$table 				Name of table
967
+     *	@param	string	$field_name 		Name of field to modify
968
+     *	@param	string	$field_desc 		Array with description of field format
969
+     *	@return	int							<0 if KO, >0 if OK
970
+     */
971
+    function DDLUpdateField($table,$field_name,$field_desc)
972
+    {
973 973
         // phpcs:enable
974
-		$sql = "ALTER TABLE ".$table;
975
-		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
976
-		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
977
-			$sql.="(".$field_desc['value'].")";
978
-		}
979
-
980
-		dol_syslog($sql,LOG_DEBUG);
981
-		if (! $this->query($sql))
982
-		return -1;
983
-		else
984
-		return 1;
985
-	}
974
+        $sql = "ALTER TABLE ".$table;
975
+        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
976
+        if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
977
+            $sql.="(".$field_desc['value'].")";
978
+        }
979
+
980
+        dol_syslog($sql,LOG_DEBUG);
981
+        if (! $this->query($sql))
982
+        return -1;
983
+        else
984
+        return 1;
985
+    }
986 986
 
987 987
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
988
-	/**
989
-	 *	Drop a field from table
990
-	 *
991
-	 *	@param	string	$table 			Name of table
992
-	 *	@param	string	$field_name 	Name of field to drop
993
-	 *	@return	int						<0 if KO, >0 if OK
994
-	 */
995
-	function DDLDropField($table,$field_name)
996
-	{
988
+    /**
989
+     *	Drop a field from table
990
+     *
991
+     *	@param	string	$table 			Name of table
992
+     *	@param	string	$field_name 	Name of field to drop
993
+     *	@return	int						<0 if KO, >0 if OK
994
+     */
995
+    function DDLDropField($table,$field_name)
996
+    {
997 997
         // phpcs:enable
998
-		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
999
-		dol_syslog($sql,LOG_DEBUG);
1000
-		if (! $this->query($sql))
1001
-		{
1002
-			$this->error=$this->lasterror();
1003
-			return -1;
1004
-		}
1005
-		else return 1;
1006
-	}
998
+        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
999
+        dol_syslog($sql,LOG_DEBUG);
1000
+        if (! $this->query($sql))
1001
+        {
1002
+            $this->error=$this->lasterror();
1003
+            return -1;
1004
+        }
1005
+        else return 1;
1006
+    }
1007 1007
 
1008 1008
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1009
-	/**
1010
-	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
1011
-	 *
1012
-	 *	@param	string	$dolibarr_main_db_host 		Ip serveur
1013
-	 *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1014
-	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1015
-	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1016
-	 *	@return	int									<0 if KO, >=0 if OK
1017
-	 */
1018
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1019
-	{
1009
+    /**
1010
+     * 	Create a user and privileges to connect to database (even if database does not exists yet)
1011
+     *
1012
+     *	@param	string	$dolibarr_main_db_host 		Ip serveur
1013
+     *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1014
+     *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1015
+     *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1016
+     *	@return	int									<0 if KO, >=0 if OK
1017
+     */
1018
+    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1019
+    {
1020 1020
         // phpcs:enable
1021 1021
         $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
1022 1022
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
@@ -1025,12 +1025,12 @@  discard block
 block discarded – undo
1025 1025
         {
1026 1026
             if ($this->lasterrno != '15025')
1027 1027
             {
1028
-	            return -1;
1028
+                return -1;
1029 1029
             }
1030 1030
             else
1031
-			{
1032
-            	// If user already exists, we continue to set permissions
1033
-            	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1031
+            {
1032
+                // If user already exists, we continue to set permissions
1033
+                dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1034 1034
             }
1035 1035
         }
1036 1036
         $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
                 $this->query($sql);
1052 1052
             }
1053 1053
         }
1054
-	    return 1;
1055
-	}
1054
+        return 1;
1055
+    }
1056 1056
 
1057 1057
     /**
1058 1058
      *	Return charset used to store data in database
@@ -1060,158 +1060,158 @@  discard block
 block discarded – undo
1060 1060
      *	@return		string		Charset
1061 1061
      */
1062 1062
     function getDefaultCharacterSetDatabase()
1063
-	{
1064
-		// FIXME: Dummy method
1065
-		// TODO: Implement
1066
-
1067
-		return '';
1068
-	}
1069
-
1070
-	/**
1071
-	 *	Return list of available charset that can be used to store data in database
1072
-	 *
1073
-	 *	@return		array		List of Charset
1074
-	 */
1075
-	function getListOfCharacterSet()
1076
-	{
1077
-		// FIXME: Dummy method
1078
-		// TODO: Implement
1079
-
1080
-		return '';
1081
-	}
1082
-
1083
-	/**
1084
-	 *	Return collation used in database
1085
-	 *
1086
-	 *	@return		string		Collation value
1087
-	 */
1088
-	function getDefaultCollationDatabase()
1089
-	{
1090
-		$resql=$this->query("SELECT SERVERPROPERTY('collation')");
1091
-		if (!$resql)
1092
-		{
1093
-			return $this->forcecollate;
1094
-		}
1095
-		$liste=$this->fetch_array($resql);
1096
-		return $liste['computed'];
1097
-	}
1098
-
1099
-	/**
1100
-	 *	Return list of available collation that can be used for database
1101
-	 *
1102
-	 *	@return		array		Liste of Collation
1103
-	 */
1104
-	function getListOfCollation()
1105
-	{
1106
-		// FIXME: Dummy method
1107
-		// TODO: Implement
1108
-
1109
-		return array();
1110
-	}
1111
-
1112
-	/**
1113
-	 *	Return full path of dump program
1114
-	 *
1115
-	 *	@return		string		Full path of dump program
1116
-	 */
1117
-	function getPathOfDump()
1118
-	{
1119
-		// FIXME: Dummy method
1120
-		// TODO: Implement
1121
-
1122
-	    return '';
1123
-	}
1124
-
1125
-	/**
1126
-	 *	Return full path of restore program
1127
-	 *
1128
-	 *	@return		string		Full path of restore program
1129
-	 */
1130
-	function getPathOfRestore()
1131
-	{
1132
-		// FIXME: Dummy method
1133
-		// TODO: Implement
1134
-
1135
-	    return '';
1136
-	}
1137
-
1138
-	/**
1139
-	 * Return value of server parameters
1140
-	 *
1141
-	 * @param	string	$filter		Filter list on a particular value
1142
-	 * @return	array				Array of key-values (key=>value)
1143
-	 */
1144
-	function getServerParametersValues($filter='')
1145
-	{
1146
-		// FIXME: Dummy method
1147
-		// TODO: Implement
1148
-		// May help: SELECT SERVERPROPERTY
1149
-
1150
-		$result=array();
1151
-		return $result;
1152
-	}
1153
-
1154
-	/**
1155
-	 * Return value of server status
1156
-	 *
1157
-	 * @param	string	$filter		Filter list on a particular value
1158
-	 * @return  array				Array of key-values (key=>value)
1159
-	 */
1160
-	function getServerStatusValues($filter='')
1161
-	{
1162
-		// FIXME: Dummy method
1163
-		// TODO: Implement
1164
-		// May help: http://www.experts-exchange.com/Database/MS-SQL-Server/Q_20971756.html
1165
-
1166
-		return array();
1167
-	}
1063
+    {
1064
+        // FIXME: Dummy method
1065
+        // TODO: Implement
1066
+
1067
+        return '';
1068
+    }
1069
+
1070
+    /**
1071
+     *	Return list of available charset that can be used to store data in database
1072
+     *
1073
+     *	@return		array		List of Charset
1074
+     */
1075
+    function getListOfCharacterSet()
1076
+    {
1077
+        // FIXME: Dummy method
1078
+        // TODO: Implement
1079
+
1080
+        return '';
1081
+    }
1082
+
1083
+    /**
1084
+     *	Return collation used in database
1085
+     *
1086
+     *	@return		string		Collation value
1087
+     */
1088
+    function getDefaultCollationDatabase()
1089
+    {
1090
+        $resql=$this->query("SELECT SERVERPROPERTY('collation')");
1091
+        if (!$resql)
1092
+        {
1093
+            return $this->forcecollate;
1094
+        }
1095
+        $liste=$this->fetch_array($resql);
1096
+        return $liste['computed'];
1097
+    }
1098
+
1099
+    /**
1100
+     *	Return list of available collation that can be used for database
1101
+     *
1102
+     *	@return		array		Liste of Collation
1103
+     */
1104
+    function getListOfCollation()
1105
+    {
1106
+        // FIXME: Dummy method
1107
+        // TODO: Implement
1108
+
1109
+        return array();
1110
+    }
1111
+
1112
+    /**
1113
+     *	Return full path of dump program
1114
+     *
1115
+     *	@return		string		Full path of dump program
1116
+     */
1117
+    function getPathOfDump()
1118
+    {
1119
+        // FIXME: Dummy method
1120
+        // TODO: Implement
1121
+
1122
+        return '';
1123
+    }
1124
+
1125
+    /**
1126
+     *	Return full path of restore program
1127
+     *
1128
+     *	@return		string		Full path of restore program
1129
+     */
1130
+    function getPathOfRestore()
1131
+    {
1132
+        // FIXME: Dummy method
1133
+        // TODO: Implement
1134
+
1135
+        return '';
1136
+    }
1137
+
1138
+    /**
1139
+     * Return value of server parameters
1140
+     *
1141
+     * @param	string	$filter		Filter list on a particular value
1142
+     * @return	array				Array of key-values (key=>value)
1143
+     */
1144
+    function getServerParametersValues($filter='')
1145
+    {
1146
+        // FIXME: Dummy method
1147
+        // TODO: Implement
1148
+        // May help: SELECT SERVERPROPERTY
1149
+
1150
+        $result=array();
1151
+        return $result;
1152
+    }
1153
+
1154
+    /**
1155
+     * Return value of server status
1156
+     *
1157
+     * @param	string	$filter		Filter list on a particular value
1158
+     * @return  array				Array of key-values (key=>value)
1159
+     */
1160
+    function getServerStatusValues($filter='')
1161
+    {
1162
+        // FIXME: Dummy method
1163
+        // TODO: Implement
1164
+        // May help: http://www.experts-exchange.com/Database/MS-SQL-Server/Q_20971756.html
1165
+
1166
+        return array();
1167
+    }
1168 1168
 
1169 1169
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1170
-	/**
1171
-	 *    Escape a field name according to escape's syntax
1172
-	 *
1173
-	 * @param      string $fieldname   Field's name to escape
1174
-	 * @return     string              field's name escaped
1175
-	 */
1170
+    /**
1171
+     *    Escape a field name according to escape's syntax
1172
+     *
1173
+     * @param      string $fieldname   Field's name to escape
1174
+     * @return     string              field's name escaped
1175
+     */
1176 1176
     function EscapeFieldName($fieldname)
1177 1177
     {
1178 1178
         // phpcs:enable
1179
-	    return "[".$fieldname."]";
1180
-	}
1179
+        return "[".$fieldname."]";
1180
+    }
1181 1181
 
1182 1182
 
1183 1183
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1184
-	/**
1185
-	 * Get information on field
1186
-	 *
1187
-	 * @param      string  $table      Table name which contains fields
1188
-	 * @param      mixed   $fields     String for one field or array of string for multiple field
1189
-	 * @return false|object
1190
-	 */
1184
+    /**
1185
+     * Get information on field
1186
+     *
1187
+     * @param      string  $table      Table name which contains fields
1188
+     * @param      mixed   $fields     String for one field or array of string for multiple field
1189
+     * @return false|object
1190
+     */
1191 1191
     function GetFieldInformation($table,$fields)
1192 1192
     {
1193 1193
         // phpcs:enable
1194
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1195
-	    if (is_array($fields))
1196
-	    {
1197
-	        $where=" IN ('".implode("','",$fields)."')";
1198
-	    }
1199
-	    else
1200
-	    {
1201
-	        $where="='".$this->escape($fields)."'";
1202
-	    }
1203
-	    $result=array();
1204
-	    $ret=mssql_query($sql.$where,$this->db);
1205
-	    if ($ret)
1206
-	    {
1207
-	        while($obj=mssql_fetch_object($ret))
1208
-	        {
1209
-	            $result[]=$obj;
1210
-	        }
1211
-	    }
1212
-	    else
1213
-	        return false;
1214
-
1215
-	    return $result;
1216
-	}
1194
+        $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1195
+        if (is_array($fields))
1196
+        {
1197
+            $where=" IN ('".implode("','",$fields)."')";
1198
+        }
1199
+        else
1200
+        {
1201
+            $where="='".$this->escape($fields)."'";
1202
+        }
1203
+        $result=array();
1204
+        $ret=mssql_query($sql.$where,$this->db);
1205
+        if ($ret)
1206
+        {
1207
+            while($obj=mssql_fetch_object($ret))
1208
+            {
1209
+                $result[]=$obj;
1210
+            }
1211
+        }
1212
+        else
1213
+            return false;
1214
+
1215
+        return $result;
1216
+    }
1217 1217
 }
Please login to merge, or discard this patch.
Braces   +107 added lines, -93 removed lines patch added patch discarded remove patch
@@ -90,8 +90,7 @@  discard block
 block discarded – undo
90 90
 			// (La base Dolibarr a ete forcee en this->forcecharset a l'install)
91 91
 			$this->connected = true;
92 92
 			$this->ok = true;
93
-		}
94
-		else
93
+		} else
95 94
 		{
96 95
 			// host, login ou password incorrect
97 96
 			$this->connected = false;
@@ -108,8 +107,7 @@  discard block
 block discarded – undo
108 107
 				$this->database_selected = true;
109 108
 				$this->database_name = $name;
110 109
 				$this->ok = true;
111
-			}
112
-			else
110
+			} else
113 111
 			{
114 112
 				$this->database_selected = false;
115 113
 				$this->database_name = '';
@@ -117,8 +115,7 @@  discard block
 block discarded – undo
117 115
 				$this->error=$this->error();
118 116
 				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
119 117
 			}
120
-		}
121
-		else
118
+		} else
122 119
 		{
123 120
 			// Pas de selection de base demandee, ok ou ko
124 121
 			$this->database_selected = false;
@@ -167,7 +164,9 @@  discard block
 block discarded – undo
167 164
 	{
168 165
 		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
169 166
 		$newhost=$host;
170
-		if ($port) $newhost.=':'.$port;
167
+		if ($port) {
168
+		    $newhost.=':'.$port;
169
+		}
171 170
 		$this->db  = @mssql_connect($newhost, $login, $passwd);
172 171
 		//force les enregistrement en latin1 si la base est en utf8 par defaut
173 172
 		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
@@ -198,8 +197,9 @@  discard block
 block discarded – undo
198 197
 		{
199 198
             $version=$this->fetch_array($resql);
200 199
             return $version['computed'];
200
+		} else {
201
+		    return '';
201 202
 		}
202
-		else return '';
203 203
 	}
204 204
 
205 205
 	/**
@@ -222,7 +222,9 @@  discard block
 block discarded – undo
222 222
     {
223 223
         if ($this->db)
224 224
         {
225
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
225
+          if ($this->transaction_opened > 0) {
226
+              dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
227
+          }
226 228
           $this->connected=false;
227 229
           return mssql_close($this->db);
228 230
         }
@@ -250,8 +252,7 @@  discard block
 block discarded – undo
250 252
 				dol_syslog("BEGIN Transaction",LOG_DEBUG);
251 253
 			}
252 254
 			return $ret;
253
-		}
254
-		else
255
+		} else
255 256
 		{
256 257
 			return true;
257 258
 		}
@@ -276,13 +277,11 @@  discard block
 block discarded – undo
276 277
 			{
277 278
 				dol_syslog("COMMIT Transaction",LOG_DEBUG);
278 279
 				return true;
279
-			}
280
-			else
280
+			} else
281 281
 			{
282 282
 				return false;
283 283
 			}
284
-		}
285
-		elseif ($this->transaction_opened > 1)
284
+		} elseif ($this->transaction_opened > 1)
286 285
 		{
287 286
 			return true;
288 287
 		}
@@ -306,8 +305,7 @@  discard block
 block discarded – undo
306 305
 			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
307 306
 			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
308 307
 			return $ret;
309
-		}
310
-		elseif ($this->transaction_opened > 1)
308
+		} elseif ($this->transaction_opened > 1)
311 309
 		{
312 310
 			return true;
313 311
 		}
@@ -328,7 +326,9 @@  discard block
 block discarded – undo
328 326
 	{
329 327
 		$query = trim($query);
330 328
 
331
-		if (preg_match('/^--/',$query)) return true;
329
+		if (preg_match('/^--/',$query)) {
330
+		    return true;
331
+		}
332 332
 
333 333
 		// Conversion syntaxe MySql vers MSDE.
334 334
 		$query = str_ireplace("now()", "getdate()", $query);
@@ -362,11 +362,11 @@  discard block
 block discarded – undo
362 362
                             $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
363 363
                         }
364 364
                     }
365
-                    if (! empty($query_comp))
366
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
365
+                    if (! empty($query_comp)) {
366
+                                            $query.=" WHERE ".implode(" AND ",$query_comp);
367
+                    }
367 368
                 }
368
-    		}
369
-    		else
369
+    		} else
370 370
     		{
371 371
     		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
372 372
     		    {
@@ -419,14 +419,15 @@  discard block
 block discarded – undo
419 419
 		}
420 420
 		//print "<!--".$query."-->";
421 421
 
422
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
422
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
423
+		    dol_syslog('sql='.$query, LOG_DEBUG);
424
+		}
423 425
 
424 426
 		if (! $this->database_name)
425 427
 		{
426 428
 			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
427 429
 			$ret = mssql_query($query, $this->db);
428
-		}
429
-		else
430
+		} else
430 431
 		{
431 432
 			$ret = mssql_query($query, $this->db);
432 433
 		}
@@ -449,7 +450,9 @@  discard block
 block discarded – undo
449 450
 				$this->lasterrno = $row["code"];
450 451
 
451 452
 				dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
452
-				if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
453
+				if ($original_query) {
454
+				    dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
455
+				}
453 456
 				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
454 457
 			}
455 458
 			$this->lastquery=$query;
@@ -553,7 +556,9 @@  discard block
 block discarded – undo
553 556
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
554 557
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
555 558
 		// Si resultset en est un, on libere la memoire
556
-		if (is_resource($resultset)) mssql_free_result($resultset);
559
+		if (is_resource($resultset)) {
560
+		    mssql_free_result($resultset);
561
+		}
557 562
 	}
558 563
 
559 564
 	/**
@@ -591,8 +596,7 @@  discard block
 block discarded – undo
591 596
 		{
592 597
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
593 598
 			return 'DB_ERROR_FAILED_TO_CONNECT';
594
-		}
595
-		else
599
+		} else
596 600
 		{
597 601
 			// Constants to convert a MSSql error code to a generic Dolibarr error code
598 602
 			$errorcode_map = array(
@@ -643,8 +647,7 @@  discard block
 block discarded – undo
643 647
 		if (! $this->connected) {
644 648
 			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
645 649
 			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
646
-		}
647
-		else {
650
+		} else {
648 651
 			return mssql_get_last_message();
649 652
 		}
650 653
 	}
@@ -664,8 +667,7 @@  discard block
 block discarded – undo
664 667
 		if ($res && $data = $this->fetch_array($res))
665 668
 		{
666 669
 			return $data["id"];
667
-		}
668
-		else
670
+		} else
669 671
 		{
670 672
 			return -1;
671 673
 		}
@@ -728,8 +730,9 @@  discard block
 block discarded – undo
728 730
 		{
729 731
             $row=$this->fetch_row($resql);
730 732
             return $row[0];
733
+		} else {
734
+		    return '?';
731 735
 		}
732
-		else return '?';
733 736
 	}
734 737
 
735 738
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -830,26 +833,27 @@  discard block
 block discarded – undo
830 833
 		{
831 834
 			$sqlfields[$i] = $field_name." ";
832 835
 			$sqlfields[$i]  .= $field_desc['type'];
833
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
834
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
835
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
836
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
837
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
836
+			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
837
+						$sqlfields[$i]  .= "(".$field_desc['value'].")";
838
+			} else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
839
+						$sqlfields[$i]  .= " ".$field_desc['attribute'];
840
+			} else if( preg_match("/^[^\s]/i",$field_desc['default']))
838 841
 			{
839
-				if(preg_match("/null/i",$field_desc['default']))
840
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
841
-				else
842
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
842
+				if(preg_match("/null/i",$field_desc['default'])) {
843
+								$sqlfields[$i]  .= " default ".$field_desc['default'];
844
+				} else {
845
+								$sqlfields[$i]  .= " default '".$field_desc['default']."'";
846
+				}
847
+			} else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
848
+						$sqlfields[$i]  .= " ".$field_desc['null'];
849
+			} else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
850
+						$sqlfields[$i]  .= " ".$field_desc['extra'];
843 851
 			}
844
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
845
-			$sqlfields[$i]  .= " ".$field_desc['null'];
846
-
847
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
848
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
849 852
 			$i++;
850 853
 		}
851
-		if($primary_key != "")
852
-		$pk = "primary key(".$primary_key.")";
854
+		if($primary_key != "") {
855
+				$pk = "primary key(".$primary_key.")";
856
+		}
853 857
 
854 858
 		if(is_array($unique_keys))
855 859
 		{
@@ -870,19 +874,23 @@  discard block
 block discarded – undo
870 874
 			}
871 875
 		}
872 876
 		$sql .= implode(',',$sqlfields);
873
-		if($primary_key != "")
874
-		$sql .= ",".$pk;
875
-		if(is_array($unique_keys))
876
-		$sql .= ",".implode(',',$sqluq);
877
-		if(is_array($keys))
878
-		$sql .= ",".implode(',',$sqlk);
877
+		if($primary_key != "") {
878
+				$sql .= ",".$pk;
879
+		}
880
+		if(is_array($unique_keys)) {
881
+				$sql .= ",".implode(',',$sqluq);
882
+		}
883
+		if(is_array($keys)) {
884
+				$sql .= ",".implode(',',$sqlk);
885
+		}
879 886
 		$sql .=") type=".$type;
880 887
 
881 888
 		dol_syslog($sql);
882
-		if(! $this -> query($sql))
883
-		return -1;
884
-		else
885
-		return 1;
889
+		if(! $this -> query($sql)) {
890
+				return -1;
891
+		} else {
892
+				return 1;
893
+		}
886 894
 	}
887 895
 
888 896
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -897,10 +905,11 @@  discard block
 block discarded – undo
897 905
         // phpcs:enable
898 906
 		$sql = "DROP TABLE ".$table;
899 907
 
900
-		if (! $this->query($sql))
901
-			return -1;
902
-		else
903
-			return 1;
908
+		if (! $this->query($sql)) {
909
+					return -1;
910
+		} else {
911
+					return 1;
912
+		}
904 913
 	}
905 914
 
906 915
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -938,25 +947,31 @@  discard block
 block discarded – undo
938 947
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
939 948
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
940 949
 		$sql .= $field_desc['type'];
941
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
942
-		$sql  .= "(".$field_desc['value'].")";
943
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
944
-		$sql  .= " ".$field_desc['attribute'];
945
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
946
-		$sql  .= " ".$field_desc['null'];
947
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
948
-		if(preg_match("/null/i",$field_desc['default']))
950
+		if( preg_match("/^[^\s]/i",$field_desc['value'])) {
951
+				$sql  .= "(".$field_desc['value'].")";
952
+		}
953
+		if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
954
+				$sql  .= " ".$field_desc['attribute'];
955
+		}
956
+		if( preg_match("/^[^\s]/i",$field_desc['null'])) {
957
+				$sql  .= " ".$field_desc['null'];
958
+		}
959
+		if( preg_match("/^[^\s]/i",$field_desc['default'])) {
960
+				if(preg_match("/null/i",$field_desc['default']))
949 961
 		$sql  .= " default ".$field_desc['default'];
950
-		else
951
-		$sql  .= " default '".$field_desc['default']."'";
952
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
953
-		$sql  .= " ".$field_desc['extra'];
962
+		} else {
963
+				$sql  .= " default '".$field_desc['default']."'";
964
+		}
965
+		if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
966
+				$sql  .= " ".$field_desc['extra'];
967
+		}
954 968
 		$sql .= " ".$field_position;
955 969
 
956
-		if(! $this -> query($sql))
957
-		return -1;
958
-		else
959
-		return 1;
970
+		if(! $this -> query($sql)) {
971
+				return -1;
972
+		} else {
973
+				return 1;
974
+		}
960 975
 	}
961 976
 
962 977
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -978,10 +993,11 @@  discard block
 block discarded – undo
978 993
 		}
979 994
 
980 995
 		dol_syslog($sql,LOG_DEBUG);
981
-		if (! $this->query($sql))
982
-		return -1;
983
-		else
984
-		return 1;
996
+		if (! $this->query($sql)) {
997
+				return -1;
998
+		} else {
999
+				return 1;
1000
+		}
985 1001
 	}
986 1002
 
987 1003
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1001,8 +1017,9 @@  discard block
 block discarded – undo
1001 1017
 		{
1002 1018
 			$this->error=$this->lasterror();
1003 1019
 			return -1;
1020
+		} else {
1021
+		    return 1;
1004 1022
 		}
1005
-		else return 1;
1006 1023
 	}
1007 1024
 
1008 1025
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1026,8 +1043,7 @@  discard block
 block discarded – undo
1026 1043
             if ($this->lasterrno != '15025')
1027 1044
             {
1028 1045
 	            return -1;
1029
-            }
1030
-            else
1046
+            } else
1031 1047
 			{
1032 1048
             	// If user already exists, we continue to set permissions
1033 1049
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -1039,8 +1055,7 @@  discard block
 block discarded – undo
1039 1055
         {
1040 1056
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1041 1057
             return -1;
1042
-        }
1043
-        else
1058
+        } else
1044 1059
         {
1045 1060
             if ($num)
1046 1061
             {
@@ -1195,8 +1210,7 @@  discard block
 block discarded – undo
1195 1210
 	    if (is_array($fields))
1196 1211
 	    {
1197 1212
 	        $where=" IN ('".implode("','",$fields)."')";
1198
-	    }
1199
-	    else
1213
+	    } else
1200 1214
 	    {
1201 1215
 	        $where="='".$this->escape($fields)."'";
1202 1216
 	    }
@@ -1208,9 +1222,9 @@  discard block
 block discarded – undo
1208 1222
 	        {
1209 1223
 	            $result[]=$obj;
1210 1224
 	        }
1225
+	    } else {
1226
+	    	        return false;
1211 1227
 	    }
1212
-	    else
1213
-	        return false;
1214 1228
 
1215 1229
 	    return $result;
1216 1230
 	}
Please login to merge, or discard this patch.
Spacing   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
  */
30 30
 
31 31
 //require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
32
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
32
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
33 33
 
34 34
 /**
35 35
  *	Classe de gestion de la database de dolibarr
@@ -37,15 +37,15 @@  discard block
 block discarded – undo
37 37
 class DoliDBMssql extends DoliDB
38 38
 {
39 39
 	//! Database type
40
-	public $type='mssql';
40
+	public $type = 'mssql';
41 41
 	//! Database label
42
-	const LABEL='MSSQL';
42
+	const LABEL = 'MSSQL';
43 43
 	//! Charset used to force charset when creating database
44
-	var $forcecharset='latin1';      // Can't be static as it may be forced with a dynamic value
44
+	var $forcecharset = 'latin1'; // Can't be static as it may be forced with a dynamic value
45 45
 	//! Collate used to force collate when creating database
46
-	var $forcecollate='latin1_swedish_ci';      // Can't be static as it may be forced with a dynamic value
46
+	var $forcecollate = 'latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value
47 47
 	//! Version min database
48
-	const VERSIONMIN='2000';
48
+	const VERSIONMIN = '2000';
49 49
 	/** @var resource Resultset of last query */
50 50
 	private $_results;
51 51
 
@@ -60,30 +60,30 @@  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 65
 		global $langs;
66 66
 
67
-		$this->database_user=$user;
68
-        $this->database_host=$host;
69
-        $this->database_port=$port;
70
-		$this->transaction_opened=0;
67
+		$this->database_user = $user;
68
+        $this->database_host = $host;
69
+        $this->database_port = $port;
70
+		$this->transaction_opened = 0;
71 71
 
72
-		if (! function_exists("mssql_connect"))
72
+		if (!function_exists("mssql_connect"))
73 73
 		{
74 74
 			$this->connected = false;
75 75
 			$this->ok = false;
76
-			$this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
77
-			dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP",LOG_ERR);
76
+			$this->error = "Mssql PHP functions for using MSSql driver are not available in this version of PHP";
77
+			dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP", LOG_ERR);
78 78
 			return $this->ok;
79 79
 		}
80 80
 
81
-		if (! $host)
81
+		if (!$host)
82 82
 		{
83 83
 			$this->connected = false;
84 84
 			$this->ok = false;
85
-			$this->error=$langs->trans("ErrorWrongHostParameter");
86
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
85
+			$this->error = $langs->trans("ErrorWrongHostParameter");
86
+			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters", LOG_ERR);
87 87
 			return $this->ok;
88 88
 		}
89 89
 
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 			// host, login ou password incorrect
102 102
 			$this->connected = false;
103 103
 			$this->ok = false;
104
-			$this->error=mssql_get_last_message();
105
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error,LOG_ERR);
104
+			$this->error = mssql_get_last_message();
105
+			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error, LOG_ERR);
106 106
 		}
107 107
 
108 108
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -119,8 +119,8 @@  discard block
 block discarded – undo
119 119
 				$this->database_selected = false;
120 120
 				$this->database_name = '';
121 121
 				$this->ok = false;
122
-				$this->error=$this->error();
123
-				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
122
+				$this->error = $this->error();
123
+				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error, LOG_ERR);
124 124
 			}
125 125
 		}
126 126
 		else
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
140 140
      *  @return    string   		SQL request line converted
141 141
      */
142
-	static function convertSQLFromMysql($line,$type='ddl')
142
+	static function convertSQLFromMysql($line, $type = 'ddl')
143 143
 	{
144 144
 		return $line;
145 145
 	}
@@ -168,25 +168,25 @@  discard block
 block discarded – undo
168 168
 	 *	@return		false|resource|true	Database access handler
169 169
 	 *	@see		close
170 170
 	 */
171
-	function connect($host, $login, $passwd, $name, $port=0)
171
+	function connect($host, $login, $passwd, $name, $port = 0)
172 172
 	{
173 173
 		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
174
-		$newhost=$host;
175
-		if ($port) $newhost.=':'.$port;
176
-		$this->db  = @mssql_connect($newhost, $login, $passwd);
174
+		$newhost = $host;
175
+		if ($port) $newhost .= ':'.$port;
176
+		$this->db = @mssql_connect($newhost, $login, $passwd);
177 177
 		//force les enregistrement en latin1 si la base est en utf8 par defaut
178 178
 		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
179 179
 		// les nouvelles version de Dolibarr car force par l'install Dolibarr.
180 180
 		//$this->query('SET NAMES '.$this->forcecharset);
181 181
 		//print "Resultat fonction connect: ".$this->db;
182
-		$set_options=array('SET ANSI_PADDING ON;',
182
+		$set_options = array('SET ANSI_PADDING ON;',
183 183
 		    "SET ANSI_NULLS ON;",
184 184
 		    "SET ANSI_WARNINGS ON;",
185 185
 		    "SET ARITHABORT ON;",
186 186
 		    "SET CONCAT_NULL_YIELDS_NULL ON;",
187 187
 		    "SET QUOTED_IDENTIFIER ON;"
188 188
 		);
189
-		mssql_query(implode(' ',$set_options),$this->db);
189
+		mssql_query(implode(' ', $set_options), $this->db);
190 190
 
191 191
 		return $this->db;
192 192
 	}
@@ -198,10 +198,10 @@  discard block
 block discarded – undo
198 198
 	 */
199 199
 	function getVersion()
200 200
 	{
201
-		$resql=$this->query("SELECT @@VERSION");
201
+		$resql = $this->query("SELECT @@VERSION");
202 202
 		if ($resql)
203 203
 		{
204
-            $version=$this->fetch_array($resql);
204
+            $version = $this->fetch_array($resql);
205 205
             return $version['computed'];
206 206
 		}
207 207
 		else return '';
@@ -227,8 +227,8 @@  discard block
 block discarded – undo
227 227
     {
228 228
         if ($this->db)
229 229
         {
230
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
231
-          $this->connected=false;
230
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
231
+          $this->connected = false;
232 232
           return mssql_close($this->db);
233 233
         }
234 234
         return false;
@@ -243,16 +243,16 @@  discard block
 block discarded – undo
243 243
 	function begin()
244 244
 	{
245 245
 
246
-	    $res=mssql_query('select @@TRANCOUNT');
247
-	    $this->transaction_opened=mssql_result($res, 0, 0);
246
+	    $res = mssql_query('select @@TRANCOUNT');
247
+	    $this->transaction_opened = mssql_result($res, 0, 0);
248 248
 
249 249
 	    if ($this->transaction_opened == 0)
250 250
 		{
251 251
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
252
-			$ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
252
+			$ret = mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;", $this->db);
253 253
 			if ($ret)
254 254
 			{
255
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
255
+				dol_syslog("BEGIN Transaction", LOG_DEBUG);
256 256
 			}
257 257
 			return $ret;
258 258
 		}
@@ -268,18 +268,18 @@  discard block
 block discarded – undo
268 268
      * @param	string	$log        Add more log to default log line
269 269
      * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
270 270
 	 */
271
-	function commit($log='')
271
+	function commit($log = '')
272 272
 	{
273
-	    $res=mssql_query('select @@TRANCOUNT');
274
-	    $this->transaction_opened=mssql_result($res, 0, 0);
273
+	    $res = mssql_query('select @@TRANCOUNT');
274
+	    $this->transaction_opened = mssql_result($res, 0, 0);
275 275
 
276 276
 		if ($this->transaction_opened == 1)
277 277
 		{
278 278
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
279
-			$ret=mssql_query("COMMIT TRANSACTION",$this->db);
279
+			$ret = mssql_query("COMMIT TRANSACTION", $this->db);
280 280
 			if ($ret)
281 281
 			{
282
-				dol_syslog("COMMIT Transaction",LOG_DEBUG);
282
+				dol_syslog("COMMIT Transaction", LOG_DEBUG);
283 283
 				return true;
284 284
 			}
285 285
 			else
@@ -301,15 +301,15 @@  discard block
 block discarded – undo
301 301
 	 * @param	string	$log	Add more log to default log line
302 302
 	 * @return	bool             true si annulation ok ou transaction non ouverte, false en cas d'erreur
303 303
 	 */
304
-	function rollback($log='')
304
+	function rollback($log = '')
305 305
 	{
306
-	    $res=mssql_query('select @@TRANCOUNT');
307
-	    $this->transaction_opened=mssql_result($res, 0, 0);
306
+	    $res = mssql_query('select @@TRANCOUNT');
307
+	    $this->transaction_opened = mssql_result($res, 0, 0);
308 308
 
309 309
 		if ($this->transaction_opened == 1)
310 310
 		{
311
-			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
312
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
311
+			$ret = mssql_query("ROLLBACK TRANSACTION", $this->db);
312
+			dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
313 313
 			return $ret;
314 314
 		}
315 315
 		elseif ($this->transaction_opened > 1)
@@ -329,59 +329,59 @@  discard block
 block discarded – undo
329 329
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
330 330
      *  @return false|resource|true		Resultset of answer
331 331
 	 */
332
-	function query($query,$usesavepoint=0,$type='auto')
332
+	function query($query, $usesavepoint = 0, $type = 'auto')
333 333
 	{
334 334
 		$query = trim($query);
335 335
 
336
-		if (preg_match('/^--/',$query)) return true;
336
+		if (preg_match('/^--/', $query)) return true;
337 337
 
338 338
 		// Conversion syntaxe MySql vers MSDE.
339 339
 		$query = str_ireplace("now()", "getdate()", $query);
340 340
 		// Erreur SQL: cannot update timestamp field
341 341
 		$query = str_ireplace(", tms = tms", "", $query);
342 342
 
343
-		$query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
343
+		$query = preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/", "$1[$2]$3", $query);
344 344
 
345
-		if ($type=="auto" || $type='dml')
345
+		if ($type == "auto" || $type = 'dml')
346 346
 		{
347
-    		$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
348
-    		$query=preg_replace('/double/i','float',$query);
349
-    		$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
350
-    		$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
351
-    		$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
352
-
353
-    		$matches=array();
354
-    		$original_query='';
355
-    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
347
+    		$query = preg_replace('/AUTO_INCREMENT/i', 'IDENTITY', $query);
348
+    		$query = preg_replace('/double/i', 'float', $query);
349
+    		$query = preg_replace('/float\((.*)\)/', 'numeric($1)', $query);
350
+    		$query = preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i', '$1', $query);
351
+    		$query = preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i', "$1VARCHAR(MAX)$3", $query);
352
+
353
+    		$matches = array();
354
+    		$original_query = '';
355
+    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query, $matches))
356 356
     		{
357
-                $original_query=$query;
358
-                $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
357
+                $original_query = $query;
358
+                $query = "CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
359 359
                 if ($matches[2]) {
360 360
                     //check if columun is nullable cause Sql server only allow 1 null value if unique index.
361
-                    $fields=explode(",",trim($matches[4]));
362
-                    $fields_clear=array_map('trim',$fields);
363
-                    $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
364
-                    $query_comp=array();
365
-                    foreach($infos as $fld) {
361
+                    $fields = explode(",", trim($matches[4]));
362
+                    $fields_clear = array_map('trim', $fields);
363
+                    $infos = $this->GetFieldInformation(trim($matches[1]), $fields_clear);
364
+                    $query_comp = array();
365
+                    foreach ($infos as $fld) {
366 366
                         if ($fld->IS_NULLABLE == 'YES') {
367
-                            $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
367
+                            $query_comp[] = $fld->COLUMN_NAME." IS NOT NULL";
368 368
                         }
369 369
                     }
370
-                    if (! empty($query_comp))
371
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
370
+                    if (!empty($query_comp))
371
+                        $query .= " WHERE ".implode(" AND ", $query_comp);
372 372
                 }
373 373
     		}
374 374
     		else
375 375
     		{
376 376
     		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
377 377
     		    {
378
-                    $original_query=$query;
379
-                    $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
378
+                    $original_query = $query;
379
+                    $query = "ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
380 380
     		    }
381 381
     		}
382 382
 		}
383 383
 
384
-		if ($type=="auto" || $type='ddl')
384
+		if ($type == "auto" || $type = 'ddl')
385 385
 		{
386 386
     		$itemfound = stripos($query, " limit ");
387 387
     		if ($itemfound !== false) {
@@ -412,21 +412,21 @@  discard block
 block discarded – undo
412 412
     			// Inserer la date en parametre et le reste de la requete
413 413
     			$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
414 414
     		}
415
-    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
415
+    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i', $query, $matches))
416 416
     	   {
417 417
     	       //var_dump($query);
418 418
     	       //var_dump($matches);
419 419
     	       //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
420
-    	       $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
420
+    	       $sql = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
421 421
     	       @mssql_query($sql, $this->db);
422
-    	       $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
422
+    	       $post_query = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
423 423
     	   }
424 424
 		}
425 425
 		//print "<!--".$query."-->";
426 426
 
427
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
427
+		if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
428 428
 
429
-		if (! $this->database_name)
429
+		if (!$this->database_name)
430 430
 		{
431 431
 			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
432 432
 			$ret = mssql_query($query, $this->db);
@@ -441,10 +441,10 @@  discard block
 block discarded – undo
441 441
 		    @mssql_query($post_query, $this->db);
442 442
 		}
443 443
 
444
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
444
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
445 445
 		{
446 446
 			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
447
-			if (! $ret)
447
+			if (!$ret)
448 448
 			{
449 449
 				$result = mssql_query("SELECT @@ERROR as code", $this->db);
450 450
 				$row = mssql_fetch_array($result);
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 				if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
458 458
 				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
459 459
 			}
460
-			$this->lastquery=$query;
460
+			$this->lastquery = $query;
461 461
 			$this->_results = $ret;
462 462
 		}
463 463
 
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 	{
476 476
         // phpcs:enable
477 477
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
478
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
478
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
479 479
 		return mssql_fetch_object($resultset);
480 480
 	}
481 481
 
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 	{
491 491
         // phpcs:enable
492 492
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
493
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
493
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
494 494
 		return mssql_fetch_array($resultset);
495 495
 	}
496 496
 
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 	{
507 507
         // phpcs:enable
508 508
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
509
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
509
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
510 510
 		return @mssql_fetch_row($resultset);
511 511
 	}
512 512
 
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 	{
523 523
         // phpcs:enable
524 524
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
525
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
525
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
526 526
 		return mssql_num_rows($resultset);
527 527
 	}
528 528
 
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
 	{
539 539
         // phpcs:enable
540 540
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
541
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
541
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
542 542
 		// mssql necessite un link de base pour cette fonction contrairement
543 543
 		// a pqsql qui prend un resultset
544 544
 		$rsRows = mssql_query("select @@rowcount as rows", $this->db);
@@ -553,10 +553,10 @@  discard block
 block discarded – undo
553 553
 	 *	@param  resource	$resultset   Curseur de la requete voulue
554 554
 	 *	@return	bool
555 555
 	 */
556
-	function free($resultset=null)
556
+	function free($resultset = null)
557 557
 	{
558 558
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
559
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
559
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
560 560
 		// Si resultset en est un, on libere la memoire
561 561
 		if (is_resource($resultset)) mssql_free_result($resultset);
562 562
 	}
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 	 */
583 583
 	function idate($param)
584 584
 	{
585
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
585
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
586 586
 	}
587 587
 
588 588
 	/**
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
 	 */
593 593
 	function errno()
594 594
 	{
595
-		if (! $this->connected)
595
+		if (!$this->connected)
596 596
 		{
597 597
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
598 598
 			return 'DB_ERROR_FAILED_TO_CONNECT';
@@ -633,8 +633,8 @@  discard block
 block discarded – undo
633 633
 			{
634 634
 				return $errorcode_map[$this->lasterrno];
635 635
 			}
636
-			$errno=$this->lasterrno;
637
-			return ($errno?'DB_ERROR_'.$errno:'0');
636
+			$errno = $this->lasterrno;
637
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
638 638
 		}
639 639
 	}
640 640
 
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
 	 */
646 646
 	function error()
647 647
 	{
648
-		if (! $this->connected) {
648
+		if (!$this->connected) {
649 649
 			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
650 650
 			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
651 651
 		}
@@ -662,7 +662,7 @@  discard block
 block discarded – undo
662 662
 	 * @param	string	$fieldid	Field name
663 663
 	 * @return  int     			Id of row or -1 on error
664 664
 	 */
665
-	function last_insert_id($tab,$fieldid='rowid')
665
+	function last_insert_id($tab, $fieldid = 'rowid')
666 666
 	{
667 667
         // phpcs:enable
668 668
 		$res = $this->query("SELECT @@IDENTITY as id");
@@ -684,18 +684,18 @@  discard block
 block discarded – undo
684 684
      *  @param	int		$withQuotes     Return string with quotes
685 685
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
686 686
 	 */
687
-	function encrypt($fieldorvalue, $withQuotes=0)
687
+	function encrypt($fieldorvalue, $withQuotes = 0)
688 688
 	{
689 689
 		global $conf;
690 690
 
691 691
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
692
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
692
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
693 693
 
694 694
 		//Encryption key
695
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
695
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
696 696
 
697 697
 		$return = $fieldorvalue;
698
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
698
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
699 699
 	}
700 700
 
701 701
 	/**
@@ -709,10 +709,10 @@  discard block
 block discarded – undo
709 709
 		global $conf;
710 710
 
711 711
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
712
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
712
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
713 713
 
714 714
 		//Encryption key
715
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
715
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
716 716
 
717 717
 		$return = $value;
718 718
 		return $return;
@@ -728,10 +728,10 @@  discard block
 block discarded – undo
728 728
 	function DDLGetConnectId()
729 729
 	{
730 730
         // phpcs:enable
731
-		$resql=$this->query('SELECT CONNECTION_ID()');
731
+		$resql = $this->query('SELECT CONNECTION_ID()');
732 732
 		if ($resql)
733 733
 		{
734
-            $row=$this->fetch_row($resql);
734
+            $row = $this->fetch_row($resql);
735 735
             return $row[0];
736 736
 		}
737 737
 		else return '?';
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 	 * 	@param	string	$owner			Username of database owner
750 750
 	 * 	@return	false|resource|true		resource defined if OK, false if KO
751 751
 	 */
752
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
752
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
753 753
 	{
754 754
         // phpcs:enable
755 755
         /*if (empty($charset))   $charset=$this->forcecharset;
@@ -759,18 +759,18 @@  discard block
 block discarded – undo
759 759
 		$sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
760 760
         //TODO: Check if we need to force a charset
761 761
 		//$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
762
-		$ret=$this->query($sql);
762
+		$ret = $this->query($sql);
763 763
 
764 764
 		$this->select_db($database);
765
-		$sql="CREATE USER [$owner] FOR LOGIN [$owner]";
766
-		mssql_query($sql,$this->db);
767
-		$sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
768
-		mssql_query($sql,$this->db);
765
+		$sql = "CREATE USER [$owner] FOR LOGIN [$owner]";
766
+		mssql_query($sql, $this->db);
767
+		$sql = "ALTER ROLE [db_owner] ADD MEMBER [$owner]";
768
+		mssql_query($sql, $this->db);
769 769
 
770
-		$sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
771
-	    @mssql_query($sql,$this->db);
772
-	    $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
773
-	    @mssql_query($sql,$this->db);
770
+		$sql = "ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
771
+	    @mssql_query($sql, $this->db);
772
+	    $sql = "ALTER DATABASE [$database] SET ANSI_NULL ON;";
773
+	    @mssql_query($sql, $this->db);
774 774
 
775 775
 	    return $ret;
776 776
 	}
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
784 784
      *  @return	array					List of tables in an array
785 785
 	 */
786
-	function DDLListTables($database,$table='')
786
+	function DDLListTables($database, $table = '')
787 787
 	{
788 788
         // phpcs:enable
789 789
 		$this->_results = mssql_list_tables($database, $this->db);
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
 		// TODO: Implement
806 806
 		// May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
807 807
 
808
-		$infotables=array();
808
+		$infotables = array();
809 809
 		return $infotables;
810 810
 	}
811 811
 
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
823 823
 	 *	@return	    int						<0 if KO, >=0 if OK
824 824
 	 */
825
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
825
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
826 826
 	{
827 827
         // phpcs:enable
828 828
 		// FIXME: $fulltext_keys parameter is unused
@@ -830,61 +830,61 @@  discard block
 block discarded – undo
830 830
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
831 831
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
832 832
 		$sql = "create table ".$table."(";
833
-		$i=0;
834
-		foreach($fields as $field_name => $field_desc)
833
+		$i = 0;
834
+		foreach ($fields as $field_name => $field_desc)
835 835
 		{
836 836
 			$sqlfields[$i] = $field_name." ";
837 837
 			$sqlfields[$i]  .= $field_desc['type'];
838
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
838
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
839 839
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
840
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
840
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
841 841
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
842
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
842
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
843 843
 			{
844
-				if(preg_match("/null/i",$field_desc['default']))
844
+				if (preg_match("/null/i", $field_desc['default']))
845 845
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
846 846
 				else
847 847
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
848 848
 			}
849
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
849
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
850 850
 			$sqlfields[$i]  .= " ".$field_desc['null'];
851 851
 
852
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
852
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
853 853
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
854 854
 			$i++;
855 855
 		}
856
-		if($primary_key != "")
856
+		if ($primary_key != "")
857 857
 		$pk = "primary key(".$primary_key.")";
858 858
 
859
-		if(is_array($unique_keys))
859
+		if (is_array($unique_keys))
860 860
 		{
861 861
 			$i = 0;
862
-			foreach($unique_keys as $key => $value)
862
+			foreach ($unique_keys as $key => $value)
863 863
 			{
864 864
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
865 865
 				$i++;
866 866
 			}
867 867
 		}
868
-		if(is_array($keys))
868
+		if (is_array($keys))
869 869
 		{
870 870
 			$i = 0;
871
-			foreach($keys as $key => $value)
871
+			foreach ($keys as $key => $value)
872 872
 			{
873 873
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
874 874
 				$i++;
875 875
 			}
876 876
 		}
877
-		$sql .= implode(',',$sqlfields);
878
-		if($primary_key != "")
877
+		$sql .= implode(',', $sqlfields);
878
+		if ($primary_key != "")
879 879
 		$sql .= ",".$pk;
880
-		if(is_array($unique_keys))
881
-		$sql .= ",".implode(',',$sqluq);
882
-		if(is_array($keys))
883
-		$sql .= ",".implode(',',$sqlk);
884
-		$sql .=") type=".$type;
880
+		if (is_array($unique_keys))
881
+		$sql .= ",".implode(',', $sqluq);
882
+		if (is_array($keys))
883
+		$sql .= ",".implode(',', $sqlk);
884
+		$sql .= ") type=".$type;
885 885
 
886 886
 		dol_syslog($sql);
887
-		if(! $this -> query($sql))
887
+		if (!$this -> query($sql))
888 888
 		return -1;
889 889
 		else
890 890
 		return 1;
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
         // phpcs:enable
903 903
 		$sql = "DROP TABLE ".$table;
904 904
 
905
-		if (! $this->query($sql))
905
+		if (!$this->query($sql))
906 906
 			return -1;
907 907
 		else
908 908
 			return 1;
@@ -916,10 +916,10 @@  discard block
 block discarded – undo
916 916
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
917 917
 	 *	@return	false|resource|true	Resource
918 918
 	 */
919
-	function DDLDescTable($table,$field="")
919
+	function DDLDescTable($table, $field = "")
920 920
 	{
921 921
         // phpcs:enable
922
-		$sql="DESC ".$table." ".$field;
922
+		$sql = "DESC ".$table." ".$field;
923 923
 
924 924
 		dol_syslog($sql);
925 925
 		$this->_results = $this->query($sql);
@@ -936,29 +936,29 @@  discard block
 block discarded – undo
936 936
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
937 937
 	 *	@return	int							<0 if KO, >0 if OK
938 938
 	 */
939
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
939
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
940 940
 	{
941 941
         // phpcs:enable
942 942
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
943 943
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
944
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
944
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
945 945
 		$sql .= $field_desc['type'];
946
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
946
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
947 947
 		$sql  .= "(".$field_desc['value'].")";
948
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
948
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
949 949
 		$sql  .= " ".$field_desc['attribute'];
950
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
950
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
951 951
 		$sql  .= " ".$field_desc['null'];
952
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
953
-		if(preg_match("/null/i",$field_desc['default']))
952
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
953
+		if (preg_match("/null/i", $field_desc['default']))
954 954
 		$sql  .= " default ".$field_desc['default'];
955 955
 		else
956 956
 		$sql  .= " default '".$field_desc['default']."'";
957
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
957
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
958 958
 		$sql  .= " ".$field_desc['extra'];
959 959
 		$sql .= " ".$field_position;
960 960
 
961
-		if(! $this -> query($sql))
961
+		if (!$this -> query($sql))
962 962
 		return -1;
963 963
 		else
964 964
 		return 1;
@@ -973,17 +973,17 @@  discard block
 block discarded – undo
973 973
 	 *	@param	string	$field_desc 		Array with description of field format
974 974
 	 *	@return	int							<0 if KO, >0 if OK
975 975
 	 */
976
-	function DDLUpdateField($table,$field_name,$field_desc)
976
+	function DDLUpdateField($table, $field_name, $field_desc)
977 977
 	{
978 978
         // phpcs:enable
979 979
 		$sql = "ALTER TABLE ".$table;
980 980
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
981 981
 		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
982
-			$sql.="(".$field_desc['value'].")";
982
+			$sql .= "(".$field_desc['value'].")";
983 983
 		}
984 984
 
985
-		dol_syslog($sql,LOG_DEBUG);
986
-		if (! $this->query($sql))
985
+		dol_syslog($sql, LOG_DEBUG);
986
+		if (!$this->query($sql))
987 987
 		return -1;
988 988
 		else
989 989
 		return 1;
@@ -997,14 +997,14 @@  discard block
 block discarded – undo
997 997
 	 *	@param	string	$field_name 	Name of field to drop
998 998
 	 *	@return	int						<0 if KO, >0 if OK
999 999
 	 */
1000
-	function DDLDropField($table,$field_name)
1000
+	function DDLDropField($table, $field_name)
1001 1001
 	{
1002 1002
         // phpcs:enable
1003
-		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1004
-		dol_syslog($sql,LOG_DEBUG);
1005
-		if (! $this->query($sql))
1003
+		$sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1004
+		dol_syslog($sql, LOG_DEBUG);
1005
+		if (!$this->query($sql))
1006 1006
 		{
1007
-			$this->error=$this->lasterror();
1007
+			$this->error = $this->lasterror();
1008 1008
 			return -1;
1009 1009
 		}
1010 1010
 		else return 1;
@@ -1020,13 +1020,13 @@  discard block
 block discarded – undo
1020 1020
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1021 1021
 	 *	@return	int									<0 if KO, >=0 if OK
1022 1022
 	 */
1023
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1023
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1024 1024
 	{
1025 1025
         // phpcs:enable
1026 1026
         $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
1027
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1028
-        $resql=$this->query($sql);
1029
-        if (! $resql)
1027
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1028
+        $resql = $this->query($sql);
1029
+        if (!$resql)
1030 1030
         {
1031 1031
             if ($this->lasterrno != '15025')
1032 1032
             {
@@ -1038,9 +1038,9 @@  discard block
 block discarded – undo
1038 1038
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1039 1039
             }
1040 1040
         }
1041
-        $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1042
-        $ressql=$this->query($sql);
1043
-        if (! $ressql)
1041
+        $sql = "SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1042
+        $ressql = $this->query($sql);
1043
+        if (!$ressql)
1044 1044
         {
1045 1045
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1046 1046
             return -1;
@@ -1050,9 +1050,9 @@  discard block
 block discarded – undo
1050 1050
             if ($num)
1051 1051
             {
1052 1052
                 $this->select_db($dolibarr_main_db_name);
1053
-                $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1053
+                $sql = "CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1054 1054
                 $this->query($sql);
1055
-                $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1055
+                $sql = "ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1056 1056
                 $this->query($sql);
1057 1057
             }
1058 1058
         }
@@ -1092,12 +1092,12 @@  discard block
 block discarded – undo
1092 1092
 	 */
1093 1093
 	function getDefaultCollationDatabase()
1094 1094
 	{
1095
-		$resql=$this->query("SELECT SERVERPROPERTY('collation')");
1095
+		$resql = $this->query("SELECT SERVERPROPERTY('collation')");
1096 1096
 		if (!$resql)
1097 1097
 		{
1098 1098
 			return $this->forcecollate;
1099 1099
 		}
1100
-		$liste=$this->fetch_array($resql);
1100
+		$liste = $this->fetch_array($resql);
1101 1101
 		return $liste['computed'];
1102 1102
 	}
1103 1103
 
@@ -1146,13 +1146,13 @@  discard block
 block discarded – undo
1146 1146
 	 * @param	string	$filter		Filter list on a particular value
1147 1147
 	 * @return	array				Array of key-values (key=>value)
1148 1148
 	 */
1149
-	function getServerParametersValues($filter='')
1149
+	function getServerParametersValues($filter = '')
1150 1150
 	{
1151 1151
 		// FIXME: Dummy method
1152 1152
 		// TODO: Implement
1153 1153
 		// May help: SELECT SERVERPROPERTY
1154 1154
 
1155
-		$result=array();
1155
+		$result = array();
1156 1156
 		return $result;
1157 1157
 	}
1158 1158
 
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
 	 * @param	string	$filter		Filter list on a particular value
1163 1163
 	 * @return  array				Array of key-values (key=>value)
1164 1164
 	 */
1165
-	function getServerStatusValues($filter='')
1165
+	function getServerStatusValues($filter = '')
1166 1166
 	{
1167 1167
 		// FIXME: Dummy method
1168 1168
 		// TODO: Implement
@@ -1193,25 +1193,25 @@  discard block
 block discarded – undo
1193 1193
 	 * @param      mixed   $fields     String for one field or array of string for multiple field
1194 1194
 	 * @return false|object
1195 1195
 	 */
1196
-    function GetFieldInformation($table,$fields)
1196
+    function GetFieldInformation($table, $fields)
1197 1197
     {
1198 1198
         // phpcs:enable
1199
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1199
+	    $sql = "SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1200 1200
 	    if (is_array($fields))
1201 1201
 	    {
1202
-	        $where=" IN ('".implode("','",$fields)."')";
1202
+	        $where = " IN ('".implode("','", $fields)."')";
1203 1203
 	    }
1204 1204
 	    else
1205 1205
 	    {
1206
-	        $where="='".$this->escape($fields)."'";
1206
+	        $where = "='".$this->escape($fields)."'";
1207 1207
 	    }
1208
-	    $result=array();
1209
-	    $ret=mssql_query($sql.$where,$this->db);
1208
+	    $result = array();
1209
+	    $ret = mssql_query($sql.$where, $this->db);
1210 1210
 	    if ($ret)
1211 1211
 	    {
1212
-	        while($obj=mssql_fetch_object($ret))
1212
+	        while ($obj = mssql_fetch_object($ret))
1213 1213
 	        {
1214
-	            $result[]=$obj;
1214
+	            $result[] = $obj;
1215 1215
 	        }
1216 1216
 	    }
1217 1217
 	    else
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/mysqli.class.php 3 patches
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -32,27 +32,27 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class DoliDBMysqli extends DoliDB
34 34
 {
35
-	/** @var mysqli Database object */
36
-	public $db;
35
+    /** @var mysqli Database object */
36
+    public $db;
37 37
     //! Database type
38 38
     public $type='mysqli';
39 39
     //! Database label
40 40
     const LABEL='MySQL or MariaDB';
41 41
     //! Version min database
42 42
     const VERSIONMIN='5.0.3';
43
-	/** @var mysqli_result Resultset of last query */
44
-	private $_results;
43
+    /** @var mysqli_result Resultset of last query */
44
+    private $_results;
45 45
 
46 46
     /**
47
-	 *	Constructor.
48
-	 *	This create an opened connexion to a database server and eventually to a database
49
-	 *
50
-	 *	@param      string	$type		Type of database (mysql, pgsql...)
51
-	 *	@param	    string	$host		Address of database server
52
-	 *	@param	    string	$user		Nom de l'utilisateur autorise
53
-	 *	@param	    string	$pass		Mot de passe
54
-	 *	@param	    string	$name		Nom de la database
55
-	 *	@param	    int		$port		Port of database server
47
+     *	Constructor.
48
+     *	This create an opened connexion to a database server and eventually to a database
49
+     *
50
+     *	@param      string	$type		Type of database (mysql, pgsql...)
51
+     *	@param	    string	$host		Address of database server
52
+     *	@param	    string	$user		Nom de l'utilisateur autorise
53
+     *	@param	    string	$pass		Mot de passe
54
+     *	@param	    string	$name		Nom de la database
55
+     *	@param	    int		$port		Port of database server
56 56
      */
57 57
     function __construct($type, $host, $user, $pass, $name='', $port=0)
58 58
     {
@@ -86,21 +86,21 @@  discard block
 block discarded – undo
86 86
             dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
87 87
         }
88 88
 
89
-		// Try server connection
90
-		// We do not try to connect to database, only to server. Connect to database is done later in constrcutor
91
-		$this->db = $this->connect($host, $user, $pass, '', $port);
92
-
93
-		if ($this->db->connect_errno) {
94
-			$this->connected = false;
95
-			$this->ok = false;
96
-			$this->error = $this->db->connect_error;
97
-			dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
98
-		} else {
99
-			$this->connected = true;
100
-			$this->ok = true;
101
-		}
102
-
103
-		// If server connection is ok, we try to connect to the database
89
+        // Try server connection
90
+        // We do not try to connect to database, only to server. Connect to database is done later in constrcutor
91
+        $this->db = $this->connect($host, $user, $pass, '', $port);
92
+
93
+        if ($this->db->connect_errno) {
94
+            $this->connected = false;
95
+            $this->ok = false;
96
+            $this->error = $this->db->connect_error;
97
+            dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
98
+        } else {
99
+            $this->connected = true;
100
+            $this->ok = true;
101
+        }
102
+
103
+        // If server connection is ok, we try to connect to the database
104 104
         if ($this->connected && $name)
105 105
         {
106 106
             if ($this->select_db($name))
@@ -113,14 +113,14 @@  discard block
 block discarded – undo
113 113
                 $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114 114
                 if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
115 115
 
116
-				if ($this->db->character_set_name() != $clientmustbe) {
117
-					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
116
+                if ($this->db->character_set_name() != $clientmustbe) {
117
+                    $this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
118 118
 
119
-					$collation = $conf->db->dolibarr_main_db_collation;
120
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
119
+                    $collation = $conf->db->dolibarr_main_db_collation;
120
+                    if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
121 121
 
122
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
123
-				}
122
+                    if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
123
+                }
124 124
             }
125 125
             else
126 126
             {
@@ -138,19 +138,19 @@  discard block
 block discarded – undo
138 138
 
139 139
             if ($this->connected)
140 140
             {
141
-            	// If client is old latin, we force utf8
142
-            	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
141
+                // If client is old latin, we force utf8
142
+                $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
+                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
144 144
 
145
-				if ($this->db->character_set_name() != $clientmustbe) {
146
-					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
145
+                if ($this->db->character_set_name() != $clientmustbe) {
146
+                    $this->db->set_charset($clientmustbe);	// This set utf8_general_ci
147 147
 
148
-					$collation = $conf->db->dolibarr_main_db_collation;
149
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
148
+                    $collation = $conf->db->dolibarr_main_db_collation;
149
+                    if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
150 150
 
151
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
152
-				}
153
-			}
151
+                    if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
152
+                }
153
+            }
154 154
         }
155 155
     }
156 156
 
@@ -168,12 +168,12 @@  discard block
 block discarded – undo
168 168
     }
169 169
 
170 170
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
171
-	/**
172
-	 *  Select a database
173
-	 *
174
-	 *  @param	    string	$database	Name of database
175
-	 *  @return	    boolean  		    true if OK, false if KO
176
-	 */
171
+    /**
172
+     *  Select a database
173
+     *
174
+     *  @param	    string	$database	Name of database
175
+     *  @return	    boolean  		    true if OK, false if KO
176
+     */
177 177
     function select_db($database)
178 178
     {
179 179
         // phpcs:enable
@@ -182,31 +182,31 @@  discard block
 block discarded – undo
182 182
     }
183 183
 
184 184
 
185
-	/**
186
-	 * Connect to server
187
-	 *
188
-	 * @param   string $host database server host
189
-	 * @param   string $login login
190
-	 * @param   string $passwd password
191
-	 * @param   string $name name of database (not used for mysql, used for pgsql)
192
-	 * @param   integer $port Port of database server
193
-	 * @return  mysqli  Database access object
194
-	 * @see close
195
-	 */
196
-	function connect($host, $login, $passwd, $name, $port = 0)
197
-	{
198
-		dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
199
-
200
-		// Can also be
201
-		// mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
202
-		// return mysqli::real_connect($host, $user, $pass, $db, $port);
203
-		return new mysqli($host, $login, $passwd, $name, $port);
204
-	}
185
+    /**
186
+     * Connect to server
187
+     *
188
+     * @param   string $host database server host
189
+     * @param   string $login login
190
+     * @param   string $passwd password
191
+     * @param   string $name name of database (not used for mysql, used for pgsql)
192
+     * @param   integer $port Port of database server
193
+     * @return  mysqli  Database access object
194
+     * @see close
195
+     */
196
+    function connect($host, $login, $passwd, $name, $port = 0)
197
+    {
198
+        dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
199
+
200
+        // Can also be
201
+        // mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
202
+        // return mysqli::real_connect($host, $user, $pass, $db, $port);
203
+        return new mysqli($host, $login, $passwd, $name, $port);
204
+    }
205 205
 
206 206
     /**
207
-	 *	Return version of database server
208
-	 *
209
-	 *	@return	        string      Version string
207
+     *	Return version of database server
208
+     *
209
+     *	@return	        string      Version string
210 210
      */
211 211
     function getVersion()
212 212
     {
@@ -218,10 +218,10 @@  discard block
 block discarded – undo
218 218
      *
219 219
      *	@return	        string      Version string
220 220
      */
221
-	function getDriverInfo()
222
-	{
223
-		return $this->db->client_info;
224
-	}
221
+    function getDriverInfo()
222
+    {
223
+        return $this->db->client_info;
224
+    }
225 225
 
226 226
 
227 227
     /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
     {
235 235
         if ($this->db)
236 236
         {
237
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
237
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
238 238
             $this->connected=false;
239 239
             return $this->db->close();
240 240
         }
@@ -252,11 +252,11 @@  discard block
 block discarded – undo
252 252
      */
253 253
     function query($query,$usesavepoint=0,$type='auto')
254 254
     {
255
-    	global $conf;
255
+        global $conf;
256 256
 
257 257
         $query = trim($query);
258 258
 
259
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
259
+        if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
260 260
 
261 261
         if (! $this->database_name)
262 262
         {
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
                 $this->lasterror = $this->error();
278 278
                 $this->lasterrno = $this->errno();
279 279
 
280
-				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
280
+                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
281 281
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
282 282
             }
283 283
             $this->lastquery=$query;
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
         // phpcs:enable
300 300
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
301 301
         if (! is_object($resultset)) { $resultset=$this->_results; }
302
-		return $resultset->fetch_object();
302
+        return $resultset->fetch_object();
303 303
     }
304 304
 
305 305
 
@@ -453,9 +453,9 @@  discard block
 block discarded – undo
453 453
     }
454 454
 
455 455
     /**
456
-	 *	Return description of last error
457
-	 *
458
-	 *	@return	string		Error text
456
+     *	Return description of last error
457
+     *
458
+     *	@return	string		Error text
459 459
      */
460 460
     function error()
461 461
     {
@@ -470,11 +470,11 @@  discard block
 block discarded – undo
470 470
 
471 471
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
472 472
     /**
473
-	 * Get last ID after an insert INSERT
474
-	 *
475
-	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
476
-	 * @param	string	$fieldid	Field name
477
-	 * @return  int|string			Id of row
473
+     * Get last ID after an insert INSERT
474
+     *
475
+     * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
476
+     * @param	string	$fieldid	Field name
477
+     * @return  int|string			Id of row
478 478
      */
479 479
     function last_insert_id($tab,$fieldid='rowid')
480 480
     {
@@ -554,9 +554,9 @@  discard block
 block discarded – undo
554 554
 
555 555
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
556 556
     /**
557
-	 * Return connexion ID
558
-	 *
559
-	 * @return	        string      Id connexion
557
+     * Return connexion ID
558
+     *
559
+     * @return	        string      Id connexion
560 560
      */
561 561
     function DDLGetConnectId()
562 562
     {
@@ -573,14 +573,14 @@  discard block
 block discarded – undo
573 573
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
574 574
     /**
575 575
      *  Create a new database
576
-	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
577
-	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
578
-	 *
579
-	 *	@param	string	$database		Database name to create
580
-	 * 	@param	string	$charset		Charset used to store data
581
-	 * 	@param	string	$collation		Charset used to sort data
582
-	 * 	@param	string	$owner			Username of database owner
583
-	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
576
+     *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
577
+     *	We force to create database with charset this->forcecharset and collate this->forcecollate
578
+     *
579
+     *	@param	string	$database		Database name to create
580
+     * 	@param	string	$charset		Charset used to store data
581
+     * 	@param	string	$collation		Charset used to sort data
582
+     * 	@param	string	$owner			Username of database owner
583
+     * 	@return	bool|mysqli_result		resource defined if OK, null if KO
584 584
      */
585 585
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
586 586
     {
@@ -589,8 +589,8 @@  discard block
 block discarded – undo
589 589
         if (empty($collation)) $collation=$this->forcecollate;
590 590
 
591 591
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
592
-		$sql = "CREATE DATABASE `".$this->escape($database)."`";
593
-		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
592
+        $sql = "CREATE DATABASE `".$this->escape($database)."`";
593
+        $sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
594 594
 
595 595
         dol_syslog($sql,LOG_DEBUG);
596 596
         $ret=$this->query($sql);
@@ -606,11 +606,11 @@  discard block
 block discarded – undo
606 606
 
607 607
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
608 608
     /**
609
-	 *  List tables into a database
610
-	 *
611
-	 *  @param	string		$database	Name of database
612
-	 *  @param	string		$table		Nmae of table filter ('xxx%')
613
-	 *  @return	array					List of tables in an array
609
+     *  List tables into a database
610
+     *
611
+     *  @param	string		$database	Name of database
612
+     *  @param	string		$table		Nmae of table filter ('xxx%')
613
+     *  @return	array					List of tables in an array
614 614
      */
615 615
     function DDLListTables($database, $table='')
616 616
     {
@@ -634,10 +634,10 @@  discard block
 block discarded – undo
634 634
 
635 635
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
636 636
     /**
637
-	 *	List information of columns into a table.
638
-	 *
639
-	 *	@param	string	$table		Name of table
640
-	 *	@return	array				Tableau des informations des champs de la table
637
+     *	List information of columns into a table.
638
+     *
639
+     *	@param	string	$table		Name of table
640
+     *	@return	array				Tableau des informations des champs de la table
641 641
      */
642 642
     function DDLInfoTable($table)
643 643
     {
@@ -660,21 +660,21 @@  discard block
 block discarded – undo
660 660
 
661 661
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
662 662
     /**
663
-	 *	Create a table into database
664
-	 *
665
-	 *	@param	    string	$table 			Name of table
666
-	 *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
667
-	 *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
668
-	 *	@param	    string	$type 			Type de la table
669
-	 *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
670
-	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
671
-	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
672
-	 *	@return	    int						<0 if KO, >=0 if OK
663
+     *	Create a table into database
664
+     *
665
+     *	@param	    string	$table 			Name of table
666
+     *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
667
+     *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
668
+     *	@param	    string	$type 			Type de la table
669
+     *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
670
+     *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
671
+     *	@param	    array	$keys 			Tableau des champs cles noms => valeur
672
+     *	@return	    int						<0 if KO, >=0 if OK
673 673
      */
674 674
     function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
675 675
     {
676 676
         // phpcs:enable
677
-	    // FIXME: $fulltext_keys parameter is unused
677
+        // FIXME: $fulltext_keys parameter is unused
678 678
 
679 679
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
680 680
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
@@ -682,29 +682,29 @@  discard block
 block discarded – undo
682 682
         $i=0;
683 683
         foreach($fields as $field_name => $field_desc)
684 684
         {
685
-        	$sqlfields[$i] = $field_name." ";
686
-			$sqlfields[$i]  .= $field_desc['type'];
687
-			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
688
-				$sqlfields[$i]  .= "(".$field_desc['value'].")";
689
-			}
690
-			if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
691
-				$sqlfields[$i]  .= " ".$field_desc['attribute'];
692
-			}
693
-			if( preg_match("/^[^\s]/i",$field_desc['default']))
694
-			{
695
-				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
696
-					$sqlfields[$i]  .= " default ".$field_desc['default'];
697
-				}
698
-				else {
699
-					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
700
-				}
701
-			}
702
-			if( preg_match("/^[^\s]/i",$field_desc['null'])) {
703
-				$sqlfields[$i]  .= " ".$field_desc['null'];
704
-			}
705
-			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
706
-				$sqlfields[$i]  .= " ".$field_desc['extra'];
707
-			}
685
+            $sqlfields[$i] = $field_name." ";
686
+            $sqlfields[$i]  .= $field_desc['type'];
687
+            if( preg_match("/^[^\s]/i",$field_desc['value'])) {
688
+                $sqlfields[$i]  .= "(".$field_desc['value'].")";
689
+            }
690
+            if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
691
+                $sqlfields[$i]  .= " ".$field_desc['attribute'];
692
+            }
693
+            if( preg_match("/^[^\s]/i",$field_desc['default']))
694
+            {
695
+                if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
696
+                    $sqlfields[$i]  .= " default ".$field_desc['default'];
697
+                }
698
+                else {
699
+                    $sqlfields[$i]  .= " default '".$field_desc['default']."'";
700
+                }
701
+            }
702
+            if( preg_match("/^[^\s]/i",$field_desc['null'])) {
703
+                $sqlfields[$i]  .= " ".$field_desc['null'];
704
+            }
705
+            if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
706
+                $sqlfields[$i]  .= " ".$field_desc['extra'];
707
+            }
708 708
             $i++;
709 709
         }
710 710
         if($primary_key != "")
@@ -754,19 +754,19 @@  discard block
 block discarded – undo
754 754
         // phpcs:enable
755 755
         $sql = "DROP TABLE ".$table;
756 756
 
757
-		if (! $this->query($sql))
758
- 			return -1;
759
-    	else
760
-    		return 1;
757
+        if (! $this->query($sql))
758
+                return -1;
759
+        else
760
+            return 1;
761 761
     }
762 762
 
763 763
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
764 764
     /**
765
-	 *	Return a pointer of line with description of a table or field
766
-	 *
767
-	 *	@param	string		$table	Name of table
768
-	 *	@param	string		$field	Optionnel : Name of field if we want description of field
769
-	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
765
+     *	Return a pointer of line with description of a table or field
766
+     *
767
+     *	@param	string		$table	Name of table
768
+     *	@param	string		$field	Optionnel : Name of field if we want description of field
769
+     *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
770 770
      */
771 771
     function DDLDescTable($table,$field="")
772 772
     {
@@ -780,13 +780,13 @@  discard block
 block discarded – undo
780 780
 
781 781
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
782 782
     /**
783
-	 *	Create a new field into table
784
-	 *
785
-	 *	@param	string	$table 				Name of table
786
-	 *	@param	string	$field_name 		Name of field to add
787
-	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
788
-	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
789
-	 *	@return	int							<0 if KO, >0 if OK
783
+     *	Create a new field into table
784
+     *
785
+     *	@param	string	$table 				Name of table
786
+     *	@param	string	$field_name 		Name of field to add
787
+     *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
788
+     *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
789
+     *	@return	int							<0 if KO, >0 if OK
790 790
      */
791 791
     function DDLAddField($table,$field_name,$field_desc,$field_position="")
792 792
     {
@@ -804,11 +804,11 @@  discard block
 block discarded – undo
804 804
         }
805 805
         if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i",$field_desc['attribute']))
806 806
         {
807
-        	$sql.= " ".$field_desc['attribute'];
807
+            $sql.= " ".$field_desc['attribute'];
808 808
         }
809 809
         if (isset($field_desc['null']) && preg_match("/^[^\s]/i",$field_desc['null']))
810 810
         {
811
-        	$sql.= " ".$field_desc['null'];
811
+            $sql.= " ".$field_desc['null'];
812 812
         }
813 813
         if (isset($field_desc['default']) && preg_match("/^[^\s]/i",$field_desc['default']))
814 814
         {
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
         }
820 820
         if (isset($field_desc['extra']) && preg_match("/^[^\s]/i",$field_desc['extra']))
821 821
         {
822
-        	$sql.= " ".$field_desc['extra'];
822
+            $sql.= " ".$field_desc['extra'];
823 823
         }
824 824
         $sql.= " ".$field_position;
825 825
 
@@ -832,12 +832,12 @@  discard block
 block discarded – undo
832 832
 
833 833
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
834 834
     /**
835
-	 *	Update format of a field into a table
836
-	 *
837
-	 *	@param	string	$table 				Name of table
838
-	 *	@param	string	$field_name 		Name of field to modify
839
-	 *	@param	string	$field_desc 		Array with description of field format
840
-	 *	@return	int							<0 if KO, >0 if OK
835
+     *	Update format of a field into a table
836
+     *
837
+     *	@param	string	$table 				Name of table
838
+     *	@param	string	$field_name 		Name of field to modify
839
+     *	@param	string	$field_desc 		Array with description of field format
840
+     *	@return	int							<0 if KO, >0 if OK
841 841
      */
842 842
     function DDLUpdateField($table,$field_name,$field_desc)
843 843
     {
@@ -845,29 +845,29 @@  discard block
 block discarded – undo
845 845
         $sql = "ALTER TABLE ".$table;
846 846
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
847 847
         if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
848
-        	$sql.="(".$field_desc['value'].")";
848
+            $sql.="(".$field_desc['value'].")";
849 849
         }
850 850
         if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
851 851
         {
852
-        	// 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
853
-        	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
854
-        	{
855
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
856
-        		$this->query($sqlbis);
857
-        	}
858
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
859
-        	{
860
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
861
-        		$this->query($sqlbis);
862
-        	}
863
-
864
-        	$sql.=" NOT NULL";
852
+            // 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
853
+            if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
854
+            {
855
+                $sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
856
+                $this->query($sqlbis);
857
+            }
858
+            elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
859
+            {
860
+                $sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
861
+                $this->query($sqlbis);
862
+            }
863
+
864
+            $sql.=" NOT NULL";
865 865
         }
866 866
 
867 867
         if ($field_desc['default'] != '')
868 868
         {
869
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
870
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
869
+            if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
870
+            elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
871 871
         }
872 872
 
873 873
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
@@ -879,11 +879,11 @@  discard block
 block discarded – undo
879 879
 
880 880
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
881 881
     /**
882
-	 *	Drop a field from table
883
-	 *
884
-	 *	@param	string	$table 			Name of table
885
-	 *	@param	string	$field_name 	Name of field to drop
886
-	 *	@return	int						<0 if KO, >0 if OK
882
+     *	Drop a field from table
883
+     *
884
+     *	@param	string	$table 			Name of table
885
+     *	@param	string	$field_name 	Name of field to drop
886
+     *	@return	int						<0 if KO, >0 if OK
887 887
      */
888 888
     function DDLDropField($table,$field_name)
889 889
     {
@@ -900,13 +900,13 @@  discard block
 block discarded – undo
900 900
 
901 901
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
902 902
     /**
903
-	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
904
-	 *
905
-	 *	@param	string	$dolibarr_main_db_host 		Ip server or '%'
906
-	 *	@param	string	$dolibarr_main_db_user 		Nom user a creer
907
-	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
908
-	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
909
-	 *	@return	int									<0 if KO, >=0 if OK
903
+     * 	Create a user and privileges to connect to database (even if database does not exists yet)
904
+     *
905
+     *	@param	string	$dolibarr_main_db_host 		Ip server or '%'
906
+     *	@param	string	$dolibarr_main_db_user 		Nom user a creer
907
+     *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
908
+     *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
909
+     *	@return	int									<0 if KO, >=0 if OK
910 910
      */
911 911
     function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
912 912
     {
@@ -918,12 +918,12 @@  discard block
 block discarded – undo
918 918
         {
919 919
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
920 920
             {
921
-            	return -1;
921
+                return -1;
922 922
             }
923 923
             else
924
-			{
925
-            	// If user already exists, we continue to set permissions
926
-            	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
924
+            {
925
+                // If user already exists, we continue to set permissions
926
+                dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
927 927
             }
928 928
         }
929 929
         $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)."'";
@@ -1039,9 +1039,9 @@  discard block
 block discarded – undo
1039 1039
     }
1040 1040
 
1041 1041
     /**
1042
-	 *	Return full path of dump program
1043
-	 *
1044
-	 *	@return		string		Full path of dump program
1042
+     *	Return full path of dump program
1043
+     *
1044
+     *	@return		string		Full path of dump program
1045 1045
      */
1046 1046
     function getPathOfDump()
1047 1047
     {
@@ -1080,7 +1080,7 @@  discard block
 block discarded – undo
1080 1080
      * Return value of server parameters
1081 1081
      *
1082 1082
      * @param	string	$filter		Filter list on a particular value
1083
-	 * @return	array				Array of key-values (key=>value)
1083
+     * @return	array				Array of key-values (key=>value)
1084 1084
      */
1085 1085
     function getServerParametersValues($filter='')
1086 1086
     {
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
         $resql=$this->query($sql);
1092 1092
         if ($resql)
1093 1093
         {
1094
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1094
+            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1095 1095
         }
1096 1096
 
1097 1097
         return $result;
@@ -1101,7 +1101,7 @@  discard block
 block discarded – undo
1101 1101
      * Return value of server status (current indicators on memory, cache...)
1102 1102
      *
1103 1103
      * @param	string	$filter		Filter list on a particular value
1104
-	 * @return  array				Array of key-values (key=>value)
1104
+     * @return  array				Array of key-values (key=>value)
1105 1105
      */
1106 1106
     function getServerStatusValues($filter='')
1107 1107
     {
Please login to merge, or discard this patch.
Braces   +108 added lines, -66 removed lines patch added patch discarded remove patch
@@ -59,8 +59,12 @@  discard block
 block discarded – undo
59 59
         global $conf,$langs;
60 60
 
61 61
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
62
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
63
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
62
+        if (! empty($conf->db->character_set)) {
63
+            $this->forcecharset=$conf->db->character_set;
64
+        }
65
+        if (! empty($conf->db->dolibarr_main_db_collation)) {
66
+            $this->forcecollate=$conf->db->dolibarr_main_db_collation;
67
+        }
64 68
 
65 69
         $this->database_user=$user;
66 70
         $this->database_host=$host;
@@ -111,18 +115,23 @@  discard block
 block discarded – undo
111 115
 
112 116
                 // If client is old latin, we force utf8
113 117
                 $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
118
+                if (preg_match('/latin1/', $clientmustbe)) {
119
+                    $clientmustbe='utf8';
120
+                }
115 121
 
116 122
 				if ($this->db->character_set_name() != $clientmustbe) {
117 123
 					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
118 124
 
119 125
 					$collation = $conf->db->dolibarr_main_db_collation;
120
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
126
+					if (preg_match('/latin1/', $collation)) {
127
+					    $collation='utf8_unicode_ci';
128
+					}
121 129
 
122
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
130
+					if (! preg_match('/general/', $collation)) {
131
+					    $this->db->query("SET collation_connection = ".$collation);
132
+					}
123 133
 				}
124
-            }
125
-            else
134
+            } else
126 135
             {
127 136
                 $this->database_selected = false;
128 137
                 $this->database_name = '';
@@ -130,8 +139,7 @@  discard block
 block discarded – undo
130 139
                 $this->error=$this->error();
131 140
                 dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
132 141
             }
133
-        }
134
-        else
142
+        } else
135 143
         {
136 144
             // Pas de selection de base demandee, ok ou ko
137 145
             $this->database_selected = false;
@@ -140,15 +148,21 @@  discard block
 block discarded – undo
140 148
             {
141 149
             	// If client is old latin, we force utf8
142 150
             	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
151
+            	if (preg_match('/latin1/', $clientmustbe)) {
152
+            	    $clientmustbe='utf8';
153
+            	}
144 154
 
145 155
 				if ($this->db->character_set_name() != $clientmustbe) {
146 156
 					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
147 157
 
148 158
 					$collation = $conf->db->dolibarr_main_db_collation;
149
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
159
+					if (preg_match('/latin1/', $collation)) {
160
+					    $collation='utf8_unicode_ci';
161
+					}
150 162
 
151
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
163
+					if (! preg_match('/general/', $collation)) {
164
+					    $this->db->query("SET collation_connection = ".$collation);
165
+					}
152 166
 				}
153 167
 			}
154 168
         }
@@ -234,7 +248,9 @@  discard block
 block discarded – undo
234 248
     {
235 249
         if ($this->db)
236 250
         {
237
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
251
+	        if ($this->transaction_opened > 0) {
252
+	            dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
253
+	        }
238 254
             $this->connected=false;
239 255
             return $this->db->close();
240 256
         }
@@ -256,14 +272,15 @@  discard block
 block discarded – undo
256 272
 
257 273
         $query = trim($query);
258 274
 
259
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
275
+	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
276
+	        dol_syslog('sql='.$query, LOG_DEBUG);
277
+	    }
260 278
 
261 279
         if (! $this->database_name)
262 280
         {
263 281
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
264 282
             $ret = $this->db->query($query);
265
-        }
266
-        else
283
+        } else
267 284
         {
268 285
             $ret = $this->db->query($query);
269 286
         }
@@ -277,7 +294,10 @@  discard block
 block discarded – undo
277 294
                 $this->lasterror = $this->error();
278 295
                 $this->lasterrno = $this->errno();
279 296
 
280
-				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
297
+				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
298
+				    dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
299
+				}
300
+				// Log of request was not yet done previously
281 301
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
282 302
             }
283 303
             $this->lastquery=$query;
@@ -333,8 +353,7 @@  discard block
 block discarded – undo
333 353
         {
334 354
             if (! is_object($resultset)) { $resultset=$this->_results; }
335 355
             return $resultset->fetch_row();
336
-        }
337
-        else
356
+        } else
338 357
         {
339 358
             // si le curseur est un booleen on retourne la valeur 0
340 359
             return 0;
@@ -387,7 +406,9 @@  discard block
 block discarded – undo
387 406
         // If resultset not provided, we take the last used by connexion
388 407
         if (! is_object($resultset)) { $resultset=$this->_results; }
389 408
         // Si resultset en est un, on libere la memoire
390
-        if (is_object($resultset)) $resultset->free_result();
409
+        if (is_object($resultset)) {
410
+            $resultset->free_result();
411
+        }
391 412
     }
392 413
 
393 414
     /**
@@ -462,8 +483,7 @@  discard block
 block discarded – undo
462 483
         if (! $this->connected) {
463 484
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
464 485
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
465
-        }
466
-        else {
486
+        } else {
467 487
             return $this->db->error;
468 488
         }
469 489
     }
@@ -508,8 +528,7 @@  discard block
 block discarded – undo
508 528
             if ($cryptType == 2)
509 529
             {
510 530
                 $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
511
-            }
512
-            else if ($cryptType == 1)
531
+            } else if ($cryptType == 1)
513 532
             {
514 533
                 $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
515 534
             }
@@ -541,8 +560,7 @@  discard block
 block discarded – undo
541 560
             if ($cryptType == 2)
542 561
             {
543 562
                 $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
544
-            }
545
-            else if ($cryptType == 1)
563
+            } else if ($cryptType == 1)
546 564
             {
547 565
                 $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
548 566
             }
@@ -566,8 +584,9 @@  discard block
 block discarded – undo
566 584
         {
567 585
             $row=$this->fetch_row($resql);
568 586
             return $row[0];
587
+        } else {
588
+            return '?';
569 589
         }
570
-        else return '?';
571 590
     }
572 591
 
573 592
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -585,8 +604,12 @@  discard block
 block discarded – undo
585 604
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
586 605
     {
587 606
         // phpcs:enable
588
-        if (empty($charset))   $charset=$this->forcecharset;
589
-        if (empty($collation)) $collation=$this->forcecollate;
607
+        if (empty($charset)) {
608
+            $charset=$this->forcecharset;
609
+        }
610
+        if (empty($collation)) {
611
+            $collation=$this->forcecollate;
612
+        }
590 613
 
591 614
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
592 615
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
@@ -618,7 +641,9 @@  discard block
 block discarded – undo
618 641
         $listtables=array();
619 642
 
620 643
         $like = '';
621
-        if ($table) $like = "LIKE '".$table."'";
644
+        if ($table) {
645
+            $like = "LIKE '".$table."'";
646
+        }
622 647
         $sql="SHOW TABLES FROM ".$database." ".$like.";";
623 648
         //print $sql;
624 649
         $result = $this->query($sql);
@@ -694,8 +719,7 @@  discard block
 block discarded – undo
694 719
 			{
695 720
 				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
696 721
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
697
-				}
698
-				else {
722
+				} else {
699 723
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
700 724
 				}
701 725
 			}
@@ -707,8 +731,9 @@  discard block
 block discarded – undo
707 731
 			}
708 732
             $i++;
709 733
         }
710
-        if($primary_key != "")
711
-        $pk = "primary key(".$primary_key.")";
734
+        if($primary_key != "") {
735
+                $pk = "primary key(".$primary_key.")";
736
+        }
712 737
 
713 738
         if(is_array($unique_keys)) {
714 739
             $i = 0;
@@ -728,18 +753,22 @@  discard block
 block discarded – undo
728 753
             }
729 754
         }
730 755
         $sql .= implode(',',$sqlfields);
731
-        if($primary_key != "")
732
-        $sql .= ",".$pk;
733
-        if($unique_keys != "")
734
-        $sql .= ",".implode(',',$sqluq);
735
-        if(is_array($keys))
736
-        $sql .= ",".implode(',',$sqlk);
756
+        if($primary_key != "") {
757
+                $sql .= ",".$pk;
758
+        }
759
+        if($unique_keys != "") {
760
+                $sql .= ",".implode(',',$sqluq);
761
+        }
762
+        if(is_array($keys)) {
763
+                $sql .= ",".implode(',',$sqlk);
764
+        }
737 765
         $sql .=") engine=".$type;
738 766
 
739
-        if(! $this->query($sql))
740
-        return -1;
741
-        else
742
-        return 1;
767
+        if(! $this->query($sql)) {
768
+                return -1;
769
+        } else {
770
+                return 1;
771
+        }
743 772
     }
744 773
 
745 774
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -754,10 +783,11 @@  discard block
 block discarded – undo
754 783
         // phpcs:enable
755 784
         $sql = "DROP TABLE ".$table;
756 785
 
757
-		if (! $this->query($sql))
758
- 			return -1;
759
-    	else
760
-    		return 1;
786
+		if (! $this->query($sql)) {
787
+		 			return -1;
788
+		} else {
789
+    	    		return 1;
790
+    	}
761 791
     }
762 792
 
763 793
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -812,10 +842,11 @@  discard block
 block discarded – undo
812 842
         }
813 843
         if (isset($field_desc['default']) && preg_match("/^[^\s]/i",$field_desc['default']))
814 844
         {
815
-            if(preg_match("/null/i",$field_desc['default']))
816
-            $sql.= " default ".$field_desc['default'];
817
-            else
818
-            $sql.= " default '".$field_desc['default']."'";
845
+            if(preg_match("/null/i",$field_desc['default'])) {
846
+                        $sql.= " default ".$field_desc['default'];
847
+            } else {
848
+                        $sql.= " default '".$field_desc['default']."'";
849
+            }
819 850
         }
820 851
         if (isset($field_desc['extra']) && preg_match("/^[^\s]/i",$field_desc['extra']))
821 852
         {
@@ -854,8 +885,7 @@  discard block
 block discarded – undo
854 885
         	{
855 886
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
856 887
         		$this->query($sqlbis);
857
-        	}
858
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
888
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
859 889
         	{
860 890
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
861 891
         		$this->query($sqlbis);
@@ -866,15 +896,20 @@  discard block
 block discarded – undo
866 896
 
867 897
         if ($field_desc['default'] != '')
868 898
         {
869
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
870
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
899
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
900
+			    $sql.=" DEFAULT ".$this->escape($field_desc['default']);
901
+			} elseif ($field_desc['type'] == 'text') {
902
+        	    $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
903
+        	}
904
+        	// Default not supported on text fields
871 905
         }
872 906
 
873 907
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
874
-        if (! $this->query($sql))
875
-        return -1;
876
-        else
877
-        return 1;
908
+        if (! $this->query($sql)) {
909
+                return -1;
910
+        } else {
911
+                return 1;
912
+        }
878 913
     }
879 914
 
880 915
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -919,8 +954,7 @@  discard block
 block discarded – undo
919 954
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
920 955
             {
921 956
             	return -1;
922
-            }
923
-            else
957
+            } else
924 958
 			{
925 959
             	// If user already exists, we continue to set permissions
926 960
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -1087,11 +1121,15 @@  discard block
 block discarded – undo
1087 1121
         $result=array();
1088 1122
 
1089 1123
         $sql='SHOW VARIABLES';
1090
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1124
+        if ($filter) {
1125
+            $sql.=" LIKE '".$this->escape($filter)."'";
1126
+        }
1091 1127
         $resql=$this->query($sql);
1092 1128
         if ($resql)
1093 1129
         {
1094
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1130
+        	while($obj=$this->fetch_object($resql)) {
1131
+        	    $result[$obj->Variable_name]=$obj->Value;
1132
+        	}
1095 1133
         }
1096 1134
 
1097 1135
         return $result;
@@ -1108,11 +1146,15 @@  discard block
 block discarded – undo
1108 1146
         $result=array();
1109 1147
 
1110 1148
         $sql='SHOW STATUS';
1111
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1149
+        if ($filter) {
1150
+            $sql.=" LIKE '".$this->escape($filter)."'";
1151
+        }
1112 1152
         $resql=$this->query($sql);
1113 1153
         if ($resql)
1114 1154
         {
1115
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1155
+            while($obj=$this->fetch_object($resql)) {
1156
+                $result[$obj->Variable_name]=$obj->Value;
1157
+            }
1116 1158
         }
1117 1159
 
1118 1160
         return $result;
Please login to merge, or discard this patch.
Spacing   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
  * 	\brief      Class file to manage Dolibarr database access for a MySQL database
30 30
  */
31 31
 
32
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
32
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
33 33
 
34 34
 /**
35 35
  *	Class to manage Dolibarr database access for a MySQL database using the MySQLi extension
@@ -39,11 +39,11 @@  discard block
 block discarded – undo
39 39
 	/** @var mysqli Database object */
40 40
 	public $db;
41 41
     //! Database type
42
-    public $type='mysqli';
42
+    public $type = 'mysqli';
43 43
     //! Database label
44
-    const LABEL='MySQL or MariaDB';
44
+    const LABEL = 'MySQL or MariaDB';
45 45
     //! Version min database
46
-    const VERSIONMIN='5.0.3';
46
+    const VERSIONMIN = '5.0.3';
47 47
 	/** @var mysqli_result Resultset of last query */
48 48
 	private $_results;
49 49
 
@@ -58,36 +58,36 @@  discard block
 block discarded – undo
58 58
 	 *	@param	    string	$name		Nom de la database
59 59
 	 *	@param	    int		$port		Port of database server
60 60
      */
61
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
61
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
62 62
     {
63
-        global $conf,$langs;
63
+        global $conf, $langs;
64 64
 
65 65
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
66
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
67
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
66
+        if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
67
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
68 68
 
69
-        $this->database_user=$user;
70
-        $this->database_host=$host;
71
-        $this->database_port=$port;
69
+        $this->database_user = $user;
70
+        $this->database_host = $host;
71
+        $this->database_port = $port;
72 72
 
73
-        $this->transaction_opened=0;
73
+        $this->transaction_opened = 0;
74 74
 
75 75
         //print "Name DB: $host,$user,$pass,$name<br>";
76 76
 
77
-        if (! class_exists('mysqli'))
77
+        if (!class_exists('mysqli'))
78 78
         {
79 79
             $this->connected = false;
80 80
             $this->ok = false;
81
-            $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
82
-            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);
81
+            $this->error = "Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
82
+            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 83
         }
84 84
 
85
-        if (! $host)
85
+        if (!$host)
86 86
         {
87 87
             $this->connected = false;
88 88
             $this->ok = false;
89
-            $this->error=$langs->trans("ErrorWrongHostParameter");
90
-            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
89
+            $this->error = $langs->trans("ErrorWrongHostParameter");
90
+            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters", LOG_ERR);
91 91
         }
92 92
 
93 93
 		// Try server connection
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 			$this->connected = false;
99 99
 			$this->ok = false;
100 100
 			$this->error = $this->db->connect_error;
101
-			dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
101
+			dol_syslog(get_class($this)."::DoliDBMysqli Connect error: ".$this->error, LOG_ERR);
102 102
 		} else {
103 103
 			$this->connected = true;
104 104
 			$this->ok = true;
@@ -114,16 +114,16 @@  discard block
 block discarded – undo
114 114
                 $this->ok = true;
115 115
 
116 116
                 // If client is old latin, we force utf8
117
-                $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
118
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
117
+                $clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
118
+                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
119 119
 
120 120
 				if ($this->db->character_set_name() != $clientmustbe) {
121
-					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
121
+					$this->db->set_charset($clientmustbe); // This set charset, but with a bad collation
122 122
 
123 123
 					$collation = $conf->db->dolibarr_main_db_collation;
124
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
124
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
125 125
 
126
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
126
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
127 127
 				}
128 128
             }
129 129
             else
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
                 $this->database_selected = false;
132 132
                 $this->database_name = '';
133 133
                 $this->ok = false;
134
-                $this->error=$this->error();
135
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
134
+                $this->error = $this->error();
135
+                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error, LOG_ERR);
136 136
             }
137 137
         }
138 138
         else
@@ -143,16 +143,16 @@  discard block
 block discarded – undo
143 143
             if ($this->connected)
144 144
             {
145 145
             	// If client is old latin, we force utf8
146
-            	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
147
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
146
+            	$clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
147
+            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
148 148
 
149 149
 				if ($this->db->character_set_name() != $clientmustbe) {
150
-					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
150
+					$this->db->set_charset($clientmustbe); // This set utf8_general_ci
151 151
 
152 152
 					$collation = $conf->db->dolibarr_main_db_collation;
153
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
153
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
154 154
 
155
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
155
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
156 156
 				}
157 157
 			}
158 158
         }
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
167 167
      *  @return    string   		SQL request line converted
168 168
      */
169
-    static function convertSQLFromMysql($line,$type='ddl')
169
+    static function convertSQLFromMysql($line, $type = 'ddl')
170 170
     {
171 171
         return $line;
172 172
     }
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 */
200 200
 	function connect($host, $login, $passwd, $name, $port = 0)
201 201
 	{
202
-		dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
202
+		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
203 203
 
204 204
 		// Can also be
205 205
 		// mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
@@ -238,8 +238,8 @@  discard block
 block discarded – undo
238 238
     {
239 239
         if ($this->db)
240 240
         {
241
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
242
-            $this->connected=false;
241
+	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
242
+            $this->connected = false;
243 243
             return $this->db->close();
244 244
         }
245 245
         return false;
@@ -254,15 +254,15 @@  discard block
 block discarded – undo
254 254
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
255 255
      *	@return	bool|mysqli_result		Resultset of answer
256 256
      */
257
-    function query($query,$usesavepoint=0,$type='auto')
257
+    function query($query, $usesavepoint = 0, $type = 'auto')
258 258
     {
259 259
     	global $conf;
260 260
 
261 261
         $query = trim($query);
262 262
 
263
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
263
+	    if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
264 264
 
265
-        if (! $this->database_name)
265
+        if (!$this->database_name)
266 266
         {
267 267
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
268 268
             $ret = $this->db->query($query);
@@ -272,19 +272,19 @@  discard block
 block discarded – undo
272 272
             $ret = $this->db->query($query);
273 273
         }
274 274
 
275
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
275
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
276 276
         {
277 277
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
278
-            if (! $ret)
278
+            if (!$ret)
279 279
             {
280 280
                 $this->lastqueryerror = $query;
281 281
                 $this->lasterror = $this->error();
282 282
                 $this->lasterrno = $this->errno();
283 283
 
284
-				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
284
+				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
285 285
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
286 286
             }
287
-            $this->lastquery=$query;
287
+            $this->lastquery = $query;
288 288
             $this->_results = $ret;
289 289
         }
290 290
 
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
     {
303 303
         // phpcs:enable
304 304
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
305
-        if (! is_object($resultset)) { $resultset=$this->_results; }
305
+        if (!is_object($resultset)) { $resultset = $this->_results; }
306 306
 		return $resultset->fetch_object();
307 307
     }
308 308
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
     {
319 319
         // phpcs:enable
320 320
         // If resultset not provided, we take the last used by connexion
321
-        if (! is_object($resultset)) { $resultset=$this->_results; }
321
+        if (!is_object($resultset)) { $resultset = $this->_results; }
322 322
         return $resultset->fetch_array();
323 323
     }
324 324
 
@@ -333,9 +333,9 @@  discard block
 block discarded – undo
333 333
     {
334 334
         // phpcs:enable
335 335
         // If resultset not provided, we take the last used by connexion
336
-        if (! is_bool($resultset))
336
+        if (!is_bool($resultset))
337 337
         {
338
-            if (! is_object($resultset)) { $resultset=$this->_results; }
338
+            if (!is_object($resultset)) { $resultset = $this->_results; }
339 339
             return $resultset->fetch_row();
340 340
         }
341 341
         else
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
     {
358 358
         // phpcs:enable
359 359
         // If resultset not provided, we take the last used by connexion
360
-        if (! is_object($resultset)) { $resultset=$this->_results; }
360
+        if (!is_object($resultset)) { $resultset = $this->_results; }
361 361
         return $resultset->num_rows;
362 362
     }
363 363
 
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
     {
374 374
         // phpcs:enable
375 375
         // If resultset not provided, we take the last used by connexion
376
-        if (! is_object($resultset)) { $resultset=$this->_results; }
376
+        if (!is_object($resultset)) { $resultset = $this->_results; }
377 377
         // mysql necessite un link de base pour cette fonction contrairement
378 378
         // a pqsql qui prend un resultset
379 379
         return $this->db->affected_rows;
@@ -386,10 +386,10 @@  discard block
 block discarded – undo
386 386
      *	@param  mysqli_result	$resultset	Curseur de la requete voulue
387 387
      *	@return	void
388 388
      */
389
-    function free($resultset=null)
389
+    function free($resultset = null)
390 390
     {
391 391
         // If resultset not provided, we take the last used by connexion
392
-        if (! is_object($resultset)) { $resultset=$this->_results; }
392
+        if (!is_object($resultset)) { $resultset = $this->_results; }
393 393
         // Si resultset en est un, on libere la memoire
394 394
         if (is_object($resultset)) $resultset->free_result();
395 395
     }
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
      */
413 413
     function errno()
414 414
     {
415
-        if (! $this->connected) {
415
+        if (!$this->connected) {
416 416
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
417 417
             return 'DB_ERROR_FAILED_TO_CONNECT';
418 418
         } else {
@@ -444,15 +444,15 @@  discard block
 block discarded – undo
444 444
             1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
445 445
             1216 => 'DB_ERROR_NO_PARENT',
446 446
             1217 => 'DB_ERROR_CHILD_EXISTS',
447
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
447
+            1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
448 448
             1451 => 'DB_ERROR_CHILD_EXISTS'
449 449
             );
450 450
 
451 451
             if (isset($errorcode_map[$this->db->errno])) {
452 452
                 return $errorcode_map[$this->db->errno];
453 453
             }
454
-            $errno=$this->db->errno;
455
-            return ($errno?'DB_ERROR_'.$errno:'0');
454
+            $errno = $this->db->errno;
455
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
456 456
         }
457 457
     }
458 458
 
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
      */
464 464
     function error()
465 465
     {
466
-        if (! $this->connected) {
466
+        if (!$this->connected) {
467 467
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
468 468
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
469 469
         }
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
 	 * @param	string	$fieldid	Field name
481 481
 	 * @return  int|string			Id of row
482 482
      */
483
-    function last_insert_id($tab,$fieldid='rowid')
483
+    function last_insert_id($tab, $fieldid = 'rowid')
484 484
     {
485 485
         // phpcs:enable
486 486
         return $this->db->insert_id;
@@ -495,17 +495,17 @@  discard block
 block discarded – undo
495 495
      * 	@return	string					XXX(field) or XXX('value') or field or 'value'
496 496
      *
497 497
      */
498
-    function encrypt($fieldorvalue, $withQuotes=0)
498
+    function encrypt($fieldorvalue, $withQuotes = 0)
499 499
     {
500 500
         global $conf;
501 501
 
502 502
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
503
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
503
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
504 504
 
505 505
         //Encryption key
506
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
506
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
507 507
 
508
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
508
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
509 509
 
510 510
         if ($cryptType && !empty($cryptKey))
511 511
         {
@@ -533,10 +533,10 @@  discard block
 block discarded – undo
533 533
         global $conf;
534 534
 
535 535
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
536
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
536
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
537 537
 
538 538
         //Encryption key
539
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
539
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
540 540
 
541 541
         $return = $value;
542 542
 
@@ -565,10 +565,10 @@  discard block
 block discarded – undo
565 565
     function DDLGetConnectId()
566 566
     {
567 567
         // phpcs:enable
568
-        $resql=$this->query('SELECT CONNECTION_ID()');
568
+        $resql = $this->query('SELECT CONNECTION_ID()');
569 569
         if ($resql)
570 570
         {
571
-            $row=$this->fetch_row($resql);
571
+            $row = $this->fetch_row($resql);
572 572
             return $row[0];
573 573
         }
574 574
         else return '?';
@@ -586,24 +586,24 @@  discard block
 block discarded – undo
586 586
 	 * 	@param	string	$owner			Username of database owner
587 587
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
588 588
      */
589
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
589
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
590 590
     {
591 591
         // phpcs:enable
592
-        if (empty($charset))   $charset=$this->forcecharset;
593
-        if (empty($collation)) $collation=$this->forcecollate;
592
+        if (empty($charset))   $charset = $this->forcecharset;
593
+        if (empty($collation)) $collation = $this->forcecollate;
594 594
 
595 595
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
596 596
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
597
-		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
597
+		$sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
598 598
 
599
-        dol_syslog($sql,LOG_DEBUG);
600
-        $ret=$this->query($sql);
601
-        if (! $ret)
599
+        dol_syslog($sql, LOG_DEBUG);
600
+        $ret = $this->query($sql);
601
+        if (!$ret)
602 602
         {
603 603
             // We try again for compatibility with Mysql < 4.1.1
604 604
             $sql = "CREATE DATABASE `".$this->escape($database)."`";
605
-            dol_syslog($sql,LOG_DEBUG);
606
-            $ret=$this->query($sql);
605
+            dol_syslog($sql, LOG_DEBUG);
606
+            $ret = $this->query($sql);
607 607
         }
608 608
         return $ret;
609 609
     }
@@ -616,19 +616,19 @@  discard block
 block discarded – undo
616 616
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
617 617
 	 *  @return	array					List of tables in an array
618 618
      */
619
-    function DDLListTables($database, $table='')
619
+    function DDLListTables($database, $table = '')
620 620
     {
621 621
         // phpcs:enable
622
-        $listtables=array();
622
+        $listtables = array();
623 623
 
624 624
         $like = '';
625 625
         if ($table) $like = "LIKE '".$table."'";
626
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
626
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
627 627
         //print $sql;
628 628
         $result = $this->query($sql);
629 629
         if ($result)
630 630
         {
631
-            while($row = $this->fetch_row($result))
631
+            while ($row = $this->fetch_row($result))
632 632
             {
633 633
                 $listtables[] = $row[0];
634 634
             }
@@ -646,15 +646,15 @@  discard block
 block discarded – undo
646 646
     function DDLInfoTable($table)
647 647
     {
648 648
         // phpcs:enable
649
-        $infotables=array();
649
+        $infotables = array();
650 650
 
651
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
651
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
652 652
 
653
-        dol_syslog($sql,LOG_DEBUG);
653
+        dol_syslog($sql, LOG_DEBUG);
654 654
         $result = $this->query($sql);
655 655
         if ($result)
656 656
         {
657
-            while($row = $this->fetch_row($result))
657
+            while ($row = $this->fetch_row($result))
658 658
             {
659 659
                 $infotables[] = $row;
660 660
             }
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
676 676
 	 *	@return	    int						<0 if KO, >=0 if OK
677 677
      */
678
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
678
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
679 679
     {
680 680
         // phpcs:enable
681 681
 	    // FIXME: $fulltext_keys parameter is unused
@@ -683,64 +683,64 @@  discard block
 block discarded – undo
683 683
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
684 684
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
685 685
         $sql = "CREATE TABLE ".$table."(";
686
-        $i=0;
687
-        foreach($fields as $field_name => $field_desc)
686
+        $i = 0;
687
+        foreach ($fields as $field_name => $field_desc)
688 688
         {
689 689
         	$sqlfields[$i] = $field_name." ";
690
-			$sqlfields[$i]  .= $field_desc['type'];
691
-			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
690
+			$sqlfields[$i] .= $field_desc['type'];
691
+			if (preg_match("/^[^\s]/i", $field_desc['value'])) {
692 692
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
693 693
 			}
694
-			if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
694
+			if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
695 695
 				$sqlfields[$i]  .= " ".$field_desc['attribute'];
696 696
 			}
697
-			if( preg_match("/^[^\s]/i",$field_desc['default']))
697
+			if (preg_match("/^[^\s]/i", $field_desc['default']))
698 698
 			{
699
-				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
699
+				if ((preg_match("/null/i", $field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i", $field_desc['default']))) {
700 700
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
701 701
 				}
702 702
 				else {
703 703
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
704 704
 				}
705 705
 			}
706
-			if( preg_match("/^[^\s]/i",$field_desc['null'])) {
706
+			if (preg_match("/^[^\s]/i", $field_desc['null'])) {
707 707
 				$sqlfields[$i]  .= " ".$field_desc['null'];
708 708
 			}
709
-			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
709
+			if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
710 710
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
711 711
 			}
712 712
             $i++;
713 713
         }
714
-        if($primary_key != "")
714
+        if ($primary_key != "")
715 715
         $pk = "primary key(".$primary_key.")";
716 716
 
717
-        if(is_array($unique_keys)) {
717
+        if (is_array($unique_keys)) {
718 718
             $i = 0;
719
-            foreach($unique_keys as $key => $value)
719
+            foreach ($unique_keys as $key => $value)
720 720
             {
721 721
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
722 722
                 $i++;
723 723
             }
724 724
         }
725
-        if(is_array($keys))
725
+        if (is_array($keys))
726 726
         {
727 727
             $i = 0;
728
-            foreach($keys as $key => $value)
728
+            foreach ($keys as $key => $value)
729 729
             {
730 730
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
731 731
                 $i++;
732 732
             }
733 733
         }
734
-        $sql .= implode(',',$sqlfields);
735
-        if($primary_key != "")
734
+        $sql .= implode(',', $sqlfields);
735
+        if ($primary_key != "")
736 736
         $sql .= ",".$pk;
737
-        if($unique_keys != "")
738
-        $sql .= ",".implode(',',$sqluq);
739
-        if(is_array($keys))
740
-        $sql .= ",".implode(',',$sqlk);
741
-        $sql .=") engine=".$type;
737
+        if ($unique_keys != "")
738
+        $sql .= ",".implode(',', $sqluq);
739
+        if (is_array($keys))
740
+        $sql .= ",".implode(',', $sqlk);
741
+        $sql .= ") engine=".$type;
742 742
 
743
-        if(! $this->query($sql))
743
+        if (!$this->query($sql))
744 744
         return -1;
745 745
         else
746 746
         return 1;
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
         // phpcs:enable
759 759
         $sql = "DROP TABLE ".$table;
760 760
 
761
-		if (! $this->query($sql))
761
+		if (!$this->query($sql))
762 762
  			return -1;
763 763
     	else
764 764
     		return 1;
@@ -772,12 +772,12 @@  discard block
 block discarded – undo
772 772
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
773 773
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
774 774
      */
775
-    function DDLDescTable($table,$field="")
775
+    function DDLDescTable($table, $field = "")
776 776
     {
777 777
         // phpcs:enable
778
-        $sql="DESC ".$table." ".$field;
778
+        $sql = "DESC ".$table." ".$field;
779 779
 
780
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
780
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
781 781
         $this->_results = $this->query($sql);
782 782
         return $this->_results;
783 783
     }
@@ -792,42 +792,42 @@  discard block
 block discarded – undo
792 792
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
793 793
 	 *	@return	int							<0 if KO, >0 if OK
794 794
      */
795
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
795
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
796 796
     {
797 797
         // phpcs:enable
798 798
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
799 799
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
800
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
801
-        $sql.= $field_desc['type'];
802
-        if (preg_match("/^[^\s]/i",$field_desc['value']))
800
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
801
+        $sql .= $field_desc['type'];
802
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
803 803
         {
804
-            if (! in_array($field_desc['type'],array('date','datetime')))
804
+            if (!in_array($field_desc['type'], array('date', 'datetime')))
805 805
             {
806
-                $sql.= "(".$field_desc['value'].")";
806
+                $sql .= "(".$field_desc['value'].")";
807 807
             }
808 808
         }
809
-        if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i",$field_desc['attribute']))
809
+        if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute']))
810 810
         {
811
-        	$sql.= " ".$field_desc['attribute'];
811
+        	$sql .= " ".$field_desc['attribute'];
812 812
         }
813
-        if (isset($field_desc['null']) && preg_match("/^[^\s]/i",$field_desc['null']))
813
+        if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null']))
814 814
         {
815
-        	$sql.= " ".$field_desc['null'];
815
+        	$sql .= " ".$field_desc['null'];
816 816
         }
817
-        if (isset($field_desc['default']) && preg_match("/^[^\s]/i",$field_desc['default']))
817
+        if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default']))
818 818
         {
819
-            if(preg_match("/null/i",$field_desc['default']))
820
-            $sql.= " default ".$field_desc['default'];
819
+            if (preg_match("/null/i", $field_desc['default']))
820
+            $sql .= " default ".$field_desc['default'];
821 821
             else
822
-            $sql.= " default '".$field_desc['default']."'";
822
+            $sql .= " default '".$field_desc['default']."'";
823 823
         }
824
-        if (isset($field_desc['extra']) && preg_match("/^[^\s]/i",$field_desc['extra']))
824
+        if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra']))
825 825
         {
826
-        	$sql.= " ".$field_desc['extra'];
826
+        	$sql .= " ".$field_desc['extra'];
827 827
         }
828
-        $sql.= " ".$field_position;
828
+        $sql .= " ".$field_position;
829 829
 
830
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
830
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
831 831
         if ($this->query($sql)) {
832 832
             return 1;
833 833
         }
@@ -843,39 +843,39 @@  discard block
 block discarded – undo
843 843
 	 *	@param	string	$field_desc 		Array with description of field format
844 844
 	 *	@return	int							<0 if KO, >0 if OK
845 845
      */
846
-    function DDLUpdateField($table,$field_name,$field_desc)
846
+    function DDLUpdateField($table, $field_name, $field_desc)
847 847
     {
848 848
         // phpcs:enable
849 849
         $sql = "ALTER TABLE ".$table;
850 850
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
851 851
         if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
852
-        	$sql.="(".$field_desc['value'].")";
852
+        	$sql .= "(".$field_desc['value'].")";
853 853
         }
854 854
         if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
855 855
         {
856 856
         	// 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
857 857
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
858 858
         	{
859
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
859
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
860 860
         		$this->query($sqlbis);
861 861
         	}
862 862
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
863 863
         	{
864
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
864
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
865 865
         		$this->query($sqlbis);
866 866
         	}
867 867
 
868
-        	$sql.=" NOT NULL";
868
+        	$sql .= " NOT NULL";
869 869
         }
870 870
 
871 871
         if ($field_desc['default'] != '')
872 872
         {
873
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
874
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
873
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
874
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
875 875
         }
876 876
 
877
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
878
-        if (! $this->query($sql))
877
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
878
+        if (!$this->query($sql))
879 879
         return -1;
880 880
         else
881 881
         return 1;
@@ -889,15 +889,15 @@  discard block
 block discarded – undo
889 889
 	 *	@param	string	$field_name 	Name of field to drop
890 890
 	 *	@return	int						<0 if KO, >0 if OK
891 891
      */
892
-    function DDLDropField($table,$field_name)
892
+    function DDLDropField($table, $field_name)
893 893
     {
894 894
         // phpcs:enable
895
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
896
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
895
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
896
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
897 897
         if ($this->query($sql)) {
898 898
             return 1;
899 899
         }
900
-        $this->error=$this->lasterror();
900
+        $this->error = $this->lasterror();
901 901
         return -1;
902 902
     }
903 903
 
@@ -912,13 +912,13 @@  discard block
 block discarded – undo
912 912
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
913 913
 	 *	@return	int									<0 if KO, >=0 if OK
914 914
      */
915
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
915
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
916 916
     {
917 917
         // phpcs:enable
918 918
         $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
919
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
920
-        $resql=$this->query($sql);
921
-        if (! $resql)
919
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
920
+        $resql = $this->query($sql);
921
+        if (!$resql)
922 922
         {
923 923
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
924 924
             {
@@ -931,18 +931,18 @@  discard block
 block discarded – undo
931 931
             }
932 932
         }
933 933
         $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)."'";
934
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
935
-        $resql=$this->query($sql);
936
-        if (! $resql)
934
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
935
+        $resql = $this->query($sql);
936
+        if (!$resql)
937 937
         {
938 938
             return -1;
939 939
         }
940 940
 
941
-        $sql="FLUSH Privileges";
941
+        $sql = "FLUSH Privileges";
942 942
 
943 943
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
944
-        $resql=$this->query($sql);
945
-        if (! $resql)
944
+        $resql = $this->query($sql);
945
+        if (!$resql)
946 946
         {
947 947
             return -1;
948 948
         }
@@ -959,13 +959,13 @@  discard block
 block discarded – undo
959 959
      */
960 960
     function getDefaultCharacterSetDatabase()
961 961
     {
962
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
962
+        $resql = $this->query('SHOW VARIABLES LIKE \'character_set_database\'');
963 963
         if (!$resql)
964 964
         {
965 965
             // version Mysql < 4.1.1
966 966
             return $this->forcecharset;
967 967
         }
968
-        $liste=$this->fetch_array($resql);
968
+        $liste = $this->fetch_array($resql);
969 969
         $tmpval = $liste['Value'];
970 970
 
971 971
         return $tmpval;
@@ -978,12 +978,12 @@  discard block
 block discarded – undo
978 978
      */
979 979
     function getListOfCharacterSet()
980 980
     {
981
-        $resql=$this->query('SHOW CHARSET');
981
+        $resql = $this->query('SHOW CHARSET');
982 982
         $liste = array();
983 983
         if ($resql)
984 984
         {
985 985
             $i = 0;
986
-            while ($obj = $this->fetch_object($resql) )
986
+            while ($obj = $this->fetch_object($resql))
987 987
             {
988 988
                 $liste[$i]['charset'] = $obj->Charset;
989 989
                 $liste[$i]['description'] = $obj->Description;
@@ -1005,13 +1005,13 @@  discard block
 block discarded – undo
1005 1005
      */
1006 1006
     function getDefaultCollationDatabase()
1007 1007
     {
1008
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
1008
+        $resql = $this->query('SHOW VARIABLES LIKE \'collation_database\'');
1009 1009
         if (!$resql)
1010 1010
         {
1011 1011
             // version Mysql < 4.1.1
1012 1012
             return $this->forcecollate;
1013 1013
         }
1014
-        $liste=$this->fetch_array($resql);
1014
+        $liste = $this->fetch_array($resql);
1015 1015
         $tmpval = $liste['Value'];
1016 1016
 
1017 1017
         return $tmpval;
@@ -1024,12 +1024,12 @@  discard block
 block discarded – undo
1024 1024
      */
1025 1025
     function getListOfCollation()
1026 1026
     {
1027
-        $resql=$this->query('SHOW COLLATION');
1027
+        $resql = $this->query('SHOW COLLATION');
1028 1028
         $liste = array();
1029 1029
         if ($resql)
1030 1030
         {
1031 1031
             $i = 0;
1032
-            while ($obj = $this->fetch_object($resql) )
1032
+            while ($obj = $this->fetch_object($resql))
1033 1033
             {
1034 1034
                 $liste[$i]['collation'] = $obj->Collation;
1035 1035
                 $i++;
@@ -1049,14 +1049,14 @@  discard block
 block discarded – undo
1049 1049
      */
1050 1050
     function getPathOfDump()
1051 1051
     {
1052
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1052
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1053 1053
 
1054
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1054
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1055 1055
         if ($resql)
1056 1056
         {
1057
-            $liste=$this->fetch_array($resql);
1058
-            $basedir=$liste['Value'];
1059
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1057
+            $liste = $this->fetch_array($resql);
1058
+            $basedir = $liste['Value'];
1059
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1060 1060
         }
1061 1061
         return $fullpathofdump;
1062 1062
     }
@@ -1068,14 +1068,14 @@  discard block
 block discarded – undo
1068 1068
      */
1069 1069
     function getPathOfRestore()
1070 1070
     {
1071
-        $fullpathofimport='/pathtomysql/mysql';
1071
+        $fullpathofimport = '/pathtomysql/mysql';
1072 1072
 
1073
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1073
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1074 1074
         if ($resql)
1075 1075
         {
1076
-            $liste=$this->fetch_array($resql);
1077
-            $basedir=$liste['Value'];
1078
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1076
+            $liste = $this->fetch_array($resql);
1077
+            $basedir = $liste['Value'];
1078
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1079 1079
         }
1080 1080
         return $fullpathofimport;
1081 1081
     }
@@ -1086,16 +1086,16 @@  discard block
 block discarded – undo
1086 1086
      * @param	string	$filter		Filter list on a particular value
1087 1087
 	 * @return	array				Array of key-values (key=>value)
1088 1088
      */
1089
-    function getServerParametersValues($filter='')
1089
+    function getServerParametersValues($filter = '')
1090 1090
     {
1091
-        $result=array();
1091
+        $result = array();
1092 1092
 
1093
-        $sql='SHOW VARIABLES';
1094
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1095
-        $resql=$this->query($sql);
1093
+        $sql = 'SHOW VARIABLES';
1094
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1095
+        $resql = $this->query($sql);
1096 1096
         if ($resql)
1097 1097
         {
1098
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1098
+        	while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1099 1099
         }
1100 1100
 
1101 1101
         return $result;
@@ -1107,16 +1107,16 @@  discard block
 block discarded – undo
1107 1107
      * @param	string	$filter		Filter list on a particular value
1108 1108
 	 * @return  array				Array of key-values (key=>value)
1109 1109
      */
1110
-    function getServerStatusValues($filter='')
1110
+    function getServerStatusValues($filter = '')
1111 1111
     {
1112
-        $result=array();
1112
+        $result = array();
1113 1113
 
1114
-        $sql='SHOW STATUS';
1115
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1116
-        $resql=$this->query($sql);
1114
+        $sql = 'SHOW STATUS';
1115
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1116
+        $resql = $this->query($sql);
1117 1117
         if ($resql)
1118 1118
         {
1119
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1119
+            while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1120 1120
         }
1121 1121
 
1122 1122
         return $result;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/Database.interface.php 2 patches
Indentation   +390 added lines, -390 removed lines patch added patch discarded remove patch
@@ -25,479 +25,479 @@
 block discarded – undo
25 25
  */
26 26
 interface Database
27 27
 {
28
-	/**
29
-	 * Format a SQL IF
30
-	 *
31
-	 * @param   string $test Test string (example: 'cd.statut=0', 'field IS NULL')
32
-	 * @param   string $resok resultat si test egal
33
-	 * @param   string $resko resultat si test non egal
34
-	 * @return	string                SQL string
35
-	 */
36
-	function ifsql($test, $resok, $resko);
28
+    /**
29
+     * Format a SQL IF
30
+     *
31
+     * @param   string $test Test string (example: 'cd.statut=0', 'field IS NULL')
32
+     * @param   string $resok resultat si test egal
33
+     * @param   string $resko resultat si test non egal
34
+     * @return	string                SQL string
35
+     */
36
+    function ifsql($test, $resok, $resko);
37 37
 
38 38
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
39
-	/**
40
-	 * Return datas as an array
41
-	 *
42
-	 * @param   resource $resultset Resultset of request
43
-	 * @return  array                    Array
44
-	 */
39
+    /**
40
+     * Return datas as an array
41
+     *
42
+     * @param   resource $resultset Resultset of request
43
+     * @return  array                    Array
44
+     */
45 45
     function fetch_row($resultset);
46 46
     // phpcs:enable
47 47
 
48
-	/**
49
-	 * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
50
-	 * Function to use to build INSERT, UPDATE or WHERE predica
51
-	 *
52
-	 * @param   int		$param 		Date TMS to convert
53
-	 * @return  string            	Date in a string YYYYMMDDHHMMSS
54
-	 */
55
-	function idate($param);
56
-
57
-	/**
58
-	 * Return last error code
59
-	 *
60
-	 * @return  string    lasterrno
61
-	 */
62
-	function lasterrno();
63
-
64
-	/**
65
-	 * Start transaction
66
-	 *
67
-	 * @return  int         1 if transaction successfuly opened or already opened, 0 if error
68
-	 */
69
-	function begin();
48
+    /**
49
+     * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
50
+     * Function to use to build INSERT, UPDATE or WHERE predica
51
+     *
52
+     * @param   int		$param 		Date TMS to convert
53
+     * @return  string            	Date in a string YYYYMMDDHHMMSS
54
+     */
55
+    function idate($param);
56
+
57
+    /**
58
+     * Return last error code
59
+     *
60
+     * @return  string    lasterrno
61
+     */
62
+    function lasterrno();
63
+
64
+    /**
65
+     * Start transaction
66
+     *
67
+     * @return  int         1 if transaction successfuly opened or already opened, 0 if error
68
+     */
69
+    function begin();
70 70
 
71 71
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
72
-	/**
73
-	 * Create a new database
74
-	 * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
75
-	 * We force to create database with charset this->forcecharset and collate this->forcecollate
76
-	 *
77
-	 * @param   string 		$database 		Database name to create
78
-	 * @param   string 		$charset 		Charset used to store data
79
-	 * @param   string 		$collation 		Charset used to sort data
80
-	 * @param   string 		$owner 			Username of database owner
81
-	 * @return  resource                	resource defined if OK, null if KO
82
-	 */
72
+    /**
73
+     * Create a new database
74
+     * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
75
+     * We force to create database with charset this->forcecharset and collate this->forcecollate
76
+     *
77
+     * @param   string 		$database 		Database name to create
78
+     * @param   string 		$charset 		Charset used to store data
79
+     * @param   string 		$collation 		Charset used to sort data
80
+     * @param   string 		$owner 			Username of database owner
81
+     * @return  resource                	resource defined if OK, null if KO
82
+     */
83 83
     function DDLCreateDb($database, $charset = '', $collation = '', $owner = '');
84 84
     // phpcs:enable
85 85
 
86
-	/**
87
-	 * Return version of database server into an array
88
-	 *
89
-	 * @return	array        Version array
90
-	 */
91
-	function getVersionArray();
92
-
93
-	/**
94
-	 *  Convert a SQL request in Mysql syntax to native syntax
95
-	 *
96
-	 * @param   string $line SQL request line to convert
97
-	 * @param   string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
98
-	 * @return  string        SQL request line converted
99
-	 */
100
-	static function convertSQLFromMysql($line, $type = 'ddl');
86
+    /**
87
+     * Return version of database server into an array
88
+     *
89
+     * @return	array        Version array
90
+     */
91
+    function getVersionArray();
92
+
93
+    /**
94
+     *  Convert a SQL request in Mysql syntax to native syntax
95
+     *
96
+     * @param   string $line SQL request line to convert
97
+     * @param   string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
98
+     * @return  string        SQL request line converted
99
+     */
100
+    static function convertSQLFromMysql($line, $type = 'ddl');
101 101
 
102 102
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
103
-	/**
104
-	 * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
105
-	 *
106
-	 * @param   resource $resultset Curseur de la requete voulue
107
-	 * @return 	int            Nombre de lignes
108
-	 * @see    	num_rows
109
-	 */
103
+    /**
104
+     * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
105
+     *
106
+     * @param   resource $resultset Curseur de la requete voulue
107
+     * @return 	int            Nombre de lignes
108
+     * @see    	num_rows
109
+     */
110 110
     function affected_rows($resultset);
111 111
     // phpcs:enable
112 112
 
113
-	/**
114
-	 * Return description of last error
115
-	 *
116
-	 * @return  string        Error text
117
-	 */
118
-	function error();
113
+    /**
114
+     * Return description of last error
115
+     *
116
+     * @return  string        Error text
117
+     */
118
+    function error();
119 119
 
120 120
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
121
-	/**
122
-	 *  List tables into a database
123
-	 *
124
-	 *  @param	string		$database	Name of database
125
-	 *  @param	string		$table		Nmae of table filter ('xxx%')
126
-	 *  @return	array					List of tables in an array
127
-	 */
121
+    /**
122
+     *  List tables into a database
123
+     *
124
+     *  @param	string		$database	Name of database
125
+     *  @param	string		$table		Nmae of table filter ('xxx%')
126
+     *  @return	array					List of tables in an array
127
+     */
128 128
     function DDLListTables($database, $table = '');
129 129
     // phpcs:enable
130 130
 
131
-	/**
132
-	 * Return last request executed with query()
133
-	 *
134
-	 * @return	string                    Last query
135
-	 */
136
-	function lastquery();
137
-
138
-	/**
139
-	 * Define sort criteria of request
140
-	 *
141
-	 * @param   string $sortfield List of sort fields
142
-	 * @param   string $sortorder Sort order
143
-	 * @return  string            String to provide syntax of a sort sql string
144
-	 */
145
-	function order($sortfield = null, $sortorder = null);
146
-
147
-	/**
148
-	 * Decrypt sensitive data in database
149
-	 *
150
-	 * @param    string $value Value to decrypt
151
-	 * @return   string                    Decrypted value if used
152
-	 */
153
-	function decrypt($value);
131
+    /**
132
+     * Return last request executed with query()
133
+     *
134
+     * @return	string                    Last query
135
+     */
136
+    function lastquery();
137
+
138
+    /**
139
+     * Define sort criteria of request
140
+     *
141
+     * @param   string $sortfield List of sort fields
142
+     * @param   string $sortorder Sort order
143
+     * @return  string            String to provide syntax of a sort sql string
144
+     */
145
+    function order($sortfield = null, $sortorder = null);
146
+
147
+    /**
148
+     * Decrypt sensitive data in database
149
+     *
150
+     * @param    string $value Value to decrypt
151
+     * @return   string                    Decrypted value if used
152
+     */
153
+    function decrypt($value);
154 154
 
155 155
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
156
-	/**
157
-	 *    Return datas as an array
158
-	 *
159
-	 * @param   resource $resultset Resultset of request
160
-	 * @return  array                    Array
161
-	 */
156
+    /**
157
+     *    Return datas as an array
158
+     *
159
+     * @param   resource $resultset Resultset of request
160
+     * @return  array                    Array
161
+     */
162 162
     function fetch_array($resultset);
163 163
     // phpcs:enable
164 164
 
165
-	/**
166
-	 * Return last error label
167
-	 *
168
-	 * @return	string    lasterror
169
-	 */
170
-	function lasterror();
171
-
172
-	/**
173
-	 * Escape a string to insert data
174
-	 *
175
-	 * @param   string $stringtoencode String to escape
176
-	 * @return  string                        String escaped
177
-	 */
178
-	function escape($stringtoencode);
165
+    /**
166
+     * Return last error label
167
+     *
168
+     * @return	string    lasterror
169
+     */
170
+    function lasterror();
171
+
172
+    /**
173
+     * Escape a string to insert data
174
+     *
175
+     * @param   string $stringtoencode String to escape
176
+     * @return  string                        String escaped
177
+     */
178
+    function escape($stringtoencode);
179 179
 
180 180
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
181
-	/**
182
-	 * Get last ID after an insert INSERT
183
-	 *
184
-	 * @param	string 	$tab 		Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
185
-	 * @param   string 	$fieldid 	Field name
186
-	 * @return  int                	Id of row
187
-	 */
181
+    /**
182
+     * Get last ID after an insert INSERT
183
+     *
184
+     * @param	string 	$tab 		Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
185
+     * @param   string 	$fieldid 	Field name
186
+     * @return  int                	Id of row
187
+     */
188 188
     function last_insert_id($tab, $fieldid = 'rowid');
189 189
     // phpcs:enable
190 190
 
191
-	/**
192
-	 *    Return full path of restore program
193
-	 *
194
-	 * @return        string        Full path of restore program
195
-	 */
196
-	function getPathOfRestore();
197
-
198
-	/**
199
-	 *    Annulation d'une transaction et retour aux anciennes valeurs
200
-	 *
201
-	 * @param	string $log Add more log to default log line
202
-	 * @return  int                1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
203
-	 */
204
-	function rollback($log = '');
205
-
206
-	/**
207
-	 * Execute a SQL request and return the resultset
208
-	 *
209
-	 * @param   string $query SQL query string
210
-	 * @param   int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
211
-	 *                            Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
212
-	 * @param   string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
213
-	 * @return  resource                Resultset of answer
214
-	 */
215
-	function query($query, $usesavepoint = 0, $type = 'auto');
216
-
217
-	/**
218
-	 *    Connexion to server
219
-	 *
220
-	 * @param   string $host database server host
221
-	 * @param   string $login login
222
-	 * @param   string $passwd password
223
-	 * @param   string $name name of database (not used for mysql, used for pgsql)
224
-	 * @param   int    $port Port of database server
225
-	 * @return  resource            Database access handler
226
-	 * @see     close
227
-	 */
228
-	function connect($host, $login, $passwd, $name, $port = 0);
229
-
230
-	/**
231
-	 *    Define limits and offset of request
232
-	 *
233
-	 * @param   int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
234
-	 * @param   int $offset Numero of line from where starting fetch
235
-	 * @return  string            String with SQL syntax to add a limit and offset
236
-	 */
237
-	function plimit($limit = 0, $offset = 0);
238
-
239
-	/**
240
-	 * Return value of server parameters
241
-	 *
242
-	 * @param   string	$filter		Filter list on a particular value
243
-	 * @return  array				Array of key-values (key=>value)
244
-	 */
245
-	function getServerParametersValues($filter = '');
246
-
247
-	/**
248
-	 * Return value of server status
249
-	 *
250
-	 * @param   string $filter 		Filter list on a particular value
251
-	 * @return  array				Array of key-values (key=>value)
252
-	 */
253
-	function getServerStatusValues($filter = '');
254
-
255
-	/**
256
-	 * Return collation used in database
257
-	 *
258
-	 * @return  string        Collation value
259
-	 */
260
-	function getDefaultCollationDatabase();
191
+    /**
192
+     *    Return full path of restore program
193
+     *
194
+     * @return        string        Full path of restore program
195
+     */
196
+    function getPathOfRestore();
197
+
198
+    /**
199
+     *    Annulation d'une transaction et retour aux anciennes valeurs
200
+     *
201
+     * @param	string $log Add more log to default log line
202
+     * @return  int                1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
203
+     */
204
+    function rollback($log = '');
205
+
206
+    /**
207
+     * Execute a SQL request and return the resultset
208
+     *
209
+     * @param   string $query SQL query string
210
+     * @param   int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
211
+     *                            Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
212
+     * @param   string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
213
+     * @return  resource                Resultset of answer
214
+     */
215
+    function query($query, $usesavepoint = 0, $type = 'auto');
216
+
217
+    /**
218
+     *    Connexion to server
219
+     *
220
+     * @param   string $host database server host
221
+     * @param   string $login login
222
+     * @param   string $passwd password
223
+     * @param   string $name name of database (not used for mysql, used for pgsql)
224
+     * @param   int    $port Port of database server
225
+     * @return  resource            Database access handler
226
+     * @see     close
227
+     */
228
+    function connect($host, $login, $passwd, $name, $port = 0);
229
+
230
+    /**
231
+     *    Define limits and offset of request
232
+     *
233
+     * @param   int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
234
+     * @param   int $offset Numero of line from where starting fetch
235
+     * @return  string            String with SQL syntax to add a limit and offset
236
+     */
237
+    function plimit($limit = 0, $offset = 0);
238
+
239
+    /**
240
+     * Return value of server parameters
241
+     *
242
+     * @param   string	$filter		Filter list on a particular value
243
+     * @return  array				Array of key-values (key=>value)
244
+     */
245
+    function getServerParametersValues($filter = '');
246
+
247
+    /**
248
+     * Return value of server status
249
+     *
250
+     * @param   string $filter 		Filter list on a particular value
251
+     * @return  array				Array of key-values (key=>value)
252
+     */
253
+    function getServerStatusValues($filter = '');
254
+
255
+    /**
256
+     * Return collation used in database
257
+     *
258
+     * @return  string        Collation value
259
+     */
260
+    function getDefaultCollationDatabase();
261 261
 
262 262
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
263
-	/**
264
-	 * Return number of lines for result of a SELECT
265
-	 *
266
-	 * @param   resource $resultset Resulset of requests
267
-	 * @return 	int                        Nb of lines
268
-	 * @see    	affected_rows
269
-	 */
263
+    /**
264
+     * Return number of lines for result of a SELECT
265
+     *
266
+     * @param   resource $resultset Resulset of requests
267
+     * @return 	int                        Nb of lines
268
+     * @see    	affected_rows
269
+     */
270 270
     function num_rows($resultset);
271 271
     // phpcs:enable
272 272
 
273
-	/**
274
-	 * Return full path of dump program
275
-	 *
276
-	 * @return        string        Full path of dump program
277
-	 */
278
-	function getPathOfDump();
279
-
280
-	/**
281
-	 * Return version of database client driver
282
-	 *
283
-	 * @return            string      Version string
284
-	 */
285
-	function getDriverInfo();
286
-
287
-	/**
288
-	 * Return generic error code of last operation.
289
-	 *
290
-	 * @return    string        Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
291
-	 */
292
-	function errno();
273
+    /**
274
+     * Return full path of dump program
275
+     *
276
+     * @return        string        Full path of dump program
277
+     */
278
+    function getPathOfDump();
279
+
280
+    /**
281
+     * Return version of database client driver
282
+     *
283
+     * @return            string      Version string
284
+     */
285
+    function getDriverInfo();
286
+
287
+    /**
288
+     * Return generic error code of last operation.
289
+     *
290
+     * @return    string        Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
291
+     */
292
+    function errno();
293 293
 
294 294
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
295
-	/**
296
-	 * Create a table into database
297
-	 *
298
-	 * @param        string $table 			Name of table
299
-	 * @param        array 	$fields 		Tableau associatif [nom champ][tableau des descriptions]
300
-	 * @param        string $primary_key 	Nom du champ qui sera la clef primaire
301
-	 * @param        string $type 			Type de la table
302
-	 * @param        array 	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
303
-	 * @param        array 	$fulltext_keys 	Tableau des Nom de champs qui seront indexes en fulltext
304
-	 * @param        array $keys 			Tableau des champs cles noms => valeur
305
-	 * @return       int                    <0 if KO, >=0 if OK
306
-	 */
295
+    /**
296
+     * Create a table into database
297
+     *
298
+     * @param        string $table 			Name of table
299
+     * @param        array 	$fields 		Tableau associatif [nom champ][tableau des descriptions]
300
+     * @param        string $primary_key 	Nom du champ qui sera la clef primaire
301
+     * @param        string $type 			Type de la table
302
+     * @param        array 	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
303
+     * @param        array 	$fulltext_keys 	Tableau des Nom de champs qui seront indexes en fulltext
304
+     * @param        array $keys 			Tableau des champs cles noms => valeur
305
+     * @return       int                    <0 if KO, >=0 if OK
306
+     */
307 307
     function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null);
308 308
     // phpcs:enable
309 309
 
310 310
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
311
-	/**
312
-	 * Drop a table into database
313
-	 *
314
-	 * @param        string $table 			Name of table
315
-	 * @return       int                    <0 if KO, >=0 if OK
316
-	 */
311
+    /**
312
+     * Drop a table into database
313
+     *
314
+     * @param        string $table 			Name of table
315
+     * @return       int                    <0 if KO, >=0 if OK
316
+     */
317 317
     function DDLDropTable($table);
318 318
     // phpcs:enable
319 319
 
320
-	/**
321
-	 * Return list of available charset that can be used to store data in database
322
-	 *
323
-	 * @return        array        List of Charset
324
-	 */
325
-	function getListOfCharacterSet();
320
+    /**
321
+     * Return list of available charset that can be used to store data in database
322
+     *
323
+     * @return        array        List of Charset
324
+     */
325
+    function getListOfCharacterSet();
326 326
 
327 327
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
328
-	/**
329
-	 * Create a new field into table
330
-	 *
331
-	 * @param    string $table 				Name of table
332
-	 * @param    string $field_name 		Name of field to add
333
-	 * @param    string $field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
334
-	 * @param    string $field_position 	Optionnel ex.: "after champtruc"
335
-	 * @return   int                        <0 if KO, >0 if OK
336
-	 */
328
+    /**
329
+     * Create a new field into table
330
+     *
331
+     * @param    string $table 				Name of table
332
+     * @param    string $field_name 		Name of field to add
333
+     * @param    string $field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
334
+     * @param    string $field_position 	Optionnel ex.: "after champtruc"
335
+     * @return   int                        <0 if KO, >0 if OK
336
+     */
337 337
     function DDLAddField($table, $field_name, $field_desc, $field_position = "");
338 338
     // phpcs:enable
339 339
 
340 340
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
341
-	/**
342
-	 * Drop a field from table
343
-	 *
344
-	 * @param    string $table 				Name of table
345
-	 * @param    string $field_name 		Name of field to drop
346
-	 * @return   int                        <0 if KO, >0 if OK
347
-	 */
341
+    /**
342
+     * Drop a field from table
343
+     *
344
+     * @param    string $table 				Name of table
345
+     * @param    string $field_name 		Name of field to drop
346
+     * @return   int                        <0 if KO, >0 if OK
347
+     */
348 348
     function DDLDropField($table, $field_name);
349 349
     // phpcs:enable
350 350
 
351 351
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
352
-	/**
353
-	 * Update format of a field into a table
354
-	 *
355
-	 * @param    string 	$table 			Name of table
356
-	 * @param    string 	$field_name 	Name of field to modify
357
-	 * @param    string 	$field_desc 	Array with description of field format
358
-	 * @return   int                        <0 if KO, >0 if OK
359
-	 */
352
+    /**
353
+     * Update format of a field into a table
354
+     *
355
+     * @param    string 	$table 			Name of table
356
+     * @param    string 	$field_name 	Name of field to modify
357
+     * @param    string 	$field_desc 	Array with description of field format
358
+     * @return   int                        <0 if KO, >0 if OK
359
+     */
360 360
     function DDLUpdateField($table, $field_name, $field_desc);
361 361
     // phpcs:enable
362 362
 
363
-	/**
364
-	 * Return list of available collation that can be used for database
365
-	 *
366
-	 * @return        array        			List of Collation
367
-	 */
368
-	function getListOfCollation();
363
+    /**
364
+     * Return list of available collation that can be used for database
365
+     *
366
+     * @return        array        			List of Collation
367
+     */
368
+    function getListOfCollation();
369 369
 
370 370
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
371
-	/**
372
-	 * Return a pointer of line with description of a table or field
373
-	 *
374
-	 * @param    string 	$table 			Name of table
375
-	 * @param    string 	$field 			Optionnel : Name of field if we want description of field
376
-	 * @return   resource            		Resource
377
-	 */
371
+    /**
372
+     * Return a pointer of line with description of a table or field
373
+     *
374
+     * @param    string 	$table 			Name of table
375
+     * @param    string 	$field 			Optionnel : Name of field if we want description of field
376
+     * @return   resource            		Resource
377
+     */
378 378
     function DDLDescTable($table, $field = "");
379 379
     // phpcs:enable
380 380
 
381
-	/**
382
-	 * Return version of database server
383
-	 *
384
-	 * @return            string      		Version string
385
-	 */
386
-	function getVersion();
381
+    /**
382
+     * Return version of database server
383
+     *
384
+     * @return            string      		Version string
385
+     */
386
+    function getVersion();
387 387
 
388
-	/**
389
-	 * Return charset used to store data in database
390
-	 *
391
-	 * @return        string        		Charset
392
-	 */
393
-	function getDefaultCharacterSetDatabase();
388
+    /**
389
+     * Return charset used to store data in database
390
+     *
391
+     * @return        string        		Charset
392
+     */
393
+    function getDefaultCharacterSetDatabase();
394 394
 
395 395
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
396
-	/**
397
-	 * Create a user and privileges to connect to database (even if database does not exists yet)
398
-	 *
399
-	 * @param    string $dolibarr_main_db_host 	Ip serveur
400
-	 * @param    string $dolibarr_main_db_user 	Nom user a creer
401
-	 * @param    string $dolibarr_main_db_pass 	Mot de passe user a creer
402
-	 * @param    string $dolibarr_main_db_name 	Database name where user must be granted
403
-	 * @return   int                            <0 if KO, >=0 if OK
404
-	 */
405
-	function DDLCreateUser(
406
-		$dolibarr_main_db_host,
407
-		$dolibarr_main_db_user,
408
-		$dolibarr_main_db_pass,
409
-		$dolibarr_main_db_name
396
+    /**
397
+     * Create a user and privileges to connect to database (even if database does not exists yet)
398
+     *
399
+     * @param    string $dolibarr_main_db_host 	Ip serveur
400
+     * @param    string $dolibarr_main_db_user 	Nom user a creer
401
+     * @param    string $dolibarr_main_db_pass 	Mot de passe user a creer
402
+     * @param    string $dolibarr_main_db_name 	Database name where user must be granted
403
+     * @return   int                            <0 if KO, >=0 if OK
404
+     */
405
+    function DDLCreateUser(
406
+        $dolibarr_main_db_host,
407
+        $dolibarr_main_db_user,
408
+        $dolibarr_main_db_pass,
409
+        $dolibarr_main_db_name
410 410
     );
411 411
     // phpcs:enable
412 412
 
413
-	/**
414
-	 * Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
415
-	 * 19700101020000 -> 3600 with TZ+1 and gmt=0
416
-	 * 19700101020000 -> 7200 whaterver is TZ if gmt=1
417
-	 *
418
-	 * @param	string			$string		Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
419
-	 * @param	bool			$gm			1=Input informations are GMT values, otherwise local to server TZ
420
-	 * @return	int|string					Date TMS or ''
421
-	 */
422
-	function jdate($string, $gm=false);
423
-
424
-	/**
425
-	 * Encrypt sensitive data in database
426
-	 * Warning: This function includes the escape, so it must use direct value
427
-	 *
428
-	 * @param   string 			$fieldorvalue 	Field name or value to encrypt
429
-	 * @param  	int 			$withQuotes 	Return string with quotes
430
-	 * @return 	string                     		XXX(field) or XXX('value') or field or 'value'
431
-	 */
432
-	function encrypt($fieldorvalue, $withQuotes = 0);
433
-
434
-	/**
435
-	 * Validate a database transaction
436
-	 *
437
-	 * @param   string 			$log 			Add more log to default log line
438
-	 * @return	int                				1 if validation is OK or transaction level no started, 0 if ERROR
439
-	 */
440
-	function commit($log = '');
413
+    /**
414
+     * Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
415
+     * 19700101020000 -> 3600 with TZ+1 and gmt=0
416
+     * 19700101020000 -> 7200 whaterver is TZ if gmt=1
417
+     *
418
+     * @param	string			$string		Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
419
+     * @param	bool			$gm			1=Input informations are GMT values, otherwise local to server TZ
420
+     * @return	int|string					Date TMS or ''
421
+     */
422
+    function jdate($string, $gm=false);
423
+
424
+    /**
425
+     * Encrypt sensitive data in database
426
+     * Warning: This function includes the escape, so it must use direct value
427
+     *
428
+     * @param   string 			$fieldorvalue 	Field name or value to encrypt
429
+     * @param  	int 			$withQuotes 	Return string with quotes
430
+     * @return 	string                     		XXX(field) or XXX('value') or field or 'value'
431
+     */
432
+    function encrypt($fieldorvalue, $withQuotes = 0);
433
+
434
+    /**
435
+     * Validate a database transaction
436
+     *
437
+     * @param   string 			$log 			Add more log to default log line
438
+     * @return	int                				1 if validation is OK or transaction level no started, 0 if ERROR
439
+     */
440
+    function commit($log = '');
441 441
 
442 442
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
443
-	/**
444
-	 * List information of columns into a table.
445
-	 *
446
-	 * @param   string 			$table 			Name of table
447
-	 * @return  array                			Array with inforation on table
448
-	 */
443
+    /**
444
+     * List information of columns into a table.
445
+     *
446
+     * @param   string 			$table 			Name of table
447
+     * @return  array                			Array with inforation on table
448
+     */
449 449
     function DDLInfoTable($table);
450 450
     // phpcs:enable
451 451
 
452
-	/**
453
-	 * Free last resultset used.
454
-	 *
455
-	 * @param  	resource 		$resultset 		Fre cursor
456
-	 * @return  void
457
-	 */
458
-	function free($resultset = null);
459
-
460
-	/**
461
-	 * Close database connexion
462
-	 *
463
-	 * @return  boolean     					True if disconnect successfull, false otherwise
464
-	 * @see     connect
465
-	 */
466
-	function close();
467
-
468
-	/**
469
-	 * Return last query in error
470
-	 *
471
-	 * @return  string    lastqueryerror
472
-	 */
473
-	function lastqueryerror();
452
+    /**
453
+     * Free last resultset used.
454
+     *
455
+     * @param  	resource 		$resultset 		Fre cursor
456
+     * @return  void
457
+     */
458
+    function free($resultset = null);
459
+
460
+    /**
461
+     * Close database connexion
462
+     *
463
+     * @return  boolean     					True if disconnect successfull, false otherwise
464
+     * @see     connect
465
+     */
466
+    function close();
467
+
468
+    /**
469
+     * Return last query in error
470
+     *
471
+     * @return  string    lastqueryerror
472
+     */
473
+    function lastqueryerror();
474 474
 
475 475
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
476
-	/**
477
-	 * Return connexion ID
478
-	 *
479
-	 * @return  string      Id connexion
480
-	 */
476
+    /**
477
+     * Return connexion ID
478
+     *
479
+     * @return  string      Id connexion
480
+     */
481 481
     function DDLGetConnectId();
482 482
     // phpcs:enable
483 483
 
484 484
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
485
-	/**
486
-	 * Renvoie la ligne courante (comme un objet) pour le curseur resultset
487
-	 *
488
-	 * @param   resource $resultset Curseur de la requete voulue
489
-	 * @return  Object                    Object result line or false if KO or end of cursor
490
-	 */
485
+    /**
486
+     * Renvoie la ligne courante (comme un objet) pour le curseur resultset
487
+     *
488
+     * @param   resource $resultset Curseur de la requete voulue
489
+     * @return  Object                    Object result line or false if KO or end of cursor
490
+     */
491 491
     function fetch_object($resultset);
492 492
     // phpcs:enable
493 493
 
494 494
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
495
-	/**
496
-	 * Select a database
497
-	 *
498
-	 * @param	string $database Name of database
499
-	 * @return  boolean            true if OK, false if KO
500
-	 */
495
+    /**
496
+     * Select a database
497
+     *
498
+     * @param	string $database Name of database
499
+     * @return  boolean            true if OK, false if KO
500
+     */
501 501
     function select_db($database);
502 502
     // phpcs:enable
503 503
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -419,7 +419,7 @@
 block discarded – undo
419 419
 	 * @param	bool			$gm			1=Input informations are GMT values, otherwise local to server TZ
420 420
 	 * @return	int|string					Date TMS or ''
421 421
 	 */
422
-	function jdate($string, $gm=false);
422
+	function jdate($string, $gm = false);
423 423
 
424 424
 	/**
425 425
 	 * Encrypt sensitive data in database
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/DoliDB.class.php 3 patches
Indentation   +250 added lines, -250 removed lines patch added patch discarded remove patch
@@ -29,273 +29,273 @@
 block discarded – undo
29 29
  */
30 30
 abstract class DoliDB implements Database
31 31
 {
32
-	/** @var resource Database handler */
33
-	public $db;
34
-	/** @var string Database type */
35
-	public $type;
36
-	/** @var string Charset used to force charset when creating database */
37
-	public $forcecharset='utf8';
38
-	/** @var string Collate used to force collate when creating database */
39
-	public $forcecollate='utf8_unicode_ci';
40
-	/** @var resource Resultset of last query */
41
-	private $_results;
42
-	/** @var bool true if connected, else false */
43
-	public $connected;
44
-	/** @var bool true if database selected, else false */
45
-	public $database_selected;
46
-	/** @var string Selected database name */
47
-	public $database_name;
48
-	/** @var string Database username */
49
-	public $database_user;
50
-	/** @var string Database host */
51
-	public $database_host;
52
-	/** @var int Database port */
53
-	public $database_port;
54
-	/** @var int >=1 if a transaction is opened, 0 otherwise */
55
-	public $transaction_opened;
56
-	/** @var string Last successful query */
57
-	public $lastquery;
58
-	/** @var string Last failed query */
59
-	public $lastqueryerror;
60
-	/** @var string Last error message */
61
-	public $lasterror;
62
-	/** @var string Last error number. For example: 'DB_ERROR_RECORD_ALREADY_EXISTS', '12345', ... */
63
-	public $lasterrno;
32
+    /** @var resource Database handler */
33
+    public $db;
34
+    /** @var string Database type */
35
+    public $type;
36
+    /** @var string Charset used to force charset when creating database */
37
+    public $forcecharset='utf8';
38
+    /** @var string Collate used to force collate when creating database */
39
+    public $forcecollate='utf8_unicode_ci';
40
+    /** @var resource Resultset of last query */
41
+    private $_results;
42
+    /** @var bool true if connected, else false */
43
+    public $connected;
44
+    /** @var bool true if database selected, else false */
45
+    public $database_selected;
46
+    /** @var string Selected database name */
47
+    public $database_name;
48
+    /** @var string Database username */
49
+    public $database_user;
50
+    /** @var string Database host */
51
+    public $database_host;
52
+    /** @var int Database port */
53
+    public $database_port;
54
+    /** @var int >=1 if a transaction is opened, 0 otherwise */
55
+    public $transaction_opened;
56
+    /** @var string Last successful query */
57
+    public $lastquery;
58
+    /** @var string Last failed query */
59
+    public $lastqueryerror;
60
+    /** @var string Last error message */
61
+    public $lasterror;
62
+    /** @var string Last error number. For example: 'DB_ERROR_RECORD_ALREADY_EXISTS', '12345', ... */
63
+    public $lasterrno;
64 64
 
65
-	/** @var bool Status */
66
-	public $ok;
67
-	/** @var string */
68
-	public $error;
65
+    /** @var bool Status */
66
+    public $ok;
67
+    /** @var string */
68
+    public $error;
69 69
 
70
-	/**
71
-	 *	Format a SQL IF
72
-	 *
73
-	 *	@param	string	$test           Test string (example: 'cd.statut=0', 'field IS NULL')
74
-	 *	@param	string	$resok          resultat si test egal
75
-	 *	@param	string	$resko          resultat si test non egal
76
-	 *	@return	string          		SQL string
77
-	 */
78
-	function ifsql($test,$resok,$resko)
79
-	{
80
-		return 'IF('.$test.','.$resok.','.$resko.')';
81
-	}
70
+    /**
71
+     *	Format a SQL IF
72
+     *
73
+     *	@param	string	$test           Test string (example: 'cd.statut=0', 'field IS NULL')
74
+     *	@param	string	$resok          resultat si test egal
75
+     *	@param	string	$resko          resultat si test non egal
76
+     *	@return	string          		SQL string
77
+     */
78
+    function ifsql($test,$resok,$resko)
79
+    {
80
+        return 'IF('.$test.','.$resok.','.$resko.')';
81
+    }
82 82
 
83
-	/**
84
-	 *   Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
85
-	 *   Function to use to build INSERT, UPDATE or WHERE predica
86
-	 *
87
-	 *   @param	    int		$param      	Date TMS to convert
88
-	 *   @return	string      			Date in a string YYYY-MM-DD HH:MM:SS
89
-	 */
90
-	function idate($param)
91
-	{
92
-		// TODO GMT $param should be gmt, so we should add tzouptut to 'gmt'
93
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
94
-	}
83
+    /**
84
+     *   Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
85
+     *   Function to use to build INSERT, UPDATE or WHERE predica
86
+     *
87
+     *   @param	    int		$param      	Date TMS to convert
88
+     *   @return	string      			Date in a string YYYY-MM-DD HH:MM:SS
89
+     */
90
+    function idate($param)
91
+    {
92
+        // TODO GMT $param should be gmt, so we should add tzouptut to 'gmt'
93
+        return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
94
+    }
95 95
 
96
-	/**
97
-	 *	Return last error code
98
-	 *
99
-	 *	@return	    string	lasterrno
100
-	 */
101
-	function lasterrno()
102
-	{
103
-		return $this->lasterrno;
104
-	}
96
+    /**
97
+     *	Return last error code
98
+     *
99
+     *	@return	    string	lasterrno
100
+     */
101
+    function lasterrno()
102
+    {
103
+        return $this->lasterrno;
104
+    }
105 105
 
106
-	/**
107
-	 * Start transaction
108
-	 *
109
-	 * @return	    int         1 if transaction successfuly opened or already opened, 0 if error
110
-	 */
111
-	function begin()
112
-	{
113
-		if (! $this->transaction_opened)
114
-		{
115
-			$ret=$this->query("BEGIN");
116
-			if ($ret)
117
-			{
118
-				$this->transaction_opened++;
119
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
120
-				dol_syslog('',0,1);
121
-			}
122
-			return $ret;
123
-		}
124
-		else
125
-		{
126
-			$this->transaction_opened++;
127
-			dol_syslog('',0,1);
128
-			return 1;
129
-		}
130
-	}
106
+    /**
107
+     * Start transaction
108
+     *
109
+     * @return	    int         1 if transaction successfuly opened or already opened, 0 if error
110
+     */
111
+    function begin()
112
+    {
113
+        if (! $this->transaction_opened)
114
+        {
115
+            $ret=$this->query("BEGIN");
116
+            if ($ret)
117
+            {
118
+                $this->transaction_opened++;
119
+                dol_syslog("BEGIN Transaction",LOG_DEBUG);
120
+                dol_syslog('',0,1);
121
+            }
122
+            return $ret;
123
+        }
124
+        else
125
+        {
126
+            $this->transaction_opened++;
127
+            dol_syslog('',0,1);
128
+            return 1;
129
+        }
130
+    }
131 131
 
132
-	/**
133
-	 * Validate a database transaction
134
-	 *
135
-	 * @param	string	$log		Add more log to default log line
136
-	 * @return	int         		1 if validation is OK or transaction level no started, 0 if ERROR
137
-	 */
138
-	function commit($log='')
139
-	{
140
-		dol_syslog('',0,-1);
141
-		if ($this->transaction_opened<=1)
142
-		{
143
-			$ret=$this->query("COMMIT");
144
-			if ($ret)
145
-			{
146
-				$this->transaction_opened=0;
147
-				dol_syslog("COMMIT Transaction".($log?' '.$log:''),LOG_DEBUG);
148
-				return 1;
149
-			}
150
-			else
151
-			{
152
-				return 0;
153
-			}
154
-		}
155
-		else
156
-		{
157
-			$this->transaction_opened--;
158
-			return 1;
159
-		}
160
-	}
132
+    /**
133
+     * Validate a database transaction
134
+     *
135
+     * @param	string	$log		Add more log to default log line
136
+     * @return	int         		1 if validation is OK or transaction level no started, 0 if ERROR
137
+     */
138
+    function commit($log='')
139
+    {
140
+        dol_syslog('',0,-1);
141
+        if ($this->transaction_opened<=1)
142
+        {
143
+            $ret=$this->query("COMMIT");
144
+            if ($ret)
145
+            {
146
+                $this->transaction_opened=0;
147
+                dol_syslog("COMMIT Transaction".($log?' '.$log:''),LOG_DEBUG);
148
+                return 1;
149
+            }
150
+            else
151
+            {
152
+                return 0;
153
+            }
154
+        }
155
+        else
156
+        {
157
+            $this->transaction_opened--;
158
+            return 1;
159
+        }
160
+    }
161 161
 
162
-	/**
163
-	 *	Annulation d'une transaction et retour aux anciennes valeurs
164
-	 *
165
-	 * 	@param	string			$log		Add more log to default log line
166
-	 * 	@return	resource|int         		1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
167
-	 */
168
-	function rollback($log='')
169
-	{
170
-		dol_syslog('',0,-1);
171
-		if ($this->transaction_opened<=1)
172
-		{
173
-			$ret=$this->query("ROLLBACK");
174
-			$this->transaction_opened=0;
175
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
176
-			return $ret;
177
-		}
178
-		else
179
-		{
180
-			$this->transaction_opened--;
181
-			return 1;
182
-		}
183
-	}
162
+    /**
163
+     *	Annulation d'une transaction et retour aux anciennes valeurs
164
+     *
165
+     * 	@param	string			$log		Add more log to default log line
166
+     * 	@return	resource|int         		1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
167
+     */
168
+    function rollback($log='')
169
+    {
170
+        dol_syslog('',0,-1);
171
+        if ($this->transaction_opened<=1)
172
+        {
173
+            $ret=$this->query("ROLLBACK");
174
+            $this->transaction_opened=0;
175
+            dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
176
+            return $ret;
177
+        }
178
+        else
179
+        {
180
+            $this->transaction_opened--;
181
+            return 1;
182
+        }
183
+    }
184 184
 
185
-	/**
186
-	 *	Define limits and offset of request
187
-	 *
188
-	 *	@param	int		$limit      Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
189
-	 *	@param	int		$offset     Numero of line from where starting fetch
190
-	 *	@return	string      		String with SQL syntax to add a limit and offset
191
-	 */
192
-	function plimit($limit=0,$offset=0)
193
-	{
194
-		global $conf;
195
-		if (empty($limit)) return "";
196
-		if ($limit < 0) $limit=$conf->liste_limit;
197
-		if ($offset > 0) return " LIMIT $offset,$limit ";
198
-		else return " LIMIT $limit ";
199
-	}
185
+    /**
186
+     *	Define limits and offset of request
187
+     *
188
+     *	@param	int		$limit      Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
189
+     *	@param	int		$offset     Numero of line from where starting fetch
190
+     *	@return	string      		String with SQL syntax to add a limit and offset
191
+     */
192
+    function plimit($limit=0,$offset=0)
193
+    {
194
+        global $conf;
195
+        if (empty($limit)) return "";
196
+        if ($limit < 0) $limit=$conf->liste_limit;
197
+        if ($offset > 0) return " LIMIT $offset,$limit ";
198
+        else return " LIMIT $limit ";
199
+    }
200 200
 
201
-	/**
202
-	 *	Return version of database server into an array
203
-	 *
204
-	 *	@return	        array  		Version array
205
-	 */
206
-	function getVersionArray()
207
-	{
208
-		return preg_split("/[\.,-]/",$this->getVersion());
209
-	}
201
+    /**
202
+     *	Return version of database server into an array
203
+     *
204
+     *	@return	        array  		Version array
205
+     */
206
+    function getVersionArray()
207
+    {
208
+        return preg_split("/[\.,-]/",$this->getVersion());
209
+    }
210 210
 
211
-	/**
212
-	 *	Return last request executed with query()
213
-	 *
214
-	 *	@return	string					Last query
215
-	 */
216
-	function lastquery()
217
-	{
218
-		return $this->lastquery;
219
-	}
211
+    /**
212
+     *	Return last request executed with query()
213
+     *
214
+     *	@return	string					Last query
215
+     */
216
+    function lastquery()
217
+    {
218
+        return $this->lastquery;
219
+    }
220 220
 
221
-	/**
222
-	 * Define sort criteria of request
223
-	 *
224
-	 * @param	string		$sortfield		List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
225
-	 * @param	string		$sortorder		Sort order, separated by comma. Example: 'ASC,DESC';
226
-	 * @return	string						String to provide syntax of a sort sql string
227
-	 */
228
-	function order($sortfield=null,$sortorder=null)
229
-	{
230
-		if (! empty($sortfield))
231
-		{
232
-			$return='';
233
-			$fields=explode(',',$sortfield);
234
-			$orders=explode(',',$sortorder);
235
-			$i=0;
236
-			foreach($fields as $val)
237
-			{
238
-				if (! $return) $return.=' ORDER BY ';
239
-				else $return.=', ';
221
+    /**
222
+     * Define sort criteria of request
223
+     *
224
+     * @param	string		$sortfield		List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
225
+     * @param	string		$sortorder		Sort order, separated by comma. Example: 'ASC,DESC';
226
+     * @return	string						String to provide syntax of a sort sql string
227
+     */
228
+    function order($sortfield=null,$sortorder=null)
229
+    {
230
+        if (! empty($sortfield))
231
+        {
232
+            $return='';
233
+            $fields=explode(',',$sortfield);
234
+            $orders=explode(',',$sortorder);
235
+            $i=0;
236
+            foreach($fields as $val)
237
+            {
238
+                if (! $return) $return.=' ORDER BY ';
239
+                else $return.=', ';
240 240
 
241
-				$return.=preg_replace('/[^0-9a-z_\.]/i','',$val);
241
+                $return.=preg_replace('/[^0-9a-z_\.]/i','',$val);
242 242
 
243
-				$tmpsortorder = trim($orders[$i]);
243
+                $tmpsortorder = trim($orders[$i]);
244 244
 
245
-				// Only ASC and DESC values are valid SQL
246
-				if (strtoupper($tmpsortorder) === 'ASC') {
247
-					$return .= ' ASC';
248
-				} elseif (strtoupper($tmpsortorder) === 'DESC') {
249
-					$return .= ' DESC';
250
-				}
245
+                // Only ASC and DESC values are valid SQL
246
+                if (strtoupper($tmpsortorder) === 'ASC') {
247
+                    $return .= ' ASC';
248
+                } elseif (strtoupper($tmpsortorder) === 'DESC') {
249
+                    $return .= ' DESC';
250
+                }
251 251
 
252
-				$i++;
253
-			}
254
-			return $return;
255
-		}
256
-		else
257
-		{
258
-			return '';
259
-		}
260
-	}
252
+                $i++;
253
+            }
254
+            return $return;
255
+        }
256
+        else
257
+        {
258
+            return '';
259
+        }
260
+    }
261 261
 
262
-	/**
263
-	 *	Return last error label
264
-	 *
265
-	 *	@return	    string		Last error
266
-	 */
267
-	function lasterror()
268
-	{
269
-		return $this->lasterror;
270
-	}
262
+    /**
263
+     *	Return last error label
264
+     *
265
+     *	@return	    string		Last error
266
+     */
267
+    function lasterror()
268
+    {
269
+        return $this->lasterror;
270
+    }
271 271
 
272
-	/**
273
-	 *	Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
274
-	 * 	19700101020000 -> 3600 with TZ+1 and gmt=0
275
-	 * 	19700101020000 -> 7200 whaterver is TZ if gmt=1
276
-	 *
277
-	 * 	@param	string				$string		Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
278
-	 *	@param	bool				$gm			1=Input informations are GMT values, otherwise local to server TZ
279
-	 *	@return	int|string						Date TMS or ''
280
-	 */
281
-	function jdate($string, $gm=false)
282
-	{
283
-		// TODO GMT must set param gm to true by default
284
-		if ($string==0 || $string=="0000-00-00 00:00:00") return '';
285
-		$string=preg_replace('/([^0-9])/i','',$string);
286
-		$tmp=$string.'000000';
287
-		$date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
288
-		return $date;
289
-	}
272
+    /**
273
+     *	Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
274
+     * 	19700101020000 -> 3600 with TZ+1 and gmt=0
275
+     * 	19700101020000 -> 7200 whaterver is TZ if gmt=1
276
+     *
277
+     * 	@param	string				$string		Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
278
+     *	@param	bool				$gm			1=Input informations are GMT values, otherwise local to server TZ
279
+     *	@return	int|string						Date TMS or ''
280
+     */
281
+    function jdate($string, $gm=false)
282
+    {
283
+        // TODO GMT must set param gm to true by default
284
+        if ($string==0 || $string=="0000-00-00 00:00:00") return '';
285
+        $string=preg_replace('/([^0-9])/i','',$string);
286
+        $tmp=$string.'000000';
287
+        $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
288
+        return $date;
289
+    }
290 290
 
291
-	/**
292
-	 *	Return last query in error
293
-	 *
294
-	 *	@return	    string	lastqueryerror
295
-	 */
296
-	function lastqueryerror()
297
-	{
298
-		return $this->lastqueryerror;
299
-	}
291
+    /**
292
+     *	Return last query in error
293
+     *
294
+     *	@return	    string	lastqueryerror
295
+     */
296
+    function lastqueryerror()
297
+    {
298
+        return $this->lastqueryerror;
299
+    }
300 300
 }
301 301
 
Please login to merge, or discard this patch.
Braces   +24 added lines, -17 removed lines patch added patch discarded remove patch
@@ -120,8 +120,7 @@  discard block
 block discarded – undo
120 120
 				dol_syslog('',0,1);
121 121
 			}
122 122
 			return $ret;
123
-		}
124
-		else
123
+		} else
125 124
 		{
126 125
 			$this->transaction_opened++;
127 126
 			dol_syslog('',0,1);
@@ -146,13 +145,11 @@  discard block
 block discarded – undo
146 145
 				$this->transaction_opened=0;
147 146
 				dol_syslog("COMMIT Transaction".($log?' '.$log:''),LOG_DEBUG);
148 147
 				return 1;
149
-			}
150
-			else
148
+			} else
151 149
 			{
152 150
 				return 0;
153 151
 			}
154
-		}
155
-		else
152
+		} else
156 153
 		{
157 154
 			$this->transaction_opened--;
158 155
 			return 1;
@@ -174,8 +171,7 @@  discard block
 block discarded – undo
174 171
 			$this->transaction_opened=0;
175 172
 			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
176 173
 			return $ret;
177
-		}
178
-		else
174
+		} else
179 175
 		{
180 176
 			$this->transaction_opened--;
181 177
 			return 1;
@@ -192,10 +188,17 @@  discard block
 block discarded – undo
192 188
 	function plimit($limit=0,$offset=0)
193 189
 	{
194 190
 		global $conf;
195
-		if (empty($limit)) return "";
196
-		if ($limit < 0) $limit=$conf->liste_limit;
197
-		if ($offset > 0) return " LIMIT $offset,$limit ";
198
-		else return " LIMIT $limit ";
191
+		if (empty($limit)) {
192
+		    return "";
193
+		}
194
+		if ($limit < 0) {
195
+		    $limit=$conf->liste_limit;
196
+		}
197
+		if ($offset > 0) {
198
+		    return " LIMIT $offset,$limit ";
199
+		} else {
200
+		    return " LIMIT $limit ";
201
+		}
199 202
 	}
200 203
 
201 204
 	/**
@@ -235,8 +238,11 @@  discard block
 block discarded – undo
235 238
 			$i=0;
236 239
 			foreach($fields as $val)
237 240
 			{
238
-				if (! $return) $return.=' ORDER BY ';
239
-				else $return.=', ';
241
+				if (! $return) {
242
+				    $return.=' ORDER BY ';
243
+				} else {
244
+				    $return.=', ';
245
+				}
240 246
 
241 247
 				$return.=preg_replace('/[^0-9a-z_\.]/i','',$val);
242 248
 
@@ -252,8 +258,7 @@  discard block
 block discarded – undo
252 258
 				$i++;
253 259
 			}
254 260
 			return $return;
255
-		}
256
-		else
261
+		} else
257 262
 		{
258 263
 			return '';
259 264
 		}
@@ -281,7 +286,9 @@  discard block
 block discarded – undo
281 286
 	function jdate($string, $gm=false)
282 287
 	{
283 288
 		// TODO GMT must set param gm to true by default
284
-		if ($string==0 || $string=="0000-00-00 00:00:00") return '';
289
+		if ($string==0 || $string=="0000-00-00 00:00:00") {
290
+		    return '';
291
+		}
285 292
 		$string=preg_replace('/([^0-9])/i','',$string);
286 293
 		$tmp=$string.'000000';
287 294
 		$date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
  * \brief 		Class file to manage Dolibarr database access
27 27
  */
28 28
 
29
-require_once DOL_BASE_PATH . '/core/db/Database.interface.php';
29
+require_once DOL_BASE_PATH.'/core/db/Database.interface.php';
30 30
 
31 31
 /**
32 32
  * Class to manage Dolibarr database access
@@ -38,9 +38,9 @@  discard block
 block discarded – undo
38 38
 	/** @var string Database type */
39 39
 	public $type;
40 40
 	/** @var string Charset used to force charset when creating database */
41
-	public $forcecharset='utf8';
41
+	public $forcecharset = 'utf8';
42 42
 	/** @var string Collate used to force collate when creating database */
43
-	public $forcecollate='utf8_unicode_ci';
43
+	public $forcecollate = 'utf8_unicode_ci';
44 44
 	/** @var resource Resultset of last query */
45 45
 	private $_results;
46 46
 	/** @var bool true if connected, else false */
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	 *	@param	string	$resko          resultat si test non egal
80 80
 	 *	@return	string          		SQL string
81 81
 	 */
82
-	function ifsql($test,$resok,$resko)
82
+	function ifsql($test, $resok, $resko)
83 83
 	{
84 84
 		return 'IF('.$test.','.$resok.','.$resko.')';
85 85
 	}
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	function idate($param)
95 95
 	{
96 96
 		// TODO GMT $param should be gmt, so we should add tzouptut to 'gmt'
97
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
97
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
98 98
 	}
99 99
 
100 100
 	/**
@@ -114,21 +114,21 @@  discard block
 block discarded – undo
114 114
 	 */
115 115
 	function begin()
116 116
 	{
117
-		if (! $this->transaction_opened)
117
+		if (!$this->transaction_opened)
118 118
 		{
119
-			$ret=$this->query("BEGIN");
119
+			$ret = $this->query("BEGIN");
120 120
 			if ($ret)
121 121
 			{
122 122
 				$this->transaction_opened++;
123
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
124
-				dol_syslog('',0,1);
123
+				dol_syslog("BEGIN Transaction", LOG_DEBUG);
124
+				dol_syslog('', 0, 1);
125 125
 			}
126 126
 			return $ret;
127 127
 		}
128 128
 		else
129 129
 		{
130 130
 			$this->transaction_opened++;
131
-			dol_syslog('',0,1);
131
+			dol_syslog('', 0, 1);
132 132
 			return 1;
133 133
 		}
134 134
 	}
@@ -139,16 +139,16 @@  discard block
 block discarded – undo
139 139
 	 * @param	string	$log		Add more log to default log line
140 140
 	 * @return	int         		1 if validation is OK or transaction level no started, 0 if ERROR
141 141
 	 */
142
-	function commit($log='')
142
+	function commit($log = '')
143 143
 	{
144
-		dol_syslog('',0,-1);
145
-		if ($this->transaction_opened<=1)
144
+		dol_syslog('', 0, -1);
145
+		if ($this->transaction_opened <= 1)
146 146
 		{
147
-			$ret=$this->query("COMMIT");
147
+			$ret = $this->query("COMMIT");
148 148
 			if ($ret)
149 149
 			{
150
-				$this->transaction_opened=0;
151
-				dol_syslog("COMMIT Transaction".($log?' '.$log:''),LOG_DEBUG);
150
+				$this->transaction_opened = 0;
151
+				dol_syslog("COMMIT Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
152 152
 				return 1;
153 153
 			}
154 154
 			else
@@ -169,14 +169,14 @@  discard block
 block discarded – undo
169 169
 	 * 	@param	string			$log		Add more log to default log line
170 170
 	 * 	@return	resource|int         		1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
171 171
 	 */
172
-	function rollback($log='')
172
+	function rollback($log = '')
173 173
 	{
174
-		dol_syslog('',0,-1);
175
-		if ($this->transaction_opened<=1)
174
+		dol_syslog('', 0, -1);
175
+		if ($this->transaction_opened <= 1)
176 176
 		{
177
-			$ret=$this->query("ROLLBACK");
178
-			$this->transaction_opened=0;
179
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
177
+			$ret = $this->query("ROLLBACK");
178
+			$this->transaction_opened = 0;
179
+			dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
180 180
 			return $ret;
181 181
 		}
182 182
 		else
@@ -193,11 +193,11 @@  discard block
 block discarded – undo
193 193
 	 *	@param	int		$offset     Numero of line from where starting fetch
194 194
 	 *	@return	string      		String with SQL syntax to add a limit and offset
195 195
 	 */
196
-	function plimit($limit=0,$offset=0)
196
+	function plimit($limit = 0, $offset = 0)
197 197
 	{
198 198
 		global $conf;
199 199
 		if (empty($limit)) return "";
200
-		if ($limit < 0) $limit=$conf->liste_limit;
200
+		if ($limit < 0) $limit = $conf->liste_limit;
201 201
 		if ($offset > 0) return " LIMIT $offset,$limit ";
202 202
 		else return " LIMIT $limit ";
203 203
 	}
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 	 */
210 210
 	function getVersionArray()
211 211
 	{
212
-		return preg_split("/[\.,-]/",$this->getVersion());
212
+		return preg_split("/[\.,-]/", $this->getVersion());
213 213
 	}
214 214
 
215 215
 	/**
@@ -229,20 +229,20 @@  discard block
 block discarded – undo
229 229
 	 * @param	string		$sortorder		Sort order, separated by comma. Example: 'ASC,DESC';
230 230
 	 * @return	string						String to provide syntax of a sort sql string
231 231
 	 */
232
-	function order($sortfield=null,$sortorder=null)
232
+	function order($sortfield = null, $sortorder = null)
233 233
 	{
234
-		if (! empty($sortfield))
234
+		if (!empty($sortfield))
235 235
 		{
236
-			$return='';
237
-			$fields=explode(',',$sortfield);
238
-			$orders=explode(',',$sortorder);
239
-			$i=0;
240
-			foreach($fields as $val)
236
+			$return = '';
237
+			$fields = explode(',', $sortfield);
238
+			$orders = explode(',', $sortorder);
239
+			$i = 0;
240
+			foreach ($fields as $val)
241 241
 			{
242
-				if (! $return) $return.=' ORDER BY ';
243
-				else $return.=', ';
242
+				if (!$return) $return .= ' ORDER BY ';
243
+				else $return .= ', ';
244 244
 
245
-				$return.=preg_replace('/[^0-9a-z_\.]/i','',$val);
245
+				$return .= preg_replace('/[^0-9a-z_\.]/i', '', $val);
246 246
 
247 247
 				$tmpsortorder = trim($orders[$i]);
248 248
 
@@ -282,13 +282,13 @@  discard block
 block discarded – undo
282 282
 	 *	@param	bool				$gm			1=Input informations are GMT values, otherwise local to server TZ
283 283
 	 *	@return	int|string						Date TMS or ''
284 284
 	 */
285
-	function jdate($string, $gm=false)
285
+	function jdate($string, $gm = false)
286 286
 	{
287 287
 		// TODO GMT must set param gm to true by default
288
-		if ($string==0 || $string=="0000-00-00 00:00:00") return '';
289
-		$string=preg_replace('/([^0-9])/i','',$string);
290
-		$tmp=$string.'000000';
291
-		$date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
288
+		if ($string == 0 || $string == "0000-00-00 00:00:00") return '';
289
+		$string = preg_replace('/([^0-9])/i', '', $string);
290
+		$tmp = $string.'000000';
291
+		$date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), $gm);
292 292
 		return $date;
293 293
 	}
294 294
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/pgsql.class.php 3 patches
Indentation   +1056 added lines, -1056 removed lines patch added patch discarded remove patch
@@ -36,110 +36,110 @@  discard block
 block discarded – undo
36 36
 class DoliDBPgsql extends DoliDB
37 37
 {
38 38
     //! Database type
39
-	public $type='pgsql';            // Name of manager
39
+    public $type='pgsql';            // Name of manager
40 40
     //! Database label
41
-	const LABEL='PostgreSQL';      // Label of manager
42
-	//! Charset
43
-	var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
41
+    const LABEL='PostgreSQL';      // Label of manager
42
+    //! Charset
43
+    var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
44 44
     //! Collate used to force collate when creating database
45 45
     var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
46
-	//! Version min database
47
-	const VERSIONMIN='9.0.0';	// Version min database
48
-	/** @var resource Resultset of last query */
49
-	private $_results;
50
-
51
-	public $unescapeslashquot;
52
-	public $standard_conforming_strings;
53
-
54
-	/**
55
-	 *	Constructor.
56
-	 *	This create an opened connexion to a database server and eventually to a database
57
-	 *
58
-	 *	@param      string	$type		Type of database (mysql, pgsql...)
59
-	 *	@param	    string	$host		Address of database server
60
-	 *	@param	    string	$user		Nom de l'utilisateur autorise
61
-	 *	@param	    string	$pass		Mot de passe
62
-	 *	@param	    string	$name		Nom de la database
63
-	 *	@param	    int		$port		Port of database server
64
-	 */
65
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
66
-	{
67
-		global $conf,$langs;
46
+    //! Version min database
47
+    const VERSIONMIN='9.0.0';	// Version min database
48
+    /** @var resource Resultset of last query */
49
+    private $_results;
50
+
51
+    public $unescapeslashquot;
52
+    public $standard_conforming_strings;
53
+
54
+    /**
55
+     *	Constructor.
56
+     *	This create an opened connexion to a database server and eventually to a database
57
+     *
58
+     *	@param      string	$type		Type of database (mysql, pgsql...)
59
+     *	@param	    string	$host		Address of database server
60
+     *	@param	    string	$user		Nom de l'utilisateur autorise
61
+     *	@param	    string	$pass		Mot de passe
62
+     *	@param	    string	$name		Nom de la database
63
+     *	@param	    int		$port		Port of database server
64
+     */
65
+    function __construct($type, $host, $user, $pass, $name='', $port=0)
66
+    {
67
+        global $conf,$langs;
68 68
 
69 69
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
70
-		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
71
-		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
70
+        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
71
+        if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
72 72
 
73
-		$this->database_user=$user;
73
+        $this->database_user=$user;
74 74
         $this->database_host=$host;
75 75
         $this->database_port=$port;
76 76
 
77
-		$this->transaction_opened=0;
78
-
79
-		//print "Name DB: $host,$user,$pass,$name<br>";
80
-
81
-		if (! function_exists("pg_connect"))
82
-		{
83
-			$this->connected = false;
84
-			$this->ok = false;
85
-			$this->error="Pgsql PHP functions are not available in this version of PHP";
86
-			dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP",LOG_ERR);
87
-			return $this->ok;
88
-		}
89
-
90
-		if (! $host)
91
-		{
92
-			$this->connected = false;
93
-			$this->ok = false;
94
-			$this->error=$langs->trans("ErrorWrongHostParameter");
95
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters",LOG_ERR);
96
-			return $this->ok;
97
-		}
98
-
99
-		// Essai connexion serveur
100
-		//print "$host, $user, $pass, $name, $port";
101
-		$this->db = $this->connect($host, $user, $pass, $name, $port);
102
-
103
-		if ($this->db)
104
-		{
105
-			$this->connected = true;
106
-			$this->ok = true;
107
-		}
108
-		else
109
-		{
110
-			// host, login ou password incorrect
111
-			$this->connected = false;
112
-			$this->ok = false;
113
-			$this->error='Host, login or password incorrect';
114
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error,LOG_ERR);
115
-		}
116
-
117
-		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
118
-		if ($this->connected && $name)
119
-		{
120
-			if ($this->select_db($name))
121
-			{
122
-				$this->database_selected = true;
123
-				$this->database_name = $name;
124
-				$this->ok = true;
125
-			}
126
-			else
127
-			{
128
-				$this->database_selected = false;
129
-				$this->database_name = '';
130
-				$this->ok = false;
131
-				$this->error=$this->error();
132
-				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
133
-			}
134
-		}
135
-		else
136
-		{
137
-			// Pas de selection de base demandee, ok ou ko
138
-			$this->database_selected = false;
139
-		}
140
-
141
-		return $this->ok;
142
-	}
77
+        $this->transaction_opened=0;
78
+
79
+        //print "Name DB: $host,$user,$pass,$name<br>";
80
+
81
+        if (! function_exists("pg_connect"))
82
+        {
83
+            $this->connected = false;
84
+            $this->ok = false;
85
+            $this->error="Pgsql PHP functions are not available in this version of PHP";
86
+            dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP",LOG_ERR);
87
+            return $this->ok;
88
+        }
89
+
90
+        if (! $host)
91
+        {
92
+            $this->connected = false;
93
+            $this->ok = false;
94
+            $this->error=$langs->trans("ErrorWrongHostParameter");
95
+            dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters",LOG_ERR);
96
+            return $this->ok;
97
+        }
98
+
99
+        // Essai connexion serveur
100
+        //print "$host, $user, $pass, $name, $port";
101
+        $this->db = $this->connect($host, $user, $pass, $name, $port);
102
+
103
+        if ($this->db)
104
+        {
105
+            $this->connected = true;
106
+            $this->ok = true;
107
+        }
108
+        else
109
+        {
110
+            // host, login ou password incorrect
111
+            $this->connected = false;
112
+            $this->ok = false;
113
+            $this->error='Host, login or password incorrect';
114
+            dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error,LOG_ERR);
115
+        }
116
+
117
+        // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
118
+        if ($this->connected && $name)
119
+        {
120
+            if ($this->select_db($name))
121
+            {
122
+                $this->database_selected = true;
123
+                $this->database_name = $name;
124
+                $this->ok = true;
125
+            }
126
+            else
127
+            {
128
+                $this->database_selected = false;
129
+                $this->database_name = '';
130
+                $this->ok = false;
131
+                $this->error=$this->error();
132
+                dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
133
+            }
134
+        }
135
+        else
136
+        {
137
+            // Pas de selection de base demandee, ok ou ko
138
+            $this->database_selected = false;
139
+        }
140
+
141
+        return $this->ok;
142
+    }
143 143
 
144 144
 
145 145
     /**
@@ -150,105 +150,105 @@  discard block
 block discarded – undo
150 150
      *  @param	bool	$unescapeslashquot	Unescape slash quote with quote quote
151 151
      *  @return string   					SQL request line converted
152 152
      */
153
-	static function convertSQLFromMysql($line,$type='auto',$unescapeslashquot=false)
154
-	{
155
-		// Removed empty line if this is a comment line for SVN tagging
156
-		if (preg_match('/^--\s\$Id/i',$line)) {
157
-			return '';
158
-		}
159
-		// Return line if this is a comment
160
-		if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
161
-		{
162
-			return $line;
163
-		}
164
-		if ($line != "")
165
-		{
166
-			// group_concat support (PgSQL >= 9.0)
167
-			// Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
168
-		    $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
169
-			$line = preg_replace('/ SEPARATOR/i', ',', $line);
170
-			$line = preg_replace('/STRING_AGG\(([^,\)]+)\)/i', 'STRING_AGG(\\1, \',\')', $line);
171
-			//print $line."\n";
172
-
173
-		    if ($type == 'auto')
174
-		    {
175
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
176
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
177
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
178
-		    }
179
-
180
-    		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
181
-
182
-		    if ($type == 'dml')
183
-		    {
153
+    static function convertSQLFromMysql($line,$type='auto',$unescapeslashquot=false)
154
+    {
155
+        // Removed empty line if this is a comment line for SVN tagging
156
+        if (preg_match('/^--\s\$Id/i',$line)) {
157
+            return '';
158
+        }
159
+        // Return line if this is a comment
160
+        if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
161
+        {
162
+            return $line;
163
+        }
164
+        if ($line != "")
165
+        {
166
+            // group_concat support (PgSQL >= 9.0)
167
+            // Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
168
+            $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
169
+            $line = preg_replace('/ SEPARATOR/i', ',', $line);
170
+            $line = preg_replace('/STRING_AGG\(([^,\)]+)\)/i', 'STRING_AGG(\\1, \',\')', $line);
171
+            //print $line."\n";
172
+
173
+            if ($type == 'auto')
174
+            {
175
+                if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
176
+                else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
177
+                else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
178
+            }
179
+
180
+            $line=preg_replace('/ as signed\)/i',' as integer)',$line);
181
+
182
+            if ($type == 'dml')
183
+            {
184 184
                 $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
185 185
 
186
-		        // we are inside create table statement so lets process datatypes
187
-    			if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
188
-    				$line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
189
-    				$line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
190
-    				$line=preg_replace('/,$/','',$line);
191
-    			}
186
+                // we are inside create table statement so lets process datatypes
187
+                if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
188
+                    $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
189
+                    $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
190
+                    $line=preg_replace('/,$/','',$line);
191
+                }
192 192
 
193
-    			// Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
194
-    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
195
-    				$newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
193
+                // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
194
+                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
195
+                    $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
196 196
                     //$line = "-- ".$line." replaced by --\n".$newline;
197 197
                     $line=$newline;
198
-    			}
198
+                }
199 199
 
200
-    			// tinyint type conversion
201
-    			$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
202
-    			$line=preg_replace('/tinyint/i','smallint',$line);
200
+                // tinyint type conversion
201
+                $line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
202
+                $line=preg_replace('/tinyint/i','smallint',$line);
203 203
 
204
-    			// nuke unsigned
205
-    			$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
204
+                // nuke unsigned
205
+                $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
206 206
 
207
-    			// blob -> text
208
-    			$line=preg_replace('/\w*blob/i','text',$line);
207
+                // blob -> text
208
+                $line=preg_replace('/\w*blob/i','text',$line);
209 209
 
210
-    			// tinytext/mediumtext -> text
211
-    			$line=preg_replace('/tinytext/i','text',$line);
212
-    			$line=preg_replace('/mediumtext/i','text',$line);
213
-    			$line=preg_replace('/longtext/i','text',$line);
210
+                // tinytext/mediumtext -> text
211
+                $line=preg_replace('/tinytext/i','text',$line);
212
+                $line=preg_replace('/mediumtext/i','text',$line);
213
+                $line=preg_replace('/longtext/i','text',$line);
214 214
 
215
-    			$line=preg_replace('/text\([0-9]+\)/i','text',$line);
215
+                $line=preg_replace('/text\([0-9]+\)/i','text',$line);
216 216
 
217
-    			// change not null datetime field to null valid ones
218
-    			// (to support remapping of "zero time" to null
219
-    			$line=preg_replace('/datetime not null/i','datetime',$line);
220
-    			$line=preg_replace('/datetime/i','timestamp',$line);
217
+                // change not null datetime field to null valid ones
218
+                // (to support remapping of "zero time" to null
219
+                $line=preg_replace('/datetime not null/i','datetime',$line);
220
+                $line=preg_replace('/datetime/i','timestamp',$line);
221 221
 
222
-    			// double -> numeric
223
-    			$line=preg_replace('/^double/i','numeric',$line);
224
-    			$line=preg_replace('/(\s*)double/i','\\1numeric',$line);
225
-    			// float -> numeric
226
-    			$line=preg_replace('/^float/i','numeric',$line);
227
-    			$line=preg_replace('/(\s*)float/i','\\1numeric',$line);
222
+                // double -> numeric
223
+                $line=preg_replace('/^double/i','numeric',$line);
224
+                $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
225
+                // float -> numeric
226
+                $line=preg_replace('/^float/i','numeric',$line);
227
+                $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
228 228
 
229
-    			//Check tms timestamp field case (in Mysql this field is defautled to now and
230
-    			// on update defaulted by now
231
-    			$line=preg_replace('/(\s*)tms(\s*)timestamp/i','\\1tms timestamp without time zone DEFAULT now() NOT NULL',$line);
229
+                //Check tms timestamp field case (in Mysql this field is defautled to now and
230
+                // on update defaulted by now
231
+                $line=preg_replace('/(\s*)tms(\s*)timestamp/i','\\1tms timestamp without time zone DEFAULT now() NOT NULL',$line);
232 232
 
233
-    			// nuke ON UPDATE CURRENT_TIMESTAMP
234
-    			$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
233
+                // nuke ON UPDATE CURRENT_TIMESTAMP
234
+                $line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
235 235
 
236
-    			// unique index(field1,field2)
237
-    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
238
-    			{
239
-    				$line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
240
-    			}
236
+                // unique index(field1,field2)
237
+                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
238
+                {
239
+                    $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
240
+                }
241 241
 
242
-    			// We remove end of requests "AFTER fieldxxx"
243
-    			$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
242
+                // We remove end of requests "AFTER fieldxxx"
243
+                $line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
244 244
 
245
-    			// We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
246
-    			$line=preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i','DROP INDEX',$line);
245
+                // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
246
+                $line=preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i','DROP INDEX',$line);
247 247
 
248 248
                 // Translate order to rename fields
249 249
                 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
250 250
                 {
251
-                	$line = "-- ".$line." replaced by --\n";
251
+                    $line = "-- ".$line." replaced by --\n";
252 252
                     $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
253 253
                 }
254 254
 
@@ -267,12 +267,12 @@  discard block
 block discarded – undo
267 267
                 }
268 268
 
269 269
                 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
270
-    			// ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
271
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
272
-    			{
273
-    				$line = "-- ".$line." replaced by --\n";
274
-    				$line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
275
-    			}
270
+                // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
271
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
272
+                {
273
+                    $line = "-- ".$line." replaced by --\n";
274
+                    $line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
275
+                }
276 276
 
277 277
                 // Translate order to drop primary keys
278 278
                 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
                     $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
283 283
                 }
284 284
 
285
-		        // Translate order to drop foreign keys
285
+                // Translate order to drop foreign keys
286 286
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
287 287
                 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
288 288
                 {
@@ -299,15 +299,15 @@  discard block
 block discarded – undo
299 299
                 }
300 300
 
301 301
                 // alter table add [unique] [index] (field1, field2 ...)
302
-    			// ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
303
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
304
-    			{
305
-    				$fieldlist=$reg[4];
306
-    				$idxname=$reg[3];
307
-    				$tablename=$reg[1];
308
-    				$line = "-- ".$line." replaced by --\n";
309
-    				$line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
310
-    			}
302
+                // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
303
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
304
+                {
305
+                    $fieldlist=$reg[4];
306
+                    $idxname=$reg[3];
307
+                    $tablename=$reg[1];
308
+                    $line = "-- ".$line." replaced by --\n";
309
+                    $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
310
+                }
311 311
             }
312 312
 
313 313
             // To have postgresql case sensitive
@@ -317,59 +317,59 @@  discard block
 block discarded – undo
317 317
             // Replace INSERT IGNORE into INSERT
318 318
             $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
319 319
 
320
-			// Delete using criteria on other table must not declare twice the deleted table
321
-			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
322
-			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
323
-			{
324
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
325
-				{
326
-					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
327
-				}
328
-			}
320
+            // Delete using criteria on other table must not declare twice the deleted table
321
+            // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
322
+            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
323
+            {
324
+                if ($reg[1] == $reg[2])	// If same table, we remove second one
325
+                {
326
+                    $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
327
+                }
328
+            }
329 329
 
330
-			// Remove () in the tables in FROM if 1 table
331
-			$line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
332
-			//print $line."\n";
330
+            // Remove () in the tables in FROM if 1 table
331
+            $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
332
+            //print $line."\n";
333 333
 
334
-			// Remove () in the tables in FROM if 2 table
335
-			$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);
336
-			//print $line."\n";
334
+            // Remove () in the tables in FROM if 2 table
335
+            $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);
336
+            //print $line."\n";
337 337
 
338
-			// Remove () in the tables in FROM if 3 table
339
-			$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);
340
-			//print $line."\n";
338
+            // Remove () in the tables in FROM if 3 table
339
+            $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);
340
+            //print $line."\n";
341 341
 
342
-			// Remove () in the tables in FROM if 4 table
343
-			$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);
344
-			//print $line."\n";
342
+            // Remove () in the tables in FROM if 4 table
343
+            $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);
344
+            //print $line."\n";
345 345
 
346
-			// Remove () in the tables in FROM if 5 table
347
-			$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);
348
-			//print $line."\n";
346
+            // Remove () in the tables in FROM if 5 table
347
+            $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);
348
+            //print $line."\n";
349 349
 
350
-			// Replace espacing \' by ''.
351
-			// By default we do not (should be already done by db->escape function if required
352
-			// except for sql insert in data file that are mysql escaped so we removed them to
353
-			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
354
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
350
+            // Replace espacing \' by ''.
351
+            // By default we do not (should be already done by db->escape function if required
352
+            // except for sql insert in data file that are mysql escaped so we removed them to
353
+            // be compatible with standard_conforming_strings=on that considers \ as ordinary character).
354
+            if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
355 355
 
356
-			//print "type=".$type." newline=".$line."<br>\n";
357
-		}
356
+            //print "type=".$type." newline=".$line."<br>\n";
357
+        }
358 358
 
359
-		return $line;
360
-	}
359
+        return $line;
360
+    }
361 361
 
362 362
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
363 363
     /**
364 364
      *  Select a database
365 365
      *  Ici postgresql n'a aucune fonction equivalente de mysql_select_db
366 366
      *  On compare juste manuellement si la database choisie est bien celle activee par la connexion
367
-	 *
368
-	 *	@param	    string	$database	Name of database
369
-	 *	@return	    bool				true if OK, false if KO
370
-	 */
371
-	function select_db($database)
372
-	{
367
+     *
368
+     *	@param	    string	$database	Name of database
369
+     *	@return	    bool				true if OK, false if KO
370
+     */
371
+    function select_db($database)
372
+    {
373 373
         // phpcs:enable
374 374
         if ($database == $this->database_name) {
375 375
             return true;
@@ -378,85 +378,85 @@  discard block
 block discarded – undo
378 378
         }
379 379
     }
380 380
 
381
-	/**
382
-	 *	Connexion to server
383
-	 *
384
-	 *	@param	    string		$host		Database server host
385
-	 *	@param	    string		$login		Login
386
-	 *	@param	    string		$passwd		Password
387
-	 *	@param		string		$name		Name of database (not used for mysql, used for pgsql)
388
-	 *	@param		integer		$port		Port of database server
389
-	 *	@return		false|resource			Database access handler
390
-	 *	@see		close
391
-	 */
392
-	function connect($host, $login, $passwd, $name, $port=0)
393
-	{
394
-		// use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
395
-
396
-		$this->db = false;
397
-
398
-		// connections parameters must be protected (only \ and ' according to pg_connect() manual)
399
-		$host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
400
-		$login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
401
-		$passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
402
-		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
403
-		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
404
-
405
-		if (! $name) $name="postgres";    // When try to connect using admin user
406
-
407
-		// try first Unix domain socket (local)
408
-		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
409
-		{
410
-			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'";    // $name may be empty
411
-			$this->db = @pg_connect($con_string);
412
-		}
413
-
414
-		// if local connection failed or not requested, use TCP/IP
415
-		if (! $this->db)
416
-		{
417
-		    if (! $host) $host = "localhost";
418
-			if (! $port) $port = 5432;
419
-
420
-			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
421
-			$this->db = @pg_connect($con_string);
422
-		}
423
-
424
-		// now we test if at least one connect method was a success
425
-		if ($this->db)
426
-		{
427
-			$this->database_name = $name;
428
-			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);	// Set verbosity to max
429
-			pg_query($this->db, "set datestyle = 'ISO, YMD';");
430
-		}
431
-
432
-		return $this->db;
433
-	}
434
-
435
-	/**
436
-	 *	Return version of database server
437
-	 *
438
-	 *	@return	        string      Version string
439
-	 */
440
-	function getVersion()
441
-	{
442
-		$resql=$this->query('SHOW server_version');
443
-		if ($resql)
444
-		{
445
-		  $liste=$this->fetch_array($resql);
446
-		  return $liste['server_version'];
447
-		}
448
-		return '';
449
-	}
450
-
451
-	/**
452
-	 *	Return version of database client driver
453
-	 *
454
-	 *	@return	        string      Version string
455
-	 */
456
-	function getDriverInfo()
457
-	{
458
-		return 'pgsql php driver';
459
-	}
381
+    /**
382
+     *	Connexion to server
383
+     *
384
+     *	@param	    string		$host		Database server host
385
+     *	@param	    string		$login		Login
386
+     *	@param	    string		$passwd		Password
387
+     *	@param		string		$name		Name of database (not used for mysql, used for pgsql)
388
+     *	@param		integer		$port		Port of database server
389
+     *	@return		false|resource			Database access handler
390
+     *	@see		close
391
+     */
392
+    function connect($host, $login, $passwd, $name, $port=0)
393
+    {
394
+        // use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
395
+
396
+        $this->db = false;
397
+
398
+        // connections parameters must be protected (only \ and ' according to pg_connect() manual)
399
+        $host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
400
+        $login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
401
+        $passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
402
+        $name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
403
+        $port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
404
+
405
+        if (! $name) $name="postgres";    // When try to connect using admin user
406
+
407
+        // try first Unix domain socket (local)
408
+        if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
409
+        {
410
+            $con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'";    // $name may be empty
411
+            $this->db = @pg_connect($con_string);
412
+        }
413
+
414
+        // if local connection failed or not requested, use TCP/IP
415
+        if (! $this->db)
416
+        {
417
+            if (! $host) $host = "localhost";
418
+            if (! $port) $port = 5432;
419
+
420
+            $con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
421
+            $this->db = @pg_connect($con_string);
422
+        }
423
+
424
+        // now we test if at least one connect method was a success
425
+        if ($this->db)
426
+        {
427
+            $this->database_name = $name;
428
+            pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);	// Set verbosity to max
429
+            pg_query($this->db, "set datestyle = 'ISO, YMD';");
430
+        }
431
+
432
+        return $this->db;
433
+    }
434
+
435
+    /**
436
+     *	Return version of database server
437
+     *
438
+     *	@return	        string      Version string
439
+     */
440
+    function getVersion()
441
+    {
442
+        $resql=$this->query('SHOW server_version');
443
+        if ($resql)
444
+        {
445
+            $liste=$this->fetch_array($resql);
446
+            return $liste['server_version'];
447
+        }
448
+        return '';
449
+    }
450
+
451
+    /**
452
+     *	Return version of database client driver
453
+     *
454
+     *	@return	        string      Version string
455
+     */
456
+    function getDriverInfo()
457
+    {
458
+        return 'pgsql php driver';
459
+    }
460 460
 
461 461
     /**
462 462
      *  Close database connexion
@@ -468,97 +468,97 @@  discard block
 block discarded – undo
468 468
     {
469 469
         if ($this->db)
470 470
         {
471
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
472
-          $this->connected=false;
473
-          return pg_close($this->db);
471
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
472
+            $this->connected=false;
473
+            return pg_close($this->db);
474 474
         }
475 475
         return false;
476 476
     }
477 477
 
478
-	/**
479
-	 * Convert request to PostgreSQL syntax, execute it and return the resultset
480
-	 *
481
-	 * @param	string	$query			SQL query string
482
-	 * @param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
478
+    /**
479
+     * Convert request to PostgreSQL syntax, execute it and return the resultset
480
+     *
481
+     * @param	string	$query			SQL query string
482
+     * @param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
483 483
      * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
484
-	 * @return	false|resource			Resultset of answer
485
-	 */
486
-	function query($query,$usesavepoint=0,$type='auto')
487
-	{
488
-		global $conf;
489
-
490
-		$query = trim($query);
491
-
492
-		// Convert MySQL syntax to PostgresSQL syntax
493
-		$query=$this->convertSQLFromMysql($query,$type,($this->unescapeslashquot && $this->standard_conforming_strings));
494
-		//print "After convertSQLFromMysql:\n".$query."<br>\n";
495
-
496
-		if (! empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
497
-		{
498
-			// Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
499
-			$loop=true;
500
-			while ($loop)
501
-			{
502
-				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))
503
-				{
504
-					$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);
505
-					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
506
-				}
507
-				else $loop=false;
508
-			}
509
-		}
510
-
511
-		if ($usesavepoint && $this->transaction_opened)
512
-		{
513
-			@pg_query($this->db, 'SAVEPOINT mysavepoint');
514
-		}
515
-
516
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
517
-
518
-		$ret = @pg_query($this->db, $query);
519
-
520
-		//print $query;
521
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
522
-		{
523
-			if (! $ret)
524
-			{
525
-			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
526
-			    {
527
-    				$this->lastqueryerror = $query;
528
-    				$this->lasterror = $this->error();
529
-    				$this->lasterrno = $this->errno();
530
-
531
-    				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
532
-					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
533
-					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
534
-			    }
535
-
536
-				if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
537
-				{
538
-					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
539
-				}
540
-			}
541
-			$this->lastquery=$query;
542
-			$this->_results = $ret;
543
-		}
544
-
545
-		return $ret;
546
-	}
484
+     * @return	false|resource			Resultset of answer
485
+     */
486
+    function query($query,$usesavepoint=0,$type='auto')
487
+    {
488
+        global $conf;
489
+
490
+        $query = trim($query);
491
+
492
+        // Convert MySQL syntax to PostgresSQL syntax
493
+        $query=$this->convertSQLFromMysql($query,$type,($this->unescapeslashquot && $this->standard_conforming_strings));
494
+        //print "After convertSQLFromMysql:\n".$query."<br>\n";
495
+
496
+        if (! empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
497
+        {
498
+            // Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
499
+            $loop=true;
500
+            while ($loop)
501
+            {
502
+                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))
503
+                {
504
+                    $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);
505
+                    dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
506
+                }
507
+                else $loop=false;
508
+            }
509
+        }
510
+
511
+        if ($usesavepoint && $this->transaction_opened)
512
+        {
513
+            @pg_query($this->db, 'SAVEPOINT mysavepoint');
514
+        }
515
+
516
+        if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
517
+
518
+        $ret = @pg_query($this->db, $query);
519
+
520
+        //print $query;
521
+        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
522
+        {
523
+            if (! $ret)
524
+            {
525
+                if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
526
+                {
527
+                    $this->lastqueryerror = $query;
528
+                    $this->lasterror = $this->error();
529
+                    $this->lasterrno = $this->errno();
530
+
531
+                    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
532
+                    dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
533
+                    dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
534
+                }
535
+
536
+                if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
537
+                {
538
+                    @pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
539
+                }
540
+            }
541
+            $this->lastquery=$query;
542
+            $this->_results = $ret;
543
+        }
544
+
545
+        return $ret;
546
+    }
547 547
 
548 548
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
549
-	/**
550
-	 *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
551
-	 *
552
-	 *	@param	resource	$resultset  Curseur de la requete voulue
553
-	 *	@return	false|object			Object result line or false if KO or end of cursor
554
-	 */
555
-	function fetch_object($resultset)
556
-	{
549
+    /**
550
+     *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
551
+     *
552
+     *	@param	resource	$resultset  Curseur de la requete voulue
553
+     *	@return	false|object			Object result line or false if KO or end of cursor
554
+     */
555
+    function fetch_object($resultset)
556
+    {
557 557
         // phpcs:enable
558 558
         // If resultset not provided, we take the last used by connexion
559
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
560
-		return pg_fetch_object($resultset);
561
-	}
559
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
560
+        return pg_fetch_object($resultset);
561
+    }
562 562
 
563 563
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
564 564
     /**
@@ -566,29 +566,29 @@  discard block
 block discarded – undo
566 566
      *
567 567
      *	@param	resource	$resultset  Resultset of request
568 568
      *	@return	false|array				Array
569
-	 */
570
-	function fetch_array($resultset)
571
-	{
569
+     */
570
+    function fetch_array($resultset)
571
+    {
572 572
         // phpcs:enable
573 573
         // If resultset not provided, we take the last used by connexion
574
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
575
-		return pg_fetch_array($resultset);
576
-	}
574
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
575
+        return pg_fetch_array($resultset);
576
+    }
577 577
 
578 578
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
579
-	/**
579
+    /**
580 580
      *	Return datas as an array
581 581
      *
582 582
      *	@param	resource	$resultset  Resultset of request
583 583
      *	@return	false|array				Array
584
-	 */
585
-	function fetch_row($resultset)
586
-	{
584
+     */
585
+    function fetch_row($resultset)
586
+    {
587 587
         // phpcs:enable
588
-		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
589
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
590
-		return pg_fetch_row($resultset);
591
-	}
588
+        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
589
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
590
+        return pg_fetch_row($resultset);
591
+    }
592 592
 
593 593
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
594 594
     /**
@@ -598,725 +598,725 @@  discard block
 block discarded – undo
598 598
      *	@return int		    			Nb of lines, -1 on error
599 599
      *	@see    affected_rows
600 600
      */
601
-	function num_rows($resultset)
602
-	{
601
+    function num_rows($resultset)
602
+    {
603 603
         // phpcs:enable
604 604
         // If resultset not provided, we take the last used by connexion
605
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
606
-		return pg_num_rows($resultset);
607
-	}
605
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
606
+        return pg_num_rows($resultset);
607
+    }
608 608
 
609 609
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
610
-	/**
611
-	 * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
612
-	 *
613
-	 * @param	resource	$resultset  Result set of request
614
-	 * @return  int		    			Nb of lines
615
-	 * @see 	num_rows
616
-	 */
617
-	function affected_rows($resultset)
618
-	{
610
+    /**
611
+     * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
612
+     *
613
+     * @param	resource	$resultset  Result set of request
614
+     * @return  int		    			Nb of lines
615
+     * @see 	num_rows
616
+     */
617
+    function affected_rows($resultset)
618
+    {
619 619
         // phpcs:enable
620 620
         // If resultset not provided, we take the last used by connexion
621
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
622
-		// pgsql necessite un resultset pour cette fonction contrairement
623
-		// a mysql qui prend un link de base
624
-		return pg_affected_rows($resultset);
625
-	}
626
-
627
-
628
-	/**
629
-	 * Libere le dernier resultset utilise sur cette connexion
630
-	 *
631
-	 * @param	resource	$resultset  Result set of request
632
-	 * @return	void
633
-	 */
634
-	function free($resultset=null)
635
-	{
621
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
622
+        // pgsql necessite un resultset pour cette fonction contrairement
623
+        // a mysql qui prend un link de base
624
+        return pg_affected_rows($resultset);
625
+    }
626
+
627
+
628
+    /**
629
+     * Libere le dernier resultset utilise sur cette connexion
630
+     *
631
+     * @param	resource	$resultset  Result set of request
632
+     * @return	void
633
+     */
634
+    function free($resultset=null)
635
+    {
636 636
         // If resultset not provided, we take the last used by connexion
637
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
638
-		// Si resultset en est un, on libere la memoire
639
-		if (is_resource($resultset)) pg_free_result($resultset);
640
-	}
637
+        if (! is_resource($resultset)) { $resultset=$this->_results; }
638
+        // Si resultset en est un, on libere la memoire
639
+        if (is_resource($resultset)) pg_free_result($resultset);
640
+    }
641 641
 
642 642
 
643
-	/**
643
+    /**
644 644
      *	Define limits and offset of request
645 645
      *
646 646
      *	@param	int		$limit      Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
647 647
      *	@param	int		$offset     Numero of line from where starting fetch
648 648
      *	@return	string      		String with SQL syntax to add a limit and offset
649
-	 */
650
-	function plimit($limit=0,$offset=0)
651
-	{
652
-		global $conf;
649
+     */
650
+    function plimit($limit=0,$offset=0)
651
+    {
652
+        global $conf;
653 653
         if (empty($limit)) return "";
654
-		if ($limit < 0) $limit=$conf->liste_limit;
655
-		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
656
-		else return " LIMIT $limit ";
657
-	}
658
-
659
-
660
-	/**
661
-	 *   Escape a string to insert data
662
-	 *
663
-	 *   @param		string	$stringtoencode		String to escape
664
-	 *   @return	string						String escaped
665
-	 */
666
-	function escape($stringtoencode)
667
-	{
668
-		return pg_escape_string($stringtoencode);
669
-	}
654
+        if ($limit < 0) $limit=$conf->liste_limit;
655
+        if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
656
+        else return " LIMIT $limit ";
657
+    }
658
+
659
+
660
+    /**
661
+     *   Escape a string to insert data
662
+     *
663
+     *   @param		string	$stringtoencode		String to escape
664
+     *   @return	string						String escaped
665
+     */
666
+    function escape($stringtoencode)
667
+    {
668
+        return pg_escape_string($stringtoencode);
669
+    }
670
+
671
+    /**
672
+     *   Convert (by PHP) a GM Timestamp date into a GM string date to insert into a date field.
673
+     *   Function to use to build INSERT, UPDATE or WHERE predica
674
+     *
675
+     *   @param	    string	$param      Date TMS to convert
676
+     *   @return	string   			Date in a string YYYY-MM-DD HH:MM:SS
677
+     */
678
+    function idate($param)
679
+    {
680
+        return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
681
+    }
670 682
 
671 683
     /**
672
-	 *   Convert (by PHP) a GM Timestamp date into a GM string date to insert into a date field.
673
-	 *   Function to use to build INSERT, UPDATE or WHERE predica
674
-	 *
675
-	 *   @param	    string	$param      Date TMS to convert
676
-	 *   @return	string   			Date in a string YYYY-MM-DD HH:MM:SS
677
-	 */
678
-	function idate($param)
679
-	{
680
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
681
-	}
682
-
683
-	/**
684 684
      *  Format a SQL IF
685 685
      *
686
-	 *  @param	string	$test           Test string (example: 'cd.statut=0', 'field IS NULL')
687
-	 *  @param	string	$resok          resultat si test egal
688
-	 *  @param	string	$resko          resultat si test non egal
689
-	 *  @return	string          		chaine formate SQL
690
-	 */
691
-	function ifsql($test,$resok,$resko)
692
-	{
693
-		return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
694
-	}
695
-
696
-	/**
697
-	 * Renvoie le code erreur generique de l'operation precedente.
698
-	 *
699
-	 * @return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
700
-	 */
701
-	function errno()
702
-	{
703
-		if (! $this->connected) {
704
-			// Si il y a eu echec de connexion, $this->db n'est pas valide.
705
-			return 'DB_ERROR_FAILED_TO_CONNECT';
706
-		}
707
-		else {
708
-			// Constants to convert error code to a generic Dolibarr error code
709
-			$errorcode_map = array(
710
-			1004 => 'DB_ERROR_CANNOT_CREATE',
711
-			1005 => 'DB_ERROR_CANNOT_CREATE',
712
-			1006 => 'DB_ERROR_CANNOT_CREATE',
713
-			1007 => 'DB_ERROR_ALREADY_EXISTS',
714
-			1008 => 'DB_ERROR_CANNOT_DROP',
715
-			1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
716
-			1044 => 'DB_ERROR_ACCESSDENIED',
717
-			1046 => 'DB_ERROR_NODBSELECTED',
718
-			1048 => 'DB_ERROR_CONSTRAINT',
719
-			'42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
720
-			'42703' => 'DB_ERROR_NOSUCHFIELD',
721
-			1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
722
-			42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
723
-			'42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
724
-			'23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
725
-			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP',		// May also be Type xxx does not exists
726
-			'42601' => 'DB_ERROR_SYNTAX',
727
-			'42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
728
-			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
729
-			1091 => 'DB_ERROR_NOSUCHFIELD',
730
-			1100 => 'DB_ERROR_NOT_LOCKED',
731
-			1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
732
-			'42P01' => 'DB_ERROR_NOSUCHTABLE',
733
-			'23503' => 'DB_ERROR_NO_PARENT',
734
-			1217 => 'DB_ERROR_CHILD_EXISTS',
735
-			1451 => 'DB_ERROR_CHILD_EXISTS',
736
-			'42P04' => 'DB_DATABASE_ALREADY_EXISTS'
737
-			);
738
-
739
-			$errorlabel=pg_last_error($this->db);
740
-			$errorcode='';
741
-			if (preg_match('/: *([0-9P]+):/',$errorlabel,$reg))
742
-			{
743
-				$errorcode=$reg[1];
744
-				if (isset($errorcode_map[$errorcode]))
745
-				{
746
-					return $errorcode_map[$errorcode];
747
-				}
748
-			}
749
-			$errno=$errorcode?$errorcode:$errorlabel;
750
-			return ($errno?'DB_ERROR_'.$errno:'0');
751
-		}
752
-		//                '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
753
-		//                '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
754
-		//                '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => 'DB_ERROR_RECORD_ALREADY_EXISTS',
755
-		//                '/divide by zero$/'                     => 'DB_ERROR_DIVZERO',
756
-		//                '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
757
-		//                '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
758
-		//                '/parser: parse error at or near \"/'   => 'DB_ERROR_SYNTAX',
759
-		//                '/referential integrity violation/'     => 'DB_ERROR_CONSTRAINT'
760
-	}
761
-
762
-	/**
763
-	 * Renvoie le texte de l'erreur pgsql de l'operation precedente
764
-	 *
765
-	 * @return	string		Error text
766
-	 */
767
-	function error()
768
-	{
769
-		return pg_last_error($this->db);
770
-	}
686
+     *  @param	string	$test           Test string (example: 'cd.statut=0', 'field IS NULL')
687
+     *  @param	string	$resok          resultat si test egal
688
+     *  @param	string	$resko          resultat si test non egal
689
+     *  @return	string          		chaine formate SQL
690
+     */
691
+    function ifsql($test,$resok,$resko)
692
+    {
693
+        return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
694
+    }
695
+
696
+    /**
697
+     * Renvoie le code erreur generique de l'operation precedente.
698
+     *
699
+     * @return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
700
+     */
701
+    function errno()
702
+    {
703
+        if (! $this->connected) {
704
+            // Si il y a eu echec de connexion, $this->db n'est pas valide.
705
+            return 'DB_ERROR_FAILED_TO_CONNECT';
706
+        }
707
+        else {
708
+            // Constants to convert error code to a generic Dolibarr error code
709
+            $errorcode_map = array(
710
+            1004 => 'DB_ERROR_CANNOT_CREATE',
711
+            1005 => 'DB_ERROR_CANNOT_CREATE',
712
+            1006 => 'DB_ERROR_CANNOT_CREATE',
713
+            1007 => 'DB_ERROR_ALREADY_EXISTS',
714
+            1008 => 'DB_ERROR_CANNOT_DROP',
715
+            1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
716
+            1044 => 'DB_ERROR_ACCESSDENIED',
717
+            1046 => 'DB_ERROR_NODBSELECTED',
718
+            1048 => 'DB_ERROR_CONSTRAINT',
719
+            '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
720
+            '42703' => 'DB_ERROR_NOSUCHFIELD',
721
+            1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
722
+            42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
723
+            '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
724
+            '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
725
+            '42704' => 'DB_ERROR_NO_INDEX_TO_DROP',		// May also be Type xxx does not exists
726
+            '42601' => 'DB_ERROR_SYNTAX',
727
+            '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
728
+            1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
729
+            1091 => 'DB_ERROR_NOSUCHFIELD',
730
+            1100 => 'DB_ERROR_NOT_LOCKED',
731
+            1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
732
+            '42P01' => 'DB_ERROR_NOSUCHTABLE',
733
+            '23503' => 'DB_ERROR_NO_PARENT',
734
+            1217 => 'DB_ERROR_CHILD_EXISTS',
735
+            1451 => 'DB_ERROR_CHILD_EXISTS',
736
+            '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
737
+            );
738
+
739
+            $errorlabel=pg_last_error($this->db);
740
+            $errorcode='';
741
+            if (preg_match('/: *([0-9P]+):/',$errorlabel,$reg))
742
+            {
743
+                $errorcode=$reg[1];
744
+                if (isset($errorcode_map[$errorcode]))
745
+                {
746
+                    return $errorcode_map[$errorcode];
747
+                }
748
+            }
749
+            $errno=$errorcode?$errorcode:$errorlabel;
750
+            return ($errno?'DB_ERROR_'.$errno:'0');
751
+        }
752
+        //                '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
753
+        //                '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
754
+        //                '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => 'DB_ERROR_RECORD_ALREADY_EXISTS',
755
+        //                '/divide by zero$/'                     => 'DB_ERROR_DIVZERO',
756
+        //                '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
757
+        //                '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
758
+        //                '/parser: parse error at or near \"/'   => 'DB_ERROR_SYNTAX',
759
+        //                '/referential integrity violation/'     => 'DB_ERROR_CONSTRAINT'
760
+    }
761
+
762
+    /**
763
+     * Renvoie le texte de l'erreur pgsql de l'operation precedente
764
+     *
765
+     * @return	string		Error text
766
+     */
767
+    function error()
768
+    {
769
+        return pg_last_error($this->db);
770
+    }
771 771
 
772 772
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
773
-	/**
774
-	 * Get last ID after an insert INSERT
775
-	 *
776
-	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
777
-	 * @param	string	$fieldid	Field name
778
-	 * @return  string     			Id of row
779
-	 */
780
-	function last_insert_id($tab,$fieldid='rowid')
781
-	{
773
+    /**
774
+     * Get last ID after an insert INSERT
775
+     *
776
+     * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
777
+     * @param	string	$fieldid	Field name
778
+     * @return  string     			Id of row
779
+     */
780
+    function last_insert_id($tab,$fieldid='rowid')
781
+    {
782 782
         // phpcs:enable
783
-		//$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
784
-		$result = pg_query($this->db,"SELECT currval('".$tab."_".$fieldid."_seq')");
785
-		if (! $result)
786
-		{
787
-			print pg_last_error($this->db);
788
-			exit;
789
-		}
790
-		//$nbre = pg_num_rows($result);
791
-		$row = pg_fetch_result($result,0,0);
792
-		return $row;
793
-	}
794
-
795
-	/**
783
+        //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
784
+        $result = pg_query($this->db,"SELECT currval('".$tab."_".$fieldid."_seq')");
785
+        if (! $result)
786
+        {
787
+            print pg_last_error($this->db);
788
+            exit;
789
+        }
790
+        //$nbre = pg_num_rows($result);
791
+        $row = pg_fetch_result($result,0,0);
792
+        return $row;
793
+    }
794
+
795
+    /**
796 796
      *  Encrypt sensitive data in database
797 797
      *  Warning: This function includes the escape, so it must use direct value
798 798
      *
799 799
      *  @param  string  $fieldorvalue   Field name or value to encrypt
800 800
      *  @param	int		$withQuotes     Return string with quotes
801 801
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
802
-	 */
803
-	function encrypt($fieldorvalue, $withQuotes=0)
804
-	{
805
-		global $conf;
802
+     */
803
+    function encrypt($fieldorvalue, $withQuotes=0)
804
+    {
805
+        global $conf;
806 806
 
807
-		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
808
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
807
+        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
808
+        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
809 809
 
810
-		//Encryption key
811
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
810
+        //Encryption key
811
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
812 812
 
813
-		$return = $fieldorvalue;
814
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
815
-	}
813
+        $return = $fieldorvalue;
814
+        return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
815
+    }
816 816
 
817 817
 
818
-	/**
819
-	 *	Decrypt sensitive data in database
820
-	 *
821
-	 *	@param	int		$value			Value to decrypt
822
-	 * 	@return	string					Decrypted value if used
823
-	 */
824
-	function decrypt($value)
825
-	{
826
-		global $conf;
818
+    /**
819
+     *	Decrypt sensitive data in database
820
+     *
821
+     *	@param	int		$value			Value to decrypt
822
+     * 	@return	string					Decrypted value if used
823
+     */
824
+    function decrypt($value)
825
+    {
826
+        global $conf;
827 827
 
828
-		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
829
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
828
+        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
829
+        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
830 830
 
831
-		//Encryption key
832
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
831
+        //Encryption key
832
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
833 833
 
834
-		$return = $value;
835
-		return $return;
836
-	}
834
+        $return = $value;
835
+        return $return;
836
+    }
837 837
 
838 838
 
839 839
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
840
-	/**
841
-	 * Return connexion ID
842
-	 *
843
-	 * @return	        string      Id connexion
844
-	 */
845
-	function DDLGetConnectId()
846
-	{
840
+    /**
841
+     * Return connexion ID
842
+     *
843
+     * @return	        string      Id connexion
844
+     */
845
+    function DDLGetConnectId()
846
+    {
847 847
         // phpcs:enable
848
-		return '?';
849
-	}
848
+        return '?';
849
+    }
850 850
 
851 851
 
852 852
 
853 853
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
854
-	/**
855
-	 *	Create a new database
856
-	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
857
-	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
858
-	 *
859
-	 *	@param	string	$database		Database name to create
860
-	 * 	@param	string	$charset		Charset used to store data
861
-	 * 	@param	string	$collation		Charset used to sort data
862
-	 * 	@param	string	$owner			Username of database owner
863
-	 * 	@return	false|resource				resource defined if OK, null if KO
864
-	 */
865
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
866
-	{
854
+    /**
855
+     *	Create a new database
856
+     *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
857
+     *	We force to create database with charset this->forcecharset and collate this->forcecollate
858
+     *
859
+     *	@param	string	$database		Database name to create
860
+     * 	@param	string	$charset		Charset used to store data
861
+     * 	@param	string	$collation		Charset used to sort data
862
+     * 	@param	string	$owner			Username of database owner
863
+     * 	@return	false|resource				resource defined if OK, null if KO
864
+     */
865
+    function DDLCreateDb($database,$charset='',$collation='',$owner='')
866
+    {
867 867
         // phpcs:enable
868
-	    if (empty($charset))   $charset=$this->forcecharset;
869
-		if (empty($collation)) $collation=$this->forcecollate;
868
+        if (empty($charset))   $charset=$this->forcecharset;
869
+        if (empty($collation)) $collation=$this->forcecollate;
870 870
 
871
-		// Test charset match LC_TYPE (pgsql error otherwise)
872
-		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
871
+        // Test charset match LC_TYPE (pgsql error otherwise)
872
+        //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
873 873
 
874
-		$sql='CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
875
-		dol_syslog($sql,LOG_DEBUG);
876
-		$ret=$this->query($sql);
877
-		return $ret;
878
-	}
874
+        $sql='CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
875
+        dol_syslog($sql,LOG_DEBUG);
876
+        $ret=$this->query($sql);
877
+        return $ret;
878
+    }
879 879
 
880 880
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
881
-	/**
882
-	 *  List tables into a database
883
-	 *
884
-	 *  @param	string		$database	Name of database
885
-	 *  @param	string		$table		Name of table filter ('xxx%')
886
-	 *  @return	array					List of tables in an array
887
-	 */
888
-	function DDLListTables($database, $table='')
881
+    /**
882
+     *  List tables into a database
883
+     *
884
+     *  @param	string		$database	Name of database
885
+     *  @param	string		$table		Name of table filter ('xxx%')
886
+     *  @return	array					List of tables in an array
887
+     */
888
+    function DDLListTables($database, $table='')
889 889
     {
890 890
         // phpcs:enable
891
-		$listtables=array();
891
+        $listtables=array();
892 892
 
893
-		$like = '';
894
-		if ($table) $like = " AND table_name LIKE '".$table."'";
895
-		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
893
+        $like = '';
894
+        if ($table) $like = " AND table_name LIKE '".$table."'";
895
+        $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
896 896
         if ($result)
897 897
         {
898
-    		while($row = $this->fetch_row($result))
899
-    		{
900
-    			$listtables[] = $row[0];
901
-    		}
898
+            while($row = $this->fetch_row($result))
899
+            {
900
+                $listtables[] = $row[0];
901
+            }
902 902
         }
903
-		return $listtables;
904
-	}
903
+        return $listtables;
904
+    }
905 905
 
906 906
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
907
-	/**
908
-	 *	List information of columns into a table.
909
-	 *
910
-	 *	@param	string	$table		Name of table
911
-	 *	@return	array				Tableau des informations des champs de la table
912
-	 *
913
-	 */
914
-	function DDLInfoTable($table)
915
-	{
907
+    /**
908
+     *	List information of columns into a table.
909
+     *
910
+     *	@param	string	$table		Name of table
911
+     *	@return	array				Tableau des informations des champs de la table
912
+     *
913
+     */
914
+    function DDLInfoTable($table)
915
+    {
916 916
         // phpcs:enable
917
-		$infotables=array();
918
-
919
-		$sql="SELECT ";
920
-		$sql.="	infcol.column_name as \"Column\",";
921
-		$sql.="	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
922
-		$sql.="		ELSE infcol.udt_name";
923
-		$sql.="	END as \"Type\",";
924
-		$sql.="	infcol.collation_name as \"Collation\",";
925
-		$sql.="	infcol.is_nullable as \"Null\",";
926
-		$sql.="	'' as \"Key\",";
927
-		$sql.="	infcol.column_default as \"Default\",";
928
-		$sql.="	'' as \"Extra\",";
929
-		$sql.="	'' as \"Privileges\"";
930
-		$sql.="	FROM information_schema.columns infcol";
931
-		$sql.="	WHERE table_schema='public' ";
932
-		$sql.="	AND table_name='".$table."'";
933
-		$sql.="	ORDER BY ordinal_position;";
934
-
935
-		dol_syslog($sql,LOG_DEBUG);
936
-		$result = $this->query($sql);
937
-		if ($result)
938
-		{
939
-    		 while($row = $this->fetch_row($result))
940
-    		 {
941
-    			$infotables[] = $row;
942
-    		 }
943
-		}
917
+        $infotables=array();
918
+
919
+        $sql="SELECT ";
920
+        $sql.="	infcol.column_name as \"Column\",";
921
+        $sql.="	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
922
+        $sql.="		ELSE infcol.udt_name";
923
+        $sql.="	END as \"Type\",";
924
+        $sql.="	infcol.collation_name as \"Collation\",";
925
+        $sql.="	infcol.is_nullable as \"Null\",";
926
+        $sql.="	'' as \"Key\",";
927
+        $sql.="	infcol.column_default as \"Default\",";
928
+        $sql.="	'' as \"Extra\",";
929
+        $sql.="	'' as \"Privileges\"";
930
+        $sql.="	FROM information_schema.columns infcol";
931
+        $sql.="	WHERE table_schema='public' ";
932
+        $sql.="	AND table_name='".$table."'";
933
+        $sql.="	ORDER BY ordinal_position;";
934
+
935
+        dol_syslog($sql,LOG_DEBUG);
936
+        $result = $this->query($sql);
937
+        if ($result)
938
+        {
939
+                while($row = $this->fetch_row($result))
940
+                {
941
+                $infotables[] = $row;
942
+                }
943
+        }
944 944
         return $infotables;
945
-	}
945
+    }
946 946
 
947 947
 
948 948
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
949
-	/**
950
-	 *	Create a table into database
951
-	 *
952
-	 *	@param	    string	$table 			Nom de la table
953
-	 *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
954
-	 *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
955
-	 *	@param	    string	$type 			Type de la table
956
-	 *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
957
-	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
958
-	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
959
-	 *	@return	    int						<0 if KO, >=0 if OK
960
-	 */
961
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
962
-	{
949
+    /**
950
+     *	Create a table into database
951
+     *
952
+     *	@param	    string	$table 			Nom de la table
953
+     *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
954
+     *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
955
+     *	@param	    string	$type 			Type de la table
956
+     *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
957
+     *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
958
+     *	@param	    array	$keys 			Tableau des champs cles noms => valeur
959
+     *	@return	    int						<0 if KO, >=0 if OK
960
+     */
961
+    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
962
+    {
963 963
         // phpcs:enable
964
-		// FIXME: $fulltext_keys parameter is unused
965
-
966
-		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
967
-		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
968
-		$sql = "create table ".$table."(";
969
-		$i=0;
970
-		foreach($fields as $field_name => $field_desc)
971
-		{
972
-			$sqlfields[$i] = $field_name." ";
973
-			$sqlfields[$i]  .= $field_desc['type'];
974
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
975
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
976
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
977
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
978
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
979
-			{
980
-				if(preg_match("/null/i",$field_desc['default']))
981
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
982
-				else
983
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
984
-			}
985
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
986
-			$sqlfields[$i]  .= " ".$field_desc['null'];
987
-
988
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
989
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
990
-			$i++;
991
-		}
992
-		if($primary_key != "")
993
-		$pk = "primary key(".$primary_key.")";
994
-
995
-		if(is_array($unique_keys))
996
-		{
997
-			$i = 0;
998
-			foreach($unique_keys as $key => $value)
999
-			{
1000
-				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
1001
-				$i++;
1002
-			}
1003
-		}
1004
-		if(is_array($keys))
1005
-		{
1006
-			$i = 0;
1007
-			foreach($keys as $key => $value)
1008
-			{
1009
-				$sqlk[$i] = "KEY ".$key." (".$value.")";
1010
-				$i++;
1011
-			}
1012
-		}
1013
-		$sql .= implode(',',$sqlfields);
1014
-		if($primary_key != "")
1015
-		$sql .= ",".$pk;
1016
-		if(is_array($unique_keys))
1017
-		$sql .= ",".implode(',',$sqluq);
1018
-		if(is_array($keys))
1019
-		$sql .= ",".implode(',',$sqlk);
1020
-		$sql .=") type=".$type;
1021
-
1022
-		dol_syslog($sql,LOG_DEBUG);
1023
-		if(! $this->query($sql))
1024
-		return -1;
1025
-		else
1026
-		return 1;
1027
-	}
964
+        // FIXME: $fulltext_keys parameter is unused
965
+
966
+        // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
967
+        // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
968
+        $sql = "create table ".$table."(";
969
+        $i=0;
970
+        foreach($fields as $field_name => $field_desc)
971
+        {
972
+            $sqlfields[$i] = $field_name." ";
973
+            $sqlfields[$i]  .= $field_desc['type'];
974
+            if( preg_match("/^[^\s]/i",$field_desc['value']))
975
+            $sqlfields[$i]  .= "(".$field_desc['value'].")";
976
+            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
977
+            $sqlfields[$i]  .= " ".$field_desc['attribute'];
978
+            else if( preg_match("/^[^\s]/i",$field_desc['default']))
979
+            {
980
+                if(preg_match("/null/i",$field_desc['default']))
981
+                $sqlfields[$i]  .= " default ".$field_desc['default'];
982
+                else
983
+                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
984
+            }
985
+            else if( preg_match("/^[^\s]/i",$field_desc['null']))
986
+            $sqlfields[$i]  .= " ".$field_desc['null'];
987
+
988
+            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
989
+            $sqlfields[$i]  .= " ".$field_desc['extra'];
990
+            $i++;
991
+        }
992
+        if($primary_key != "")
993
+        $pk = "primary key(".$primary_key.")";
994
+
995
+        if(is_array($unique_keys))
996
+        {
997
+            $i = 0;
998
+            foreach($unique_keys as $key => $value)
999
+            {
1000
+                $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
1001
+                $i++;
1002
+            }
1003
+        }
1004
+        if(is_array($keys))
1005
+        {
1006
+            $i = 0;
1007
+            foreach($keys as $key => $value)
1008
+            {
1009
+                $sqlk[$i] = "KEY ".$key." (".$value.")";
1010
+                $i++;
1011
+            }
1012
+        }
1013
+        $sql .= implode(',',$sqlfields);
1014
+        if($primary_key != "")
1015
+        $sql .= ",".$pk;
1016
+        if(is_array($unique_keys))
1017
+        $sql .= ",".implode(',',$sqluq);
1018
+        if(is_array($keys))
1019
+        $sql .= ",".implode(',',$sqlk);
1020
+        $sql .=") type=".$type;
1021
+
1022
+        dol_syslog($sql,LOG_DEBUG);
1023
+        if(! $this->query($sql))
1024
+        return -1;
1025
+        else
1026
+        return 1;
1027
+    }
1028 1028
 
1029 1029
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1030
-	/**
1031
-	 *	Drop a table into database
1032
-	 *
1033
-	 *	@param	    string	$table 			Name of table
1034
-	 *	@return	    int						<0 if KO, >=0 if OK
1035
-	 */
1036
-	function DDLDropTable($table)
1037
-	{
1030
+    /**
1031
+     *	Drop a table into database
1032
+     *
1033
+     *	@param	    string	$table 			Name of table
1034
+     *	@return	    int						<0 if KO, >=0 if OK
1035
+     */
1036
+    function DDLDropTable($table)
1037
+    {
1038 1038
         // phpcs:enable
1039
-		$sql = "DROP TABLE ".$table;
1039
+        $sql = "DROP TABLE ".$table;
1040 1040
 
1041
-		if (! $this->query($sql))
1042
-			return -1;
1043
-		else
1044
-			return 1;
1045
-	}
1041
+        if (! $this->query($sql))
1042
+            return -1;
1043
+        else
1044
+            return 1;
1045
+    }
1046 1046
 
1047 1047
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1048
-	/**
1049
-	 * 	Create a user to connect to database
1050
-	 *
1051
-	 *	@param	string	$dolibarr_main_db_host 		Ip server
1052
-	 *	@param	string	$dolibarr_main_db_user 		Name of user to create
1053
-	 *	@param	string	$dolibarr_main_db_pass 		Password of user to create
1054
-	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1055
-	 *	@return	int									<0 if KO, >=0 if OK
1056
-	 */
1057
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1058
-	{
1048
+    /**
1049
+     * 	Create a user to connect to database
1050
+     *
1051
+     *	@param	string	$dolibarr_main_db_host 		Ip server
1052
+     *	@param	string	$dolibarr_main_db_user 		Name of user to create
1053
+     *	@param	string	$dolibarr_main_db_pass 		Password of user to create
1054
+     *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1055
+     *	@return	int									<0 if KO, >=0 if OK
1056
+     */
1057
+    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1058
+    {
1059 1059
         // phpcs:enable
1060
-		// Note: using ' on user does not works with pgsql
1061
-		$sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1060
+        // Note: using ' on user does not works with pgsql
1061
+        $sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1062 1062
 
1063
-		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1064
-		$resql=$this->query($sql);
1065
-		if (! $resql)
1066
-		{
1067
-			return -1;
1068
-		}
1063
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1064
+        $resql=$this->query($sql);
1065
+        if (! $resql)
1066
+        {
1067
+            return -1;
1068
+        }
1069 1069
 
1070
-		return 1;
1071
-	}
1070
+        return 1;
1071
+    }
1072 1072
 
1073 1073
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1074
-	/**
1075
-	 *	Return a pointer of line with description of a table or field
1076
-	 *
1077
-	 *	@param	string		$table	Name of table
1078
-	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1079
-	 *	@return	false|resource		Resultset x (x->attname)
1080
-	 */
1081
-	function DDLDescTable($table,$field="")
1082
-	{
1074
+    /**
1075
+     *	Return a pointer of line with description of a table or field
1076
+     *
1077
+     *	@param	string		$table	Name of table
1078
+     *	@param	string		$field	Optionnel : Name of field if we want description of field
1079
+     *	@return	false|resource		Resultset x (x->attname)
1080
+     */
1081
+    function DDLDescTable($table,$field="")
1082
+    {
1083 1083
         // phpcs:enable
1084
-		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1085
-		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1086
-		if ($field) $sql.= " AND attname = '".$field."'";
1084
+        $sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1085
+        $sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1086
+        if ($field) $sql.= " AND attname = '".$field."'";
1087 1087
 
1088
-		dol_syslog($sql,LOG_DEBUG);
1089
-		$this->_results = $this->query($sql);
1090
-		return $this->_results;
1091
-	}
1088
+        dol_syslog($sql,LOG_DEBUG);
1089
+        $this->_results = $this->query($sql);
1090
+        return $this->_results;
1091
+    }
1092 1092
 
1093 1093
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1094
-	/**
1095
-	 *	Create a new field into table
1096
-	 *
1097
-	 *	@param	string	$table 				Name of table
1098
-	 *	@param	string	$field_name 		Name of field to add
1099
-	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
1100
-	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1101
-	 *	@return	int							<0 if KO, >0 if OK
1102
-	 */
1103
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
1104
-	{
1094
+    /**
1095
+     *	Create a new field into table
1096
+     *
1097
+     *	@param	string	$table 				Name of table
1098
+     *	@param	string	$field_name 		Name of field to add
1099
+     *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
1100
+     *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1101
+     *	@return	int							<0 if KO, >0 if OK
1102
+     */
1103
+    function DDLAddField($table,$field_name,$field_desc,$field_position="")
1104
+    {
1105 1105
         // phpcs:enable
1106
-		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1107
-		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1108
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1109
-		$sql .= $field_desc['type'];
1110
-		if (preg_match("/^[^\s]/i",$field_desc['value']))
1111
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1112
-		    {
1113
-		        $sql.= "(".$field_desc['value'].")";
1114
-		    }
1115
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1106
+        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1107
+        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1108
+        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1109
+        $sql .= $field_desc['type'];
1110
+        if (preg_match("/^[^\s]/i",$field_desc['value']))
1111
+            if (! in_array($field_desc['type'],array('int','date','datetime')))
1112
+            {
1113
+                $sql.= "(".$field_desc['value'].")";
1114
+            }
1115
+        if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1116 1116
             $sql .= " ".$field_desc['attribute'];
1117
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1117
+        if (preg_match("/^[^\s]/i",$field_desc['null']))
1118 1118
             $sql .= " ".$field_desc['null'];
1119
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1119
+        if (preg_match("/^[^\s]/i",$field_desc['default']))
1120 1120
             if (preg_match("/null/i",$field_desc['default']))
1121 1121
                 $sql .= " default ".$field_desc['default'];
1122
-		    else
1122
+            else
1123 1123
                 $sql .= " default '".$field_desc['default']."'";
1124
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1124
+        if (preg_match("/^[^\s]/i",$field_desc['extra']))
1125 1125
             $sql .= " ".$field_desc['extra'];
1126
-		$sql .= " ".$field_position;
1126
+        $sql .= " ".$field_position;
1127 1127
 
1128
-		dol_syslog($sql,LOG_DEBUG);
1129
-		if (! $this -> query($sql))
1130
-			return -1;
1131
-		return 1;
1132
-	}
1128
+        dol_syslog($sql,LOG_DEBUG);
1129
+        if (! $this -> query($sql))
1130
+            return -1;
1131
+        return 1;
1132
+    }
1133 1133
 
1134 1134
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1135
-	/**
1136
-	 *	Update format of a field into a table
1137
-	 *
1138
-	 *	@param	string	$table 				Name of table
1139
-	 *	@param	string	$field_name 		Name of field to modify
1140
-	 *	@param	string	$field_desc 		Array with description of field format
1141
-	 *	@return	int							<0 if KO, >0 if OK
1142
-	 */
1143
-	function DDLUpdateField($table,$field_name,$field_desc)
1144
-	{
1135
+    /**
1136
+     *	Update format of a field into a table
1137
+     *
1138
+     *	@param	string	$table 				Name of table
1139
+     *	@param	string	$field_name 		Name of field to modify
1140
+     *	@param	string	$field_desc 		Array with description of field format
1141
+     *	@return	int							<0 if KO, >0 if OK
1142
+     */
1143
+    function DDLUpdateField($table,$field_name,$field_desc)
1144
+    {
1145 1145
         // phpcs:enable
1146
-		$sql = "ALTER TABLE ".$table;
1147
-		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1148
-		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1149
-			$sql.="(".$field_desc['value'].")";
1150
-		}
1151
-
1152
-		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
1153
-		{
1154
-        	// 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
1155
-        	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1156
-        	{
1157
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1158
-        		$this->query($sqlbis);
1159
-        	}
1160
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1161
-        	{
1162
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1163
-        		$this->query($sqlbis);
1164
-        	}
1165
-		}
1166
-
1167
-		if ($field_desc['default'] != '')
1168
-		{
1169
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1170
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1171
-		}
1172
-
1173
-		dol_syslog($sql,LOG_DEBUG);
1174
-		if (! $this->query($sql))
1175
-			return -1;
1176
-		return 1;
1177
-	}
1146
+        $sql = "ALTER TABLE ".$table;
1147
+        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1148
+        if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1149
+            $sql.="(".$field_desc['value'].")";
1150
+        }
1151
+
1152
+        if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
1153
+        {
1154
+            // 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
1155
+            if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1156
+            {
1157
+                $sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1158
+                $this->query($sqlbis);
1159
+            }
1160
+            elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1161
+            {
1162
+                $sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1163
+                $this->query($sqlbis);
1164
+            }
1165
+        }
1166
+
1167
+        if ($field_desc['default'] != '')
1168
+        {
1169
+            if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1170
+            elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1171
+        }
1172
+
1173
+        dol_syslog($sql,LOG_DEBUG);
1174
+        if (! $this->query($sql))
1175
+            return -1;
1176
+        return 1;
1177
+    }
1178 1178
 
1179 1179
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1180
-	/**
1181
-	 *	Drop a field from table
1182
-	 *
1183
-	 *	@param	string	$table 			Name of table
1184
-	 *	@param	string	$field_name 	Name of field to drop
1185
-	 *	@return	int						<0 if KO, >0 if OK
1186
-	 */
1187
-	function DDLDropField($table,$field_name)
1188
-	{
1180
+    /**
1181
+     *	Drop a field from table
1182
+     *
1183
+     *	@param	string	$table 			Name of table
1184
+     *	@param	string	$field_name 	Name of field to drop
1185
+     *	@return	int						<0 if KO, >0 if OK
1186
+     */
1187
+    function DDLDropField($table,$field_name)
1188
+    {
1189 1189
         // phpcs:enable
1190
-		$sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1191
-		dol_syslog($sql,LOG_DEBUG);
1192
-		if (! $this->query($sql))
1193
-		{
1194
-			$this->error=$this->lasterror();
1195
-			return -1;
1196
-		}
1197
-		return 1;
1198
-	}
1199
-
1200
-	/**
1201
-	 *	Return charset used to store data in database
1202
-	 *
1203
-	 *	@return		string		Charset
1204
-	 */
1205
-	function getDefaultCharacterSetDatabase()
1206
-	{
1207
-		$resql=$this->query('SHOW SERVER_ENCODING');
1208
-		if ($resql)
1209
-		{
1190
+        $sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1191
+        dol_syslog($sql,LOG_DEBUG);
1192
+        if (! $this->query($sql))
1193
+        {
1194
+            $this->error=$this->lasterror();
1195
+            return -1;
1196
+        }
1197
+        return 1;
1198
+    }
1199
+
1200
+    /**
1201
+     *	Return charset used to store data in database
1202
+     *
1203
+     *	@return		string		Charset
1204
+     */
1205
+    function getDefaultCharacterSetDatabase()
1206
+    {
1207
+        $resql=$this->query('SHOW SERVER_ENCODING');
1208
+        if ($resql)
1209
+        {
1210 1210
             $liste=$this->fetch_array($resql);
1211
-		    return $liste['server_encoding'];
1212
-		}
1213
-		else return '';
1214
-	}
1215
-
1216
-	/**
1217
-	 *	Return list of available charset that can be used to store data in database
1218
-	 *
1219
-	 *	@return		array		List of Charset
1220
-	 */
1221
-	function getListOfCharacterSet()
1222
-	{
1223
-		$resql=$this->query('SHOW SERVER_ENCODING');
1224
-		$liste = array();
1225
-		if ($resql)
1226
-		{
1227
-			$i = 0;
1228
-			while ($obj = $this->fetch_object($resql))
1229
-			{
1230
-				$liste[$i]['charset'] = $obj->server_encoding;
1231
-				$liste[$i]['description'] = 'Default database charset';
1232
-				$i++;
1233
-			}
1234
-			$this->free($resql);
1235
-		} else {
1236
-			return null;
1237
-		}
1238
-		return $liste;
1239
-	}
1240
-
1241
-	/**
1242
-	 *	Return collation used in database
1243
-	 *
1244
-	 *	@return		string		Collation value
1245
-	 */
1246
-	function getDefaultCollationDatabase()
1247
-	{
1248
-		$resql=$this->query('SHOW LC_COLLATE');
1249
-		if ($resql)
1250
-		{
1251
-		    $liste=$this->fetch_array($resql);
1252
-			return $liste['lc_collate'];
1253
-		}
1254
-		else return '';
1255
-	}
1256
-
1257
-	/**
1258
-	 *	Return list of available collation that can be used for database
1259
-	 *
1260
-	 *	@return		array		Liste of Collation
1261
-	 */
1262
-	function getListOfCollation()
1263
-	{
1264
-		$resql=$this->query('SHOW LC_COLLATE');
1265
-		$liste = array();
1266
-		if ($resql)
1267
-		{
1268
-			$i = 0;
1269
-			while ($obj = $this->fetch_object($resql) )
1270
-			{
1271
-				$liste[$i]['collation'] = $obj->lc_collate;
1272
-				$i++;
1273
-			}
1274
-			$this->free($resql);
1275
-		} else {
1276
-			return null;
1277
-		}
1278
-		return $liste;
1279
-	}
1280
-
1281
-	/**
1282
-	 *	Return full path of dump program
1283
-	 *
1284
-	 *	@return		string		Full path of dump program
1285
-	 */
1286
-	function getPathOfDump()
1287
-	{
1288
-		$fullpathofdump='/pathtopgdump/pg_dump';
1289
-
1290
-		if (file_exists('/usr/bin/pg_dump'))
1291
-		{
1292
-		    $fullpathofdump='/usr/bin/pg_dump';
1293
-		}
1294
-		else
1295
-		{
1211
+            return $liste['server_encoding'];
1212
+        }
1213
+        else return '';
1214
+    }
1215
+
1216
+    /**
1217
+     *	Return list of available charset that can be used to store data in database
1218
+     *
1219
+     *	@return		array		List of Charset
1220
+     */
1221
+    function getListOfCharacterSet()
1222
+    {
1223
+        $resql=$this->query('SHOW SERVER_ENCODING');
1224
+        $liste = array();
1225
+        if ($resql)
1226
+        {
1227
+            $i = 0;
1228
+            while ($obj = $this->fetch_object($resql))
1229
+            {
1230
+                $liste[$i]['charset'] = $obj->server_encoding;
1231
+                $liste[$i]['description'] = 'Default database charset';
1232
+                $i++;
1233
+            }
1234
+            $this->free($resql);
1235
+        } else {
1236
+            return null;
1237
+        }
1238
+        return $liste;
1239
+    }
1240
+
1241
+    /**
1242
+     *	Return collation used in database
1243
+     *
1244
+     *	@return		string		Collation value
1245
+     */
1246
+    function getDefaultCollationDatabase()
1247
+    {
1248
+        $resql=$this->query('SHOW LC_COLLATE');
1249
+        if ($resql)
1250
+        {
1251
+            $liste=$this->fetch_array($resql);
1252
+            return $liste['lc_collate'];
1253
+        }
1254
+        else return '';
1255
+    }
1256
+
1257
+    /**
1258
+     *	Return list of available collation that can be used for database
1259
+     *
1260
+     *	@return		array		Liste of Collation
1261
+     */
1262
+    function getListOfCollation()
1263
+    {
1264
+        $resql=$this->query('SHOW LC_COLLATE');
1265
+        $liste = array();
1266
+        if ($resql)
1267
+        {
1268
+            $i = 0;
1269
+            while ($obj = $this->fetch_object($resql) )
1270
+            {
1271
+                $liste[$i]['collation'] = $obj->lc_collate;
1272
+                $i++;
1273
+            }
1274
+            $this->free($resql);
1275
+        } else {
1276
+            return null;
1277
+        }
1278
+        return $liste;
1279
+    }
1280
+
1281
+    /**
1282
+     *	Return full path of dump program
1283
+     *
1284
+     *	@return		string		Full path of dump program
1285
+     */
1286
+    function getPathOfDump()
1287
+    {
1288
+        $fullpathofdump='/pathtopgdump/pg_dump';
1289
+
1290
+        if (file_exists('/usr/bin/pg_dump'))
1291
+        {
1292
+            $fullpathofdump='/usr/bin/pg_dump';
1293
+        }
1294
+        else
1295
+        {
1296 1296
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1297
-		    $resql=$this->query('SHOW data_directory');
1298
-    		if ($resql)
1299
-    		{
1300
-    			$liste=$this->fetch_array($resql);
1301
-    			$basedir=$liste['data_directory'];
1302
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1303
-    		}
1304
-		}
1305
-
1306
-		return $fullpathofdump;
1307
-	}
1297
+            $resql=$this->query('SHOW data_directory');
1298
+            if ($resql)
1299
+            {
1300
+                $liste=$this->fetch_array($resql);
1301
+                $basedir=$liste['data_directory'];
1302
+                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1303
+            }
1304
+        }
1305
+
1306
+        return $fullpathofdump;
1307
+    }
1308 1308
 
1309 1309
     /**
1310 1310
      *	Return full path of restore program
1311 1311
      *
1312 1312
      *	@return		string		Full path of restore program
1313 1313
      */
1314
-	function getPathOfRestore()
1315
-	{
1316
-		//$tool='pg_restore';
1317
-		$tool='psql';
1314
+    function getPathOfRestore()
1315
+    {
1316
+        //$tool='pg_restore';
1317
+        $tool='psql';
1318 1318
 
1319
-		$fullpathofdump='/pathtopgrestore/'.$tool;
1319
+        $fullpathofdump='/pathtopgrestore/'.$tool;
1320 1320
 
1321 1321
         if (file_exists('/usr/bin/'.$tool))
1322 1322
         {
@@ -1334,39 +1334,39 @@  discard block
 block discarded – undo
1334 1334
             }
1335 1335
         }
1336 1336
 
1337
-		return $fullpathofdump;
1338
-	}
1339
-
1340
-	/**
1341
-	 * Return value of server parameters
1342
-	 *
1343
-	 * @param	string	$filter		Filter list on a particular value
1344
-	 * @return	array				Array of key-values (key=>value)
1345
-	 */
1346
-	function getServerParametersValues($filter='')
1347
-	{
1348
-		$result=array();
1349
-
1350
-		$resql='select name,setting from pg_settings';
1351
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1352
-		$resql=$this->query($resql);
1353
-		if ($resql)
1354
-		{
1355
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1356
-		}
1357
-
1358
-		return $result;
1359
-	}
1360
-
1361
-	/**
1362
-	 * Return value of server status
1363
-	 *
1364
-	 * @param	string	$filter		Filter list on a particular value
1365
-	 * @return  array				Array of key-values (key=>value)
1366
-	 */
1367
-	function getServerStatusValues($filter='')
1368
-	{
1369
-		/* This is to return current running requests.
1337
+        return $fullpathofdump;
1338
+    }
1339
+
1340
+    /**
1341
+     * Return value of server parameters
1342
+     *
1343
+     * @param	string	$filter		Filter list on a particular value
1344
+     * @return	array				Array of key-values (key=>value)
1345
+     */
1346
+    function getServerParametersValues($filter='')
1347
+    {
1348
+        $result=array();
1349
+
1350
+        $resql='select name,setting from pg_settings';
1351
+        if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1352
+        $resql=$this->query($resql);
1353
+        if ($resql)
1354
+        {
1355
+            while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1356
+        }
1357
+
1358
+        return $result;
1359
+    }
1360
+
1361
+    /**
1362
+     * Return value of server status
1363
+     *
1364
+     * @param	string	$filter		Filter list on a particular value
1365
+     * @return  array				Array of key-values (key=>value)
1366
+     */
1367
+    function getServerStatusValues($filter='')
1368
+    {
1369
+        /* This is to return current running requests.
1370 1370
 		$sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
1371 1371
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1372 1372
         $resql=$this->query($sql);
@@ -1377,6 +1377,6 @@  discard block
 block discarded – undo
1377 1377
         }
1378 1378
 		*/
1379 1379
 
1380
-		return array();
1381
-	}
1380
+        return array();
1381
+    }
1382 1382
 }
Please login to merge, or discard this patch.
Braces   +155 added lines, -91 removed lines patch added patch discarded remove patch
@@ -67,8 +67,12 @@  discard block
 block discarded – undo
67 67
 		global $conf,$langs;
68 68
 
69 69
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
70
-		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
71
-		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
70
+		if (! empty($conf->db->character_set)) {
71
+		    $this->forcecharset=$conf->db->character_set;
72
+		}
73
+		if (! empty($conf->db->dolibarr_main_db_collation)) {
74
+		    $this->forcecollate=$conf->db->dolibarr_main_db_collation;
75
+		}
72 76
 
73 77
 		$this->database_user=$user;
74 78
         $this->database_host=$host;
@@ -104,8 +108,7 @@  discard block
 block discarded – undo
104 108
 		{
105 109
 			$this->connected = true;
106 110
 			$this->ok = true;
107
-		}
108
-		else
111
+		} else
109 112
 		{
110 113
 			// host, login ou password incorrect
111 114
 			$this->connected = false;
@@ -122,8 +125,7 @@  discard block
 block discarded – undo
122 125
 				$this->database_selected = true;
123 126
 				$this->database_name = $name;
124 127
 				$this->ok = true;
125
-			}
126
-			else
128
+			} else
127 129
 			{
128 130
 				$this->database_selected = false;
129 131
 				$this->database_name = '';
@@ -131,8 +133,7 @@  discard block
 block discarded – undo
131 133
 				$this->error=$this->error();
132 134
 				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
133 135
 			}
134
-		}
135
-		else
136
+		} else
136 137
 		{
137 138
 			// Pas de selection de base demandee, ok ou ko
138 139
 			$this->database_selected = false;
@@ -172,9 +173,13 @@  discard block
 block discarded – undo
172 173
 
173 174
 		    if ($type == 'auto')
174 175
 		    {
175
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
176
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
177
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
176
+              if (preg_match('/ALTER TABLE/i',$line)) {
177
+                  $type='dml';
178
+              } else if (preg_match('/CREATE TABLE/i',$line)) {
179
+                  $type='dml';
180
+              } else if (preg_match('/DROP TABLE/i',$line)) {
181
+                  $type='dml';
182
+              }
178 183
 		    }
179 184
 
180 185
     		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
@@ -321,10 +326,12 @@  discard block
 block discarded – undo
321 326
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
322 327
 			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
323 328
 			{
324
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
329
+				if ($reg[1] == $reg[2]) {
330
+				    // If same table, we remove second one
325 331
 				{
326 332
 					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
327 333
 				}
334
+				}
328 335
 			}
329 336
 
330 337
 			// Remove () in the tables in FROM if 1 table
@@ -351,7 +358,9 @@  discard block
 block discarded – undo
351 358
 			// By default we do not (should be already done by db->escape function if required
352 359
 			// except for sql insert in data file that are mysql escaped so we removed them to
353 360
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
354
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
361
+			if ($unescapeslashquot) {
362
+			    $line=preg_replace("/\\\'/","''",$line);
363
+			}
355 364
 
356 365
 			//print "type=".$type." newline=".$line."<br>\n";
357 366
 		}
@@ -402,7 +411,10 @@  discard block
 block discarded – undo
402 411
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
403 412
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
404 413
 
405
-		if (! $name) $name="postgres";    // When try to connect using admin user
414
+		if (! $name) {
415
+		    $name="postgres";
416
+		}
417
+		// When try to connect using admin user
406 418
 
407 419
 		// try first Unix domain socket (local)
408 420
 		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
@@ -414,8 +426,12 @@  discard block
 block discarded – undo
414 426
 		// if local connection failed or not requested, use TCP/IP
415 427
 		if (! $this->db)
416 428
 		{
417
-		    if (! $host) $host = "localhost";
418
-			if (! $port) $port = 5432;
429
+		    if (! $host) {
430
+		        $host = "localhost";
431
+		    }
432
+			if (! $port) {
433
+			    $port = 5432;
434
+			}
419 435
 
420 436
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
421 437
 			$this->db = @pg_connect($con_string);
@@ -468,7 +484,9 @@  discard block
 block discarded – undo
468 484
     {
469 485
         if ($this->db)
470 486
         {
471
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
487
+          if ($this->transaction_opened > 0) {
488
+              dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
489
+          }
472 490
           $this->connected=false;
473 491
           return pg_close($this->db);
474 492
         }
@@ -503,8 +521,9 @@  discard block
 block discarded – undo
503 521
 				{
504 522
 					$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);
505 523
 					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
524
+				} else {
525
+				    $loop=false;
506 526
 				}
507
-				else $loop=false;
508 527
 			}
509 528
 		}
510 529
 
@@ -513,30 +532,39 @@  discard block
 block discarded – undo
513 532
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
514 533
 		}
515 534
 
516
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
535
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
536
+		    dol_syslog('sql='.$query, LOG_DEBUG);
537
+		}
517 538
 
518 539
 		$ret = @pg_query($this->db, $query);
519 540
 
520 541
 		//print $query;
521
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
542
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) {
543
+		    // Si requete utilisateur, on la sauvegarde ainsi que son resultset
522 544
 		{
523 545
 			if (! $ret)
524 546
 			{
525 547
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
526 548
 			    {
527 549
     				$this->lastqueryerror = $query;
550
+		}
528 551
     				$this->lasterror = $this->error();
529 552
     				$this->lasterrno = $this->errno();
530 553
 
531
-    				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
554
+    				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
555
+    				    dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
556
+    				}
557
+    				// Log of request was not yet done previously
532 558
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
533 559
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
534 560
 			    }
535 561
 
536
-				if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
562
+				if ($usesavepoint && $this->transaction_opened) {
563
+				    // Warning, after that errno will be erased
537 564
 				{
538 565
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
539 566
 				}
567
+				}
540 568
 			}
541 569
 			$this->lastquery=$query;
542 570
 			$this->_results = $ret;
@@ -636,7 +664,9 @@  discard block
 block discarded – undo
636 664
         // If resultset not provided, we take the last used by connexion
637 665
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
638 666
 		// Si resultset en est un, on libere la memoire
639
-		if (is_resource($resultset)) pg_free_result($resultset);
667
+		if (is_resource($resultset)) {
668
+		    pg_free_result($resultset);
669
+		}
640 670
 	}
641 671
 
642 672
 
@@ -650,10 +680,17 @@  discard block
 block discarded – undo
650 680
 	function plimit($limit=0,$offset=0)
651 681
 	{
652 682
 		global $conf;
653
-        if (empty($limit)) return "";
654
-		if ($limit < 0) $limit=$conf->liste_limit;
655
-		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
656
-		else return " LIMIT $limit ";
683
+        if (empty($limit)) {
684
+            return "";
685
+        }
686
+		if ($limit < 0) {
687
+		    $limit=$conf->liste_limit;
688
+		}
689
+		if ($offset > 0) {
690
+		    return " LIMIT ".$limit." OFFSET ".$offset." ";
691
+		} else {
692
+		    return " LIMIT $limit ";
693
+		}
657 694
 	}
658 695
 
659 696
 
@@ -703,8 +740,7 @@  discard block
 block discarded – undo
703 740
 		if (! $this->connected) {
704 741
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
705 742
 			return 'DB_ERROR_FAILED_TO_CONNECT';
706
-		}
707
-		else {
743
+		} else {
708 744
 			// Constants to convert error code to a generic Dolibarr error code
709 745
 			$errorcode_map = array(
710 746
 			1004 => 'DB_ERROR_CANNOT_CREATE',
@@ -865,8 +901,12 @@  discard block
 block discarded – undo
865 901
 	function DDLCreateDb($database,$charset='',$collation='',$owner='')
866 902
 	{
867 903
         // phpcs:enable
868
-	    if (empty($charset))   $charset=$this->forcecharset;
869
-		if (empty($collation)) $collation=$this->forcecollate;
904
+	    if (empty($charset)) {
905
+	        $charset=$this->forcecharset;
906
+	    }
907
+		if (empty($collation)) {
908
+		    $collation=$this->forcecollate;
909
+		}
870 910
 
871 911
 		// Test charset match LC_TYPE (pgsql error otherwise)
872 912
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
@@ -891,7 +931,9 @@  discard block
 block discarded – undo
891 931
 		$listtables=array();
892 932
 
893 933
 		$like = '';
894
-		if ($table) $like = " AND table_name LIKE '".$table."'";
934
+		if ($table) {
935
+		    $like = " AND table_name LIKE '".$table."'";
936
+		}
895 937
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
896 938
         if ($result)
897 939
         {
@@ -971,26 +1013,27 @@  discard block
 block discarded – undo
971 1013
 		{
972 1014
 			$sqlfields[$i] = $field_name." ";
973 1015
 			$sqlfields[$i]  .= $field_desc['type'];
974
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
975
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
976
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
977
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
978
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
1016
+			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
1017
+						$sqlfields[$i]  .= "(".$field_desc['value'].")";
1018
+			} else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1019
+						$sqlfields[$i]  .= " ".$field_desc['attribute'];
1020
+			} else if( preg_match("/^[^\s]/i",$field_desc['default']))
979 1021
 			{
980
-				if(preg_match("/null/i",$field_desc['default']))
981
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
982
-				else
983
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
1022
+				if(preg_match("/null/i",$field_desc['default'])) {
1023
+								$sqlfields[$i]  .= " default ".$field_desc['default'];
1024
+				} else {
1025
+								$sqlfields[$i]  .= " default '".$field_desc['default']."'";
1026
+				}
1027
+			} else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
1028
+						$sqlfields[$i]  .= " ".$field_desc['null'];
1029
+			} else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
1030
+						$sqlfields[$i]  .= " ".$field_desc['extra'];
984 1031
 			}
985
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
986
-			$sqlfields[$i]  .= " ".$field_desc['null'];
987
-
988
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
989
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
990 1032
 			$i++;
991 1033
 		}
992
-		if($primary_key != "")
993
-		$pk = "primary key(".$primary_key.")";
1034
+		if($primary_key != "") {
1035
+				$pk = "primary key(".$primary_key.")";
1036
+		}
994 1037
 
995 1038
 		if(is_array($unique_keys))
996 1039
 		{
@@ -1011,19 +1054,23 @@  discard block
 block discarded – undo
1011 1054
 			}
1012 1055
 		}
1013 1056
 		$sql .= implode(',',$sqlfields);
1014
-		if($primary_key != "")
1015
-		$sql .= ",".$pk;
1016
-		if(is_array($unique_keys))
1017
-		$sql .= ",".implode(',',$sqluq);
1018
-		if(is_array($keys))
1019
-		$sql .= ",".implode(',',$sqlk);
1057
+		if($primary_key != "") {
1058
+				$sql .= ",".$pk;
1059
+		}
1060
+		if(is_array($unique_keys)) {
1061
+				$sql .= ",".implode(',',$sqluq);
1062
+		}
1063
+		if(is_array($keys)) {
1064
+				$sql .= ",".implode(',',$sqlk);
1065
+		}
1020 1066
 		$sql .=") type=".$type;
1021 1067
 
1022 1068
 		dol_syslog($sql,LOG_DEBUG);
1023
-		if(! $this->query($sql))
1024
-		return -1;
1025
-		else
1026
-		return 1;
1069
+		if(! $this->query($sql)) {
1070
+				return -1;
1071
+		} else {
1072
+				return 1;
1073
+		}
1027 1074
 	}
1028 1075
 
1029 1076
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1038,10 +1085,11 @@  discard block
 block discarded – undo
1038 1085
         // phpcs:enable
1039 1086
 		$sql = "DROP TABLE ".$table;
1040 1087
 
1041
-		if (! $this->query($sql))
1042
-			return -1;
1043
-		else
1044
-			return 1;
1088
+		if (! $this->query($sql)) {
1089
+					return -1;
1090
+		} else {
1091
+					return 1;
1092
+		}
1045 1093
 	}
1046 1094
 
1047 1095
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1083,7 +1131,9 @@  discard block
 block discarded – undo
1083 1131
         // phpcs:enable
1084 1132
 		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1085 1133
 		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1086
-		if ($field) $sql.= " AND attname = '".$field."'";
1134
+		if ($field) {
1135
+		    $sql.= " AND attname = '".$field."'";
1136
+		}
1087 1137
 
1088 1138
 		dol_syslog($sql,LOG_DEBUG);
1089 1139
 		$this->_results = $this->query($sql);
@@ -1107,27 +1157,33 @@  discard block
 block discarded – undo
1107 1157
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1108 1158
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1109 1159
 		$sql .= $field_desc['type'];
1110
-		if (preg_match("/^[^\s]/i",$field_desc['value']))
1111
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1160
+		if (preg_match("/^[^\s]/i",$field_desc['value'])) {
1161
+				    if (! in_array($field_desc['type'],array('int','date','datetime')))
1112 1162
 		    {
1113 1163
 		        $sql.= "(".$field_desc['value'].")";
1164
+		}
1114 1165
 		    }
1115
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1116
-            $sql .= " ".$field_desc['attribute'];
1117
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1118
-            $sql .= " ".$field_desc['null'];
1119
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1120
-            if (preg_match("/null/i",$field_desc['default']))
1166
+		if (preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1167
+		            $sql .= " ".$field_desc['attribute'];
1168
+		}
1169
+		if (preg_match("/^[^\s]/i",$field_desc['null'])) {
1170
+		            $sql .= " ".$field_desc['null'];
1171
+		}
1172
+		if (preg_match("/^[^\s]/i",$field_desc['default'])) {
1173
+		            if (preg_match("/null/i",$field_desc['default']))
1121 1174
                 $sql .= " default ".$field_desc['default'];
1122
-		    else
1123
-                $sql .= " default '".$field_desc['default']."'";
1124
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1125
-            $sql .= " ".$field_desc['extra'];
1175
+		} else {
1176
+		                    $sql .= " default '".$field_desc['default']."'";
1177
+		    }
1178
+		if (preg_match("/^[^\s]/i",$field_desc['extra'])) {
1179
+		            $sql .= " ".$field_desc['extra'];
1180
+		}
1126 1181
 		$sql .= " ".$field_position;
1127 1182
 
1128 1183
 		dol_syslog($sql,LOG_DEBUG);
1129
-		if (! $this -> query($sql))
1130
-			return -1;
1184
+		if (! $this -> query($sql)) {
1185
+					return -1;
1186
+		}
1131 1187
 		return 1;
1132 1188
 	}
1133 1189
 
@@ -1156,8 +1212,7 @@  discard block
 block discarded – undo
1156 1212
         	{
1157 1213
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1158 1214
         		$this->query($sqlbis);
1159
-        	}
1160
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1215
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1161 1216
         	{
1162 1217
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1163 1218
         		$this->query($sqlbis);
@@ -1166,13 +1221,18 @@  discard block
 block discarded – undo
1166 1221
 
1167 1222
 		if ($field_desc['default'] != '')
1168 1223
 		{
1169
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1170
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1224
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
1225
+			    $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1226
+			} elseif ($field_desc['type'] == 'text') {
1227
+        	    $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
1228
+        	}
1229
+        	// Default not supported on text fields
1171 1230
 		}
1172 1231
 
1173 1232
 		dol_syslog($sql,LOG_DEBUG);
1174
-		if (! $this->query($sql))
1175
-			return -1;
1233
+		if (! $this->query($sql)) {
1234
+					return -1;
1235
+		}
1176 1236
 		return 1;
1177 1237
 	}
1178 1238
 
@@ -1209,8 +1269,9 @@  discard block
 block discarded – undo
1209 1269
 		{
1210 1270
             $liste=$this->fetch_array($resql);
1211 1271
 		    return $liste['server_encoding'];
1272
+		} else {
1273
+		    return '';
1212 1274
 		}
1213
-		else return '';
1214 1275
 	}
1215 1276
 
1216 1277
 	/**
@@ -1250,8 +1311,9 @@  discard block
 block discarded – undo
1250 1311
 		{
1251 1312
 		    $liste=$this->fetch_array($resql);
1252 1313
 			return $liste['lc_collate'];
1314
+		} else {
1315
+		    return '';
1253 1316
 		}
1254
-		else return '';
1255 1317
 	}
1256 1318
 
1257 1319
 	/**
@@ -1290,8 +1352,7 @@  discard block
 block discarded – undo
1290 1352
 		if (file_exists('/usr/bin/pg_dump'))
1291 1353
 		{
1292 1354
 		    $fullpathofdump='/usr/bin/pg_dump';
1293
-		}
1294
-		else
1355
+		} else
1295 1356
 		{
1296 1357
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1297 1358
 		    $resql=$this->query('SHOW data_directory');
@@ -1321,8 +1382,7 @@  discard block
 block discarded – undo
1321 1382
         if (file_exists('/usr/bin/'.$tool))
1322 1383
         {
1323 1384
             $fullpathofdump='/usr/bin/'.$tool;
1324
-        }
1325
-        else
1385
+        } else
1326 1386
         {
1327 1387
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1328 1388
             $resql=$this->query('SHOW data_directory');
@@ -1348,11 +1408,15 @@  discard block
 block discarded – undo
1348 1408
 		$result=array();
1349 1409
 
1350 1410
 		$resql='select name,setting from pg_settings';
1351
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1411
+		if ($filter) {
1412
+		    $resql.=" WHERE name = '".$this->escape($filter)."'";
1413
+		}
1352 1414
 		$resql=$this->query($resql);
1353 1415
 		if ($resql)
1354 1416
 		{
1355
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1417
+			while ($obj=$this->fetch_object($resql)) {
1418
+			    $result[$obj->name]=$obj->setting;
1419
+			}
1356 1420
 		}
1357 1421
 
1358 1422
 		return $result;
Please login to merge, or discard this patch.
Spacing   +263 added lines, -263 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
  *	\brief      Fichier de la classe permettant de gerer une base pgsql
34 34
  */
35 35
 
36
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
36
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
37 37
 
38 38
 /**
39 39
  *	Class to drive a Postgresql database for Dolibarr
@@ -41,15 +41,15 @@  discard block
 block discarded – undo
41 41
 class DoliDBPgsql extends DoliDB
42 42
 {
43 43
     //! Database type
44
-	public $type='pgsql';            // Name of manager
44
+	public $type = 'pgsql'; // Name of manager
45 45
     //! Database label
46
-	const LABEL='PostgreSQL';      // Label of manager
46
+	const LABEL = 'PostgreSQL'; // Label of manager
47 47
 	//! Charset
48
-	var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
48
+	var $forcecharset = 'UTF8'; // Can't be static as it may be forced with a dynamic value
49 49
     //! Collate used to force collate when creating database
50
-    var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
50
+    var $forcecollate = ''; // Can't be static as it may be forced with a dynamic value
51 51
 	//! Version min database
52
-	const VERSIONMIN='9.0.0';	// Version min database
52
+	const VERSIONMIN = '9.0.0'; // Version min database
53 53
 	/** @var resource Resultset of last query */
54 54
 	private $_results;
55 55
 
@@ -67,37 +67,37 @@  discard block
 block discarded – undo
67 67
 	 *	@param	    string	$name		Nom de la database
68 68
 	 *	@param	    int		$port		Port of database server
69 69
 	 */
70
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
70
+	function __construct($type, $host, $user, $pass, $name = '', $port = 0)
71 71
 	{
72
-		global $conf,$langs;
72
+		global $conf, $langs;
73 73
 
74 74
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
75
-		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
76
-		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
75
+		if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
76
+		if (!empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate = $conf->db->dolibarr_main_db_collation;
77 77
 
78
-		$this->database_user=$user;
79
-        $this->database_host=$host;
80
-        $this->database_port=$port;
78
+		$this->database_user = $user;
79
+        $this->database_host = $host;
80
+        $this->database_port = $port;
81 81
 
82
-		$this->transaction_opened=0;
82
+		$this->transaction_opened = 0;
83 83
 
84 84
 		//print "Name DB: $host,$user,$pass,$name<br>";
85 85
 
86
-		if (! function_exists("pg_connect"))
86
+		if (!function_exists("pg_connect"))
87 87
 		{
88 88
 			$this->connected = false;
89 89
 			$this->ok = false;
90
-			$this->error="Pgsql PHP functions are not available in this version of PHP";
91
-			dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP",LOG_ERR);
90
+			$this->error = "Pgsql PHP functions are not available in this version of PHP";
91
+			dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
92 92
 			return $this->ok;
93 93
 		}
94 94
 
95
-		if (! $host)
95
+		if (!$host)
96 96
 		{
97 97
 			$this->connected = false;
98 98
 			$this->ok = false;
99
-			$this->error=$langs->trans("ErrorWrongHostParameter");
100
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters",LOG_ERR);
99
+			$this->error = $langs->trans("ErrorWrongHostParameter");
100
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
101 101
 			return $this->ok;
102 102
 		}
103 103
 
@@ -115,8 +115,8 @@  discard block
 block discarded – undo
115 115
 			// host, login ou password incorrect
116 116
 			$this->connected = false;
117 117
 			$this->ok = false;
118
-			$this->error='Host, login or password incorrect';
119
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error,LOG_ERR);
118
+			$this->error = 'Host, login or password incorrect';
119
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error, LOG_ERR);
120 120
 		}
121 121
 
122 122
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -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)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
136
+				$this->error = $this->error();
137
+				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error, LOG_ERR);
138 138
 			}
139 139
 		}
140 140
 		else
@@ -155,14 +155,14 @@  discard block
 block discarded – undo
155 155
      *  @param	bool	$unescapeslashquot	Unescape slash quote with quote quote
156 156
      *  @return string   					SQL request line converted
157 157
      */
158
-	static function convertSQLFromMysql($line,$type='auto',$unescapeslashquot=false)
158
+	static function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
159 159
 	{
160 160
 		// Removed empty line if this is a comment line for SVN tagging
161
-		if (preg_match('/^--\s\$Id/i',$line)) {
161
+		if (preg_match('/^--\s\$Id/i', $line)) {
162 162
 			return '';
163 163
 		}
164 164
 		// Return line if this is a comment
165
-		if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
165
+		if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
166 166
 		{
167 167
 			return $line;
168 168
 		}
@@ -177,186 +177,186 @@  discard block
 block discarded – undo
177 177
 
178 178
 		    if ($type == 'auto')
179 179
 		    {
180
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
181
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
182
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
180
+              if (preg_match('/ALTER TABLE/i', $line)) $type = 'dml';
181
+              else if (preg_match('/CREATE TABLE/i', $line)) $type = 'dml';
182
+              else if (preg_match('/DROP TABLE/i', $line)) $type = 'dml';
183 183
 		    }
184 184
 
185
-    		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
185
+    		$line = preg_replace('/ as signed\)/i', ' as integer)', $line);
186 186
 
187 187
 		    if ($type == 'dml')
188 188
 		    {
189
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
189
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
190 190
 
191 191
 		        // we are inside create table statement so lets process datatypes
192
-    			if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
193
-    				$line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
194
-    				$line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',');',$line);
195
-    				$line=preg_replace('/,$/','',$line);
192
+    			if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
193
+    				$line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
194
+    				$line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
195
+    				$line = preg_replace('/,$/', '', $line);
196 196
     			}
197 197
 
198 198
     			// Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
199
-    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
200
-    				$newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
199
+    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
200
+    				$newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
201 201
                     //$line = "-- ".$line." replaced by --\n".$newline;
202
-                    $line=$newline;
202
+                    $line = $newline;
203 203
     			}
204 204
 
205 205
     			// tinyint type conversion
206
-    			$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
207
-    			$line=preg_replace('/tinyint/i','smallint',$line);
206
+    			$line = preg_replace('/tinyint\(?[0-9]*\)?/', 'smallint', $line);
207
+    			$line = preg_replace('/tinyint/i', 'smallint', $line);
208 208
 
209 209
     			// nuke unsigned
210
-    			$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
210
+    			$line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
211 211
 
212 212
     			// blob -> text
213
-    			$line=preg_replace('/\w*blob/i','text',$line);
213
+    			$line = preg_replace('/\w*blob/i', 'text', $line);
214 214
 
215 215
     			// tinytext/mediumtext -> text
216
-    			$line=preg_replace('/tinytext/i','text',$line);
217
-    			$line=preg_replace('/mediumtext/i','text',$line);
218
-    			$line=preg_replace('/longtext/i','text',$line);
216
+    			$line = preg_replace('/tinytext/i', 'text', $line);
217
+    			$line = preg_replace('/mediumtext/i', 'text', $line);
218
+    			$line = preg_replace('/longtext/i', 'text', $line);
219 219
 
220
-    			$line=preg_replace('/text\([0-9]+\)/i','text',$line);
220
+    			$line = preg_replace('/text\([0-9]+\)/i', 'text', $line);
221 221
 
222 222
     			// change not null datetime field to null valid ones
223 223
     			// (to support remapping of "zero time" to null
224
-    			$line=preg_replace('/datetime not null/i','datetime',$line);
225
-    			$line=preg_replace('/datetime/i','timestamp',$line);
224
+    			$line = preg_replace('/datetime not null/i', 'datetime', $line);
225
+    			$line = preg_replace('/datetime/i', 'timestamp', $line);
226 226
 
227 227
     			// double -> numeric
228
-    			$line=preg_replace('/^double/i','numeric',$line);
229
-    			$line=preg_replace('/(\s*)double/i','\\1numeric',$line);
228
+    			$line = preg_replace('/^double/i', 'numeric', $line);
229
+    			$line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
230 230
     			// float -> numeric
231
-    			$line=preg_replace('/^float/i','numeric',$line);
232
-    			$line=preg_replace('/(\s*)float/i','\\1numeric',$line);
231
+    			$line = preg_replace('/^float/i', 'numeric', $line);
232
+    			$line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
233 233
 
234 234
     			//Check tms timestamp field case (in Mysql this field is defautled to now and
235 235
     			// on update defaulted by now
236
-    			$line=preg_replace('/(\s*)tms(\s*)timestamp/i','\\1tms timestamp without time zone DEFAULT now() NOT NULL',$line);
236
+    			$line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
237 237
 
238 238
     			// nuke ON UPDATE CURRENT_TIMESTAMP
239
-    			$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
239
+    			$line = preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
240 240
 
241 241
     			// unique index(field1,field2)
242
-    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
242
+    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
243 243
     			{
244
-    				$line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
244
+    				$line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
245 245
     			}
246 246
 
247 247
     			// We remove end of requests "AFTER fieldxxx"
248
-    			$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
248
+    			$line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
249 249
 
250 250
     			// We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
251
-    			$line=preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i','DROP INDEX',$line);
251
+    			$line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
252 252
 
253 253
                 // Translate order to rename fields
254
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
254
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
255 255
                 {
256 256
                 	$line = "-- ".$line." replaced by --\n";
257
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
257
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
258 258
                 }
259 259
 
260 260
                 // Translate order to modify field format
261
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
261
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
262 262
                 {
263 263
                     $line = "-- ".$line." replaced by --\n";
264
-                    $newreg3=$reg[3];
265
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
266
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
267
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
268
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
269
-                    $newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
270
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
264
+                    $newreg3 = $reg[3];
265
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
266
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
267
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
268
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
269
+                    $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
270
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
271 271
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
272 272
                 }
273 273
 
274 274
                 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
275 275
     			// ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
276
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
276
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
277 277
     			{
278 278
     				$line = "-- ".$line." replaced by --\n";
279
-    				$line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
279
+    				$line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
280 280
     			}
281 281
 
282 282
                 // Translate order to drop primary keys
283 283
                 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
284
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg))
284
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg))
285 285
                 {
286 286
                     $line = "-- ".$line." replaced by --\n";
287
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
287
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
288 288
                 }
289 289
 
290 290
 		        // Translate order to drop foreign keys
291 291
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
292
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
292
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
293 293
                 {
294 294
                     $line = "-- ".$line." replaced by --\n";
295
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
295
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
296 296
                 }
297 297
 
298 298
                 // Translate order to add foreign keys
299 299
                 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
300
-                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
300
+                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
301 301
                 {
302
-                    $line=preg_replace('/;$/','',$line);
303
-                    $line.=" DEFERRABLE INITIALLY IMMEDIATE;";
302
+                    $line = preg_replace('/;$/', '', $line);
303
+                    $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
304 304
                 }
305 305
 
306 306
                 // alter table add [unique] [index] (field1, field2 ...)
307 307
     			// ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
308
-    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
308
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
309 309
     			{
310
-    				$fieldlist=$reg[4];
311
-    				$idxname=$reg[3];
312
-    				$tablename=$reg[1];
310
+    				$fieldlist = $reg[4];
311
+    				$idxname = $reg[3];
312
+    				$tablename = $reg[1];
313 313
     				$line = "-- ".$line." replaced by --\n";
314
-    				$line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
314
+    				$line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
315 315
     			}
316 316
             }
317 317
 
318 318
             // To have postgresql case sensitive
319
-            $line=str_replace(' LIKE \'',' ILIKE \'',$line);
320
-            $line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
319
+            $line = str_replace(' LIKE \'', ' ILIKE \'', $line);
320
+            $line = str_replace(' LIKE BINARY \'', ' LIKE \'', $line);
321 321
 
322 322
             // Replace INSERT IGNORE into INSERT
323
-            $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
323
+            $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
324 324
 
325 325
 			// Delete using criteria on other table must not declare twice the deleted table
326 326
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
327
-			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
327
+			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
328 328
 			{
329 329
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
330 330
 				{
331
-					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
331
+					$line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
332 332
 				}
333 333
 			}
334 334
 
335 335
 			// Remove () in the tables in FROM if 1 table
336
-			$line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
336
+			$line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
337 337
 			//print $line."\n";
338 338
 
339 339
 			// Remove () in the tables in FROM if 2 table
340
-			$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);
340
+			$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);
341 341
 			//print $line."\n";
342 342
 
343 343
 			// Remove () in the tables in FROM if 3 table
344
-			$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);
344
+			$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);
345 345
 			//print $line."\n";
346 346
 
347 347
 			// Remove () in the tables in FROM if 4 table
348
-			$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);
348
+			$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);
349 349
 			//print $line."\n";
350 350
 
351 351
 			// Remove () in the tables in FROM if 5 table
352
-			$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);
352
+			$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);
353 353
 			//print $line."\n";
354 354
 
355 355
 			// Replace espacing \' by ''.
356 356
 			// By default we do not (should be already done by db->escape function if required
357 357
 			// except for sql insert in data file that are mysql escaped so we removed them to
358 358
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
359
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
359
+			if ($unescapeslashquot) $line = preg_replace("/\\\'/", "''", $line);
360 360
 
361 361
 			//print "type=".$type." newline=".$line."<br>\n";
362 362
 		}
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 	 *	@return		false|resource			Database access handler
395 395
 	 *	@see		close
396 396
 	 */
397
-	function connect($host, $login, $passwd, $name, $port=0)
397
+	function connect($host, $login, $passwd, $name, $port = 0)
398 398
 	{
399 399
 		// use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
400 400
 
@@ -407,20 +407,20 @@  discard block
 block discarded – undo
407 407
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
408 408
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
409 409
 
410
-		if (! $name) $name="postgres";    // When try to connect using admin user
410
+		if (!$name) $name = "postgres"; // When try to connect using admin user
411 411
 
412 412
 		// try first Unix domain socket (local)
413
-		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
413
+		if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT'))
414 414
 		{
415
-			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'";    // $name may be empty
415
+			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
416 416
 			$this->db = @pg_connect($con_string);
417 417
 		}
418 418
 
419 419
 		// if local connection failed or not requested, use TCP/IP
420
-		if (! $this->db)
420
+		if (!$this->db)
421 421
 		{
422
-		    if (! $host) $host = "localhost";
423
-			if (! $port) $port = 5432;
422
+		    if (!$host) $host = "localhost";
423
+			if (!$port) $port = 5432;
424 424
 
425 425
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
426 426
 			$this->db = @pg_connect($con_string);
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 		if ($this->db)
431 431
 		{
432 432
 			$this->database_name = $name;
433
-			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);	// Set verbosity to max
433
+			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
434 434
 			pg_query($this->db, "set datestyle = 'ISO, YMD';");
435 435
 		}
436 436
 
@@ -444,10 +444,10 @@  discard block
 block discarded – undo
444 444
 	 */
445 445
 	function getVersion()
446 446
 	{
447
-		$resql=$this->query('SHOW server_version');
447
+		$resql = $this->query('SHOW server_version');
448 448
 		if ($resql)
449 449
 		{
450
-		  $liste=$this->fetch_array($resql);
450
+		  $liste = $this->fetch_array($resql);
451 451
 		  return $liste['server_version'];
452 452
 		}
453 453
 		return '';
@@ -473,8 +473,8 @@  discard block
 block discarded – undo
473 473
     {
474 474
         if ($this->db)
475 475
         {
476
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
477
-          $this->connected=false;
476
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
477
+          $this->connected = false;
478 478
           return pg_close($this->db);
479 479
         }
480 480
         return false;
@@ -488,28 +488,28 @@  discard block
 block discarded – undo
488 488
      * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
489 489
 	 * @return	false|resource			Resultset of answer
490 490
 	 */
491
-	function query($query,$usesavepoint=0,$type='auto')
491
+	function query($query, $usesavepoint = 0, $type = 'auto')
492 492
 	{
493 493
 		global $conf;
494 494
 
495 495
 		$query = trim($query);
496 496
 
497 497
 		// Convert MySQL syntax to PostgresSQL syntax
498
-		$query=$this->convertSQLFromMysql($query,$type,($this->unescapeslashquot && $this->standard_conforming_strings));
498
+		$query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
499 499
 		//print "After convertSQLFromMysql:\n".$query."<br>\n";
500 500
 
501
-		if (! empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
501
+		if (!empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
502 502
 		{
503 503
 			// Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
504
-			$loop=true;
504
+			$loop = true;
505 505
 			while ($loop)
506 506
 			{
507
-				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))
507
+				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))
508 508
 				{
509
-					$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);
510
-					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
509
+					$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);
510
+					dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
511 511
 				}
512
-				else $loop=false;
512
+				else $loop = false;
513 513
 			}
514 514
 		}
515 515
 
@@ -518,14 +518,14 @@  discard block
 block discarded – undo
518 518
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
519 519
 		}
520 520
 
521
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
521
+		if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
522 522
 
523 523
 		$ret = @pg_query($this->db, $query);
524 524
 
525 525
 		//print $query;
526
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
526
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
527 527
 		{
528
-			if (! $ret)
528
+			if (!$ret)
529 529
 			{
530 530
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
531 531
 			    {
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
     				$this->lasterror = $this->error();
534 534
     				$this->lasterrno = $this->errno();
535 535
 
536
-    				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
536
+    				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
537 537
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
538 538
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
539 539
 			    }
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
544 544
 				}
545 545
 			}
546
-			$this->lastquery=$query;
546
+			$this->lastquery = $query;
547 547
 			$this->_results = $ret;
548 548
 		}
549 549
 
@@ -561,7 +561,7 @@  discard block
 block discarded – undo
561 561
 	{
562 562
         // phpcs:enable
563 563
         // If resultset not provided, we take the last used by connexion
564
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
564
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
565 565
 		return pg_fetch_object($resultset);
566 566
 	}
567 567
 
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 	{
577 577
         // phpcs:enable
578 578
         // If resultset not provided, we take the last used by connexion
579
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
579
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
580 580
 		return pg_fetch_array($resultset);
581 581
 	}
582 582
 
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
 	{
592 592
         // phpcs:enable
593 593
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
594
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
594
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
595 595
 		return pg_fetch_row($resultset);
596 596
 	}
597 597
 
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 	{
608 608
         // phpcs:enable
609 609
         // If resultset not provided, we take the last used by connexion
610
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
610
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
611 611
 		return pg_num_rows($resultset);
612 612
 	}
613 613
 
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 	{
624 624
         // phpcs:enable
625 625
         // If resultset not provided, we take the last used by connexion
626
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
626
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
627 627
 		// pgsql necessite un resultset pour cette fonction contrairement
628 628
 		// a mysql qui prend un link de base
629 629
 		return pg_affected_rows($resultset);
@@ -636,10 +636,10 @@  discard block
 block discarded – undo
636 636
 	 * @param	resource	$resultset  Result set of request
637 637
 	 * @return	void
638 638
 	 */
639
-	function free($resultset=null)
639
+	function free($resultset = null)
640 640
 	{
641 641
         // If resultset not provided, we take the last used by connexion
642
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
642
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
643 643
 		// Si resultset en est un, on libere la memoire
644 644
 		if (is_resource($resultset)) pg_free_result($resultset);
645 645
 	}
@@ -652,11 +652,11 @@  discard block
 block discarded – undo
652 652
      *	@param	int		$offset     Numero of line from where starting fetch
653 653
      *	@return	string      		String with SQL syntax to add a limit and offset
654 654
 	 */
655
-	function plimit($limit=0,$offset=0)
655
+	function plimit($limit = 0, $offset = 0)
656 656
 	{
657 657
 		global $conf;
658 658
         if (empty($limit)) return "";
659
-		if ($limit < 0) $limit=$conf->liste_limit;
659
+		if ($limit < 0) $limit = $conf->liste_limit;
660 660
 		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
661 661
 		else return " LIMIT $limit ";
662 662
 	}
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 	 */
683 683
 	function idate($param)
684 684
 	{
685
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
685
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
686 686
 	}
687 687
 
688 688
 	/**
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 	 *  @param	string	$resko          resultat si test non egal
694 694
 	 *  @return	string          		chaine formate SQL
695 695
 	 */
696
-	function ifsql($test,$resok,$resko)
696
+	function ifsql($test, $resok, $resko)
697 697
 	{
698 698
 		return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
699 699
 	}
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 	 */
706 706
 	function errno()
707 707
 	{
708
-		if (! $this->connected) {
708
+		if (!$this->connected) {
709 709
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
710 710
 			return 'DB_ERROR_FAILED_TO_CONNECT';
711 711
 		}
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 			42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
728 728
 			'42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
729 729
 			'23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
730
-			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP',		// May also be Type xxx does not exists
730
+			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
731 731
 			'42601' => 'DB_ERROR_SYNTAX',
732 732
 			'42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
733 733
 			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
@@ -741,18 +741,18 @@  discard block
 block discarded – undo
741 741
 			'42P04' => 'DB_DATABASE_ALREADY_EXISTS'
742 742
 			);
743 743
 
744
-			$errorlabel=pg_last_error($this->db);
745
-			$errorcode='';
746
-			if (preg_match('/: *([0-9P]+):/',$errorlabel,$reg))
744
+			$errorlabel = pg_last_error($this->db);
745
+			$errorcode = '';
746
+			if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg))
747 747
 			{
748
-				$errorcode=$reg[1];
748
+				$errorcode = $reg[1];
749 749
 				if (isset($errorcode_map[$errorcode]))
750 750
 				{
751 751
 					return $errorcode_map[$errorcode];
752 752
 				}
753 753
 			}
754
-			$errno=$errorcode?$errorcode:$errorlabel;
755
-			return ($errno?'DB_ERROR_'.$errno:'0');
754
+			$errno = $errorcode ? $errorcode : $errorlabel;
755
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
756 756
 		}
757 757
 		//                '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
758 758
 		//                '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
@@ -782,18 +782,18 @@  discard block
 block discarded – undo
782 782
 	 * @param	string	$fieldid	Field name
783 783
 	 * @return  string     			Id of row
784 784
 	 */
785
-	function last_insert_id($tab,$fieldid='rowid')
785
+	function last_insert_id($tab, $fieldid = 'rowid')
786 786
 	{
787 787
         // phpcs:enable
788 788
 		//$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
789
-		$result = pg_query($this->db,"SELECT currval('".$tab."_".$fieldid."_seq')");
790
-		if (! $result)
789
+		$result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
790
+		if (!$result)
791 791
 		{
792 792
 			print pg_last_error($this->db);
793 793
 			exit;
794 794
 		}
795 795
 		//$nbre = pg_num_rows($result);
796
-		$row = pg_fetch_result($result,0,0);
796
+		$row = pg_fetch_result($result, 0, 0);
797 797
 		return $row;
798 798
 	}
799 799
 
@@ -805,18 +805,18 @@  discard block
 block discarded – undo
805 805
      *  @param	int		$withQuotes     Return string with quotes
806 806
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
807 807
 	 */
808
-	function encrypt($fieldorvalue, $withQuotes=0)
808
+	function encrypt($fieldorvalue, $withQuotes = 0)
809 809
 	{
810 810
 		global $conf;
811 811
 
812 812
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
813
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
813
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
814 814
 
815 815
 		//Encryption key
816
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
816
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
817 817
 
818 818
 		$return = $fieldorvalue;
819
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
819
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
820 820
 	}
821 821
 
822 822
 
@@ -831,10 +831,10 @@  discard block
 block discarded – undo
831 831
 		global $conf;
832 832
 
833 833
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
834
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
834
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
835 835
 
836 836
 		//Encryption key
837
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
837
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
838 838
 
839 839
 		$return = $value;
840 840
 		return $return;
@@ -867,18 +867,18 @@  discard block
 block discarded – undo
867 867
 	 * 	@param	string	$owner			Username of database owner
868 868
 	 * 	@return	false|resource				resource defined if OK, null if KO
869 869
 	 */
870
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
870
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
871 871
 	{
872 872
         // phpcs:enable
873
-	    if (empty($charset))   $charset=$this->forcecharset;
874
-		if (empty($collation)) $collation=$this->forcecollate;
873
+	    if (empty($charset))   $charset = $this->forcecharset;
874
+		if (empty($collation)) $collation = $this->forcecollate;
875 875
 
876 876
 		// Test charset match LC_TYPE (pgsql error otherwise)
877 877
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
878 878
 
879
-		$sql='CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
880
-		dol_syslog($sql,LOG_DEBUG);
881
-		$ret=$this->query($sql);
879
+		$sql = 'CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
880
+		dol_syslog($sql, LOG_DEBUG);
881
+		$ret = $this->query($sql);
882 882
 		return $ret;
883 883
 	}
884 884
 
@@ -890,17 +890,17 @@  discard block
 block discarded – undo
890 890
 	 *  @param	string		$table		Name of table filter ('xxx%')
891 891
 	 *  @return	array					List of tables in an array
892 892
 	 */
893
-	function DDLListTables($database, $table='')
893
+	function DDLListTables($database, $table = '')
894 894
     {
895 895
         // phpcs:enable
896
-		$listtables=array();
896
+		$listtables = array();
897 897
 
898 898
 		$like = '';
899 899
 		if ($table) $like = " AND table_name LIKE '".$table."'";
900 900
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
901 901
         if ($result)
902 902
         {
903
-    		while($row = $this->fetch_row($result))
903
+    		while ($row = $this->fetch_row($result))
904 904
     		{
905 905
     			$listtables[] = $row[0];
906 906
     		}
@@ -919,29 +919,29 @@  discard block
 block discarded – undo
919 919
 	function DDLInfoTable($table)
920 920
 	{
921 921
         // phpcs:enable
922
-		$infotables=array();
923
-
924
-		$sql="SELECT ";
925
-		$sql.="	infcol.column_name as \"Column\",";
926
-		$sql.="	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
927
-		$sql.="		ELSE infcol.udt_name";
928
-		$sql.="	END as \"Type\",";
929
-		$sql.="	infcol.collation_name as \"Collation\",";
930
-		$sql.="	infcol.is_nullable as \"Null\",";
931
-		$sql.="	'' as \"Key\",";
932
-		$sql.="	infcol.column_default as \"Default\",";
933
-		$sql.="	'' as \"Extra\",";
934
-		$sql.="	'' as \"Privileges\"";
935
-		$sql.="	FROM information_schema.columns infcol";
936
-		$sql.="	WHERE table_schema='public' ";
937
-		$sql.="	AND table_name='".$table."'";
938
-		$sql.="	ORDER BY ordinal_position;";
939
-
940
-		dol_syslog($sql,LOG_DEBUG);
922
+		$infotables = array();
923
+
924
+		$sql = "SELECT ";
925
+		$sql .= "	infcol.column_name as \"Column\",";
926
+		$sql .= "	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
927
+		$sql .= "		ELSE infcol.udt_name";
928
+		$sql .= "	END as \"Type\",";
929
+		$sql .= "	infcol.collation_name as \"Collation\",";
930
+		$sql .= "	infcol.is_nullable as \"Null\",";
931
+		$sql .= "	'' as \"Key\",";
932
+		$sql .= "	infcol.column_default as \"Default\",";
933
+		$sql .= "	'' as \"Extra\",";
934
+		$sql .= "	'' as \"Privileges\"";
935
+		$sql .= "	FROM information_schema.columns infcol";
936
+		$sql .= "	WHERE table_schema='public' ";
937
+		$sql .= "	AND table_name='".$table."'";
938
+		$sql .= "	ORDER BY ordinal_position;";
939
+
940
+		dol_syslog($sql, LOG_DEBUG);
941 941
 		$result = $this->query($sql);
942 942
 		if ($result)
943 943
 		{
944
-    		 while($row = $this->fetch_row($result))
944
+    		 while ($row = $this->fetch_row($result))
945 945
     		 {
946 946
     			$infotables[] = $row;
947 947
     		 }
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
964 964
 	 *	@return	    int						<0 if KO, >=0 if OK
965 965
 	 */
966
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
966
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
967 967
 	{
968 968
         // phpcs:enable
969 969
 		// FIXME: $fulltext_keys parameter is unused
@@ -971,61 +971,61 @@  discard block
 block discarded – undo
971 971
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
972 972
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
973 973
 		$sql = "create table ".$table."(";
974
-		$i=0;
975
-		foreach($fields as $field_name => $field_desc)
974
+		$i = 0;
975
+		foreach ($fields as $field_name => $field_desc)
976 976
 		{
977 977
 			$sqlfields[$i] = $field_name." ";
978 978
 			$sqlfields[$i]  .= $field_desc['type'];
979
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
979
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
980 980
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
981
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
981
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
982 982
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
983
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
983
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
984 984
 			{
985
-				if(preg_match("/null/i",$field_desc['default']))
985
+				if (preg_match("/null/i", $field_desc['default']))
986 986
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
987 987
 				else
988 988
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
989 989
 			}
990
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
990
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
991 991
 			$sqlfields[$i]  .= " ".$field_desc['null'];
992 992
 
993
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
993
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
994 994
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
995 995
 			$i++;
996 996
 		}
997
-		if($primary_key != "")
997
+		if ($primary_key != "")
998 998
 		$pk = "primary key(".$primary_key.")";
999 999
 
1000
-		if(is_array($unique_keys))
1000
+		if (is_array($unique_keys))
1001 1001
 		{
1002 1002
 			$i = 0;
1003
-			foreach($unique_keys as $key => $value)
1003
+			foreach ($unique_keys as $key => $value)
1004 1004
 			{
1005 1005
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
1006 1006
 				$i++;
1007 1007
 			}
1008 1008
 		}
1009
-		if(is_array($keys))
1009
+		if (is_array($keys))
1010 1010
 		{
1011 1011
 			$i = 0;
1012
-			foreach($keys as $key => $value)
1012
+			foreach ($keys as $key => $value)
1013 1013
 			{
1014 1014
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
1015 1015
 				$i++;
1016 1016
 			}
1017 1017
 		}
1018
-		$sql .= implode(',',$sqlfields);
1019
-		if($primary_key != "")
1018
+		$sql .= implode(',', $sqlfields);
1019
+		if ($primary_key != "")
1020 1020
 		$sql .= ",".$pk;
1021
-		if(is_array($unique_keys))
1022
-		$sql .= ",".implode(',',$sqluq);
1023
-		if(is_array($keys))
1024
-		$sql .= ",".implode(',',$sqlk);
1025
-		$sql .=") type=".$type;
1026
-
1027
-		dol_syslog($sql,LOG_DEBUG);
1028
-		if(! $this->query($sql))
1021
+		if (is_array($unique_keys))
1022
+		$sql .= ",".implode(',', $sqluq);
1023
+		if (is_array($keys))
1024
+		$sql .= ",".implode(',', $sqlk);
1025
+		$sql .= ") type=".$type;
1026
+
1027
+		dol_syslog($sql, LOG_DEBUG);
1028
+		if (!$this->query($sql))
1029 1029
 		return -1;
1030 1030
 		else
1031 1031
 		return 1;
@@ -1043,7 +1043,7 @@  discard block
 block discarded – undo
1043 1043
         // phpcs:enable
1044 1044
 		$sql = "DROP TABLE ".$table;
1045 1045
 
1046
-		if (! $this->query($sql))
1046
+		if (!$this->query($sql))
1047 1047
 			return -1;
1048 1048
 		else
1049 1049
 			return 1;
@@ -1059,15 +1059,15 @@  discard block
 block discarded – undo
1059 1059
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1060 1060
 	 *	@return	int									<0 if KO, >=0 if OK
1061 1061
 	 */
1062
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1062
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1063 1063
 	{
1064 1064
         // phpcs:enable
1065 1065
 		// Note: using ' on user does not works with pgsql
1066 1066
 		$sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1067 1067
 
1068
-		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1069
-		$resql=$this->query($sql);
1070
-		if (! $resql)
1068
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1069
+		$resql = $this->query($sql);
1070
+		if (!$resql)
1071 1071
 		{
1072 1072
 			return -1;
1073 1073
 		}
@@ -1083,14 +1083,14 @@  discard block
 block discarded – undo
1083 1083
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1084 1084
 	 *	@return	false|resource		Resultset x (x->attname)
1085 1085
 	 */
1086
-	function DDLDescTable($table,$field="")
1086
+	function DDLDescTable($table, $field = "")
1087 1087
 	{
1088 1088
         // phpcs:enable
1089
-		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1090
-		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1091
-		if ($field) $sql.= " AND attname = '".$field."'";
1089
+		$sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1090
+		$sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1091
+		if ($field) $sql .= " AND attname = '".$field."'";
1092 1092
 
1093
-		dol_syslog($sql,LOG_DEBUG);
1093
+		dol_syslog($sql, LOG_DEBUG);
1094 1094
 		$this->_results = $this->query($sql);
1095 1095
 		return $this->_results;
1096 1096
 	}
@@ -1105,33 +1105,33 @@  discard block
 block discarded – undo
1105 1105
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1106 1106
 	 *	@return	int							<0 if KO, >0 if OK
1107 1107
 	 */
1108
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
1108
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1109 1109
 	{
1110 1110
         // phpcs:enable
1111 1111
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1112 1112
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1113
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1113
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1114 1114
 		$sql .= $field_desc['type'];
1115
-		if (preg_match("/^[^\s]/i",$field_desc['value']))
1116
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1115
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
1116
+		    if (!in_array($field_desc['type'], array('int', 'date', 'datetime')))
1117 1117
 		    {
1118
-		        $sql.= "(".$field_desc['value'].")";
1118
+		        $sql .= "(".$field_desc['value'].")";
1119 1119
 		    }
1120
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1120
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1121 1121
             $sql .= " ".$field_desc['attribute'];
1122
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1122
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
1123 1123
             $sql .= " ".$field_desc['null'];
1124
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1125
-            if (preg_match("/null/i",$field_desc['default']))
1124
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
1125
+            if (preg_match("/null/i", $field_desc['default']))
1126 1126
                 $sql .= " default ".$field_desc['default'];
1127 1127
 		    else
1128 1128
                 $sql .= " default '".$field_desc['default']."'";
1129
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1129
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
1130 1130
             $sql .= " ".$field_desc['extra'];
1131 1131
 		$sql .= " ".$field_position;
1132 1132
 
1133
-		dol_syslog($sql,LOG_DEBUG);
1134
-		if (! $this -> query($sql))
1133
+		dol_syslog($sql, LOG_DEBUG);
1134
+		if (!$this -> query($sql))
1135 1135
 			return -1;
1136 1136
 		return 1;
1137 1137
 	}
@@ -1145,13 +1145,13 @@  discard block
 block discarded – undo
1145 1145
 	 *	@param	string	$field_desc 		Array with description of field format
1146 1146
 	 *	@return	int							<0 if KO, >0 if OK
1147 1147
 	 */
1148
-	function DDLUpdateField($table,$field_name,$field_desc)
1148
+	function DDLUpdateField($table, $field_name, $field_desc)
1149 1149
 	{
1150 1150
         // phpcs:enable
1151 1151
 		$sql = "ALTER TABLE ".$table;
1152 1152
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1153 1153
 		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1154
-			$sql.="(".$field_desc['value'].")";
1154
+			$sql .= "(".$field_desc['value'].")";
1155 1155
 		}
1156 1156
 
1157 1157
 		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
@@ -1159,24 +1159,24 @@  discard block
 block discarded – undo
1159 1159
         	// 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
1160 1160
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1161 1161
         	{
1162
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1162
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1163 1163
         		$this->query($sqlbis);
1164 1164
         	}
1165 1165
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1166 1166
         	{
1167
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1167
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1168 1168
         		$this->query($sqlbis);
1169 1169
         	}
1170 1170
 		}
1171 1171
 
1172 1172
 		if ($field_desc['default'] != '')
1173 1173
 		{
1174
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1175
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1174
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
1175
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
1176 1176
 		}
1177 1177
 
1178
-		dol_syslog($sql,LOG_DEBUG);
1179
-		if (! $this->query($sql))
1178
+		dol_syslog($sql, LOG_DEBUG);
1179
+		if (!$this->query($sql))
1180 1180
 			return -1;
1181 1181
 		return 1;
1182 1182
 	}
@@ -1189,14 +1189,14 @@  discard block
 block discarded – undo
1189 1189
 	 *	@param	string	$field_name 	Name of field to drop
1190 1190
 	 *	@return	int						<0 if KO, >0 if OK
1191 1191
 	 */
1192
-	function DDLDropField($table,$field_name)
1192
+	function DDLDropField($table, $field_name)
1193 1193
 	{
1194 1194
         // phpcs:enable
1195
-		$sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1196
-		dol_syslog($sql,LOG_DEBUG);
1197
-		if (! $this->query($sql))
1195
+		$sql = "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1196
+		dol_syslog($sql, LOG_DEBUG);
1197
+		if (!$this->query($sql))
1198 1198
 		{
1199
-			$this->error=$this->lasterror();
1199
+			$this->error = $this->lasterror();
1200 1200
 			return -1;
1201 1201
 		}
1202 1202
 		return 1;
@@ -1209,10 +1209,10 @@  discard block
 block discarded – undo
1209 1209
 	 */
1210 1210
 	function getDefaultCharacterSetDatabase()
1211 1211
 	{
1212
-		$resql=$this->query('SHOW SERVER_ENCODING');
1212
+		$resql = $this->query('SHOW SERVER_ENCODING');
1213 1213
 		if ($resql)
1214 1214
 		{
1215
-            $liste=$this->fetch_array($resql);
1215
+            $liste = $this->fetch_array($resql);
1216 1216
 		    return $liste['server_encoding'];
1217 1217
 		}
1218 1218
 		else return '';
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 	 */
1226 1226
 	function getListOfCharacterSet()
1227 1227
 	{
1228
-		$resql=$this->query('SHOW SERVER_ENCODING');
1228
+		$resql = $this->query('SHOW SERVER_ENCODING');
1229 1229
 		$liste = array();
1230 1230
 		if ($resql)
1231 1231
 		{
@@ -1250,10 +1250,10 @@  discard block
 block discarded – undo
1250 1250
 	 */
1251 1251
 	function getDefaultCollationDatabase()
1252 1252
 	{
1253
-		$resql=$this->query('SHOW LC_COLLATE');
1253
+		$resql = $this->query('SHOW LC_COLLATE');
1254 1254
 		if ($resql)
1255 1255
 		{
1256
-		    $liste=$this->fetch_array($resql);
1256
+		    $liste = $this->fetch_array($resql);
1257 1257
 			return $liste['lc_collate'];
1258 1258
 		}
1259 1259
 		else return '';
@@ -1266,12 +1266,12 @@  discard block
 block discarded – undo
1266 1266
 	 */
1267 1267
 	function getListOfCollation()
1268 1268
 	{
1269
-		$resql=$this->query('SHOW LC_COLLATE');
1269
+		$resql = $this->query('SHOW LC_COLLATE');
1270 1270
 		$liste = array();
1271 1271
 		if ($resql)
1272 1272
 		{
1273 1273
 			$i = 0;
1274
-			while ($obj = $this->fetch_object($resql) )
1274
+			while ($obj = $this->fetch_object($resql))
1275 1275
 			{
1276 1276
 				$liste[$i]['collation'] = $obj->lc_collate;
1277 1277
 				$i++;
@@ -1290,21 +1290,21 @@  discard block
 block discarded – undo
1290 1290
 	 */
1291 1291
 	function getPathOfDump()
1292 1292
 	{
1293
-		$fullpathofdump='/pathtopgdump/pg_dump';
1293
+		$fullpathofdump = '/pathtopgdump/pg_dump';
1294 1294
 
1295 1295
 		if (file_exists('/usr/bin/pg_dump'))
1296 1296
 		{
1297
-		    $fullpathofdump='/usr/bin/pg_dump';
1297
+		    $fullpathofdump = '/usr/bin/pg_dump';
1298 1298
 		}
1299 1299
 		else
1300 1300
 		{
1301 1301
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1302
-		    $resql=$this->query('SHOW data_directory');
1302
+		    $resql = $this->query('SHOW data_directory');
1303 1303
     		if ($resql)
1304 1304
     		{
1305
-    			$liste=$this->fetch_array($resql);
1306
-    			$basedir=$liste['data_directory'];
1307
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1305
+    			$liste = $this->fetch_array($resql);
1306
+    			$basedir = $liste['data_directory'];
1307
+    			$fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1308 1308
     		}
1309 1309
 		}
1310 1310
 
@@ -1319,23 +1319,23 @@  discard block
 block discarded – undo
1319 1319
 	function getPathOfRestore()
1320 1320
 	{
1321 1321
 		//$tool='pg_restore';
1322
-		$tool='psql';
1322
+		$tool = 'psql';
1323 1323
 
1324
-		$fullpathofdump='/pathtopgrestore/'.$tool;
1324
+		$fullpathofdump = '/pathtopgrestore/'.$tool;
1325 1325
 
1326 1326
         if (file_exists('/usr/bin/'.$tool))
1327 1327
         {
1328
-            $fullpathofdump='/usr/bin/'.$tool;
1328
+            $fullpathofdump = '/usr/bin/'.$tool;
1329 1329
         }
1330 1330
         else
1331 1331
         {
1332 1332
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1333
-            $resql=$this->query('SHOW data_directory');
1333
+            $resql = $this->query('SHOW data_directory');
1334 1334
             if ($resql)
1335 1335
             {
1336
-                $liste=$this->fetch_array($resql);
1337
-                $basedir=$liste['data_directory'];
1338
-                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1336
+                $liste = $this->fetch_array($resql);
1337
+                $basedir = $liste['data_directory'];
1338
+                $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1339 1339
             }
1340 1340
         }
1341 1341
 
@@ -1348,16 +1348,16 @@  discard block
 block discarded – undo
1348 1348
 	 * @param	string	$filter		Filter list on a particular value
1349 1349
 	 * @return	array				Array of key-values (key=>value)
1350 1350
 	 */
1351
-	function getServerParametersValues($filter='')
1351
+	function getServerParametersValues($filter = '')
1352 1352
 	{
1353
-		$result=array();
1353
+		$result = array();
1354 1354
 
1355
-		$resql='select name,setting from pg_settings';
1356
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1357
-		$resql=$this->query($resql);
1355
+		$resql = 'select name,setting from pg_settings';
1356
+		if ($filter) $resql .= " WHERE name = '".$this->escape($filter)."'";
1357
+		$resql = $this->query($resql);
1358 1358
 		if ($resql)
1359 1359
 		{
1360
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1360
+			while ($obj = $this->fetch_object($resql)) $result[$obj->name] = $obj->setting;
1361 1361
 		}
1362 1362
 
1363 1363
 		return $result;
@@ -1369,7 +1369,7 @@  discard block
 block discarded – undo
1369 1369
 	 * @param	string	$filter		Filter list on a particular value
1370 1370
 	 * @return  array				Array of key-values (key=>value)
1371 1371
 	 */
1372
-	function getServerStatusValues($filter='')
1372
+	function getServerStatusValues($filter = '')
1373 1373
 	{
1374 1374
 		/* This is to return current running requests.
1375 1375
 		$sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
Please login to merge, or discard this patch.
dolibarr/htdocs/core/db/sqlite3.class.php 3 patches
Indentation   +135 added lines, -135 removed lines patch added patch discarded remove patch
@@ -38,8 +38,8 @@  discard block
 block discarded – undo
38 38
     const LABEL='Sqlite3';
39 39
     //! Version min database
40 40
     const VERSIONMIN='3.0.0';
41
-	/** @var SQLite3Result Resultset of last query */
42
-	private $_results;
41
+    /** @var SQLite3Result Resultset of last query */
42
+    private $_results;
43 43
 
44 44
     const WEEK_MONDAY_FIRST=1;
45 45
     const WEEK_YEAR = 2;
@@ -47,15 +47,15 @@  discard block
 block discarded – undo
47 47
 
48 48
 
49 49
     /**
50
-	 *	Constructor.
51
-	 *	This create an opened connexion to a database server and eventually to a database
50
+     *	Constructor.
51
+     *	This create an opened connexion to a database server and eventually to a database
52 52
      *
53
-	 *	@param      string	$type		Type of database (mysql, pgsql...)
54
-	 *	@param	    string	$host		Address of database server
55
-	 *	@param	    string	$user		Nom de l'utilisateur autorise
56
-	 *	@param	    string	$pass		Mot de passe
57
-	 *	@param	    string	$name		Nom de la database
58
-	 *	@param	    int		$port		Port of database server
53
+     *	@param      string	$type		Type of database (mysql, pgsql...)
54
+     *	@param	    string	$host		Address of database server
55
+     *	@param	    string	$user		Nom de l'utilisateur autorise
56
+     *	@param	    string	$pass		Mot de passe
57
+     *	@param	    string	$name		Nom de la database
58
+     *	@param	    int		$port		Port of database server
59 59
      */
60 60
     function __construct($type, $host, $user, $pass, $name='', $port=0)
61 61
     {
@@ -149,9 +149,9 @@  discard block
 block discarded – undo
149 149
         {
150 150
             if ($type == 'auto')
151 151
             {
152
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
153
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
154
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
152
+                if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
153
+                else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
154
+                else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
155 155
             }
156 156
 
157 157
             if ($type == 'dml')
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
272 272
             if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
273 273
             {
274
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
274
+                if ($reg[1] == $reg[2])	// If same table, we remove second one
275 275
                 {
276 276
                     $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
277 277
                 }
@@ -297,10 +297,10 @@  discard block
 block discarded – undo
297 297
 
298 298
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
299 299
     /**
300
-	 *	Select a database
300
+     *	Select a database
301 301
      *
302
-	 *	@param	    string	$database	Name of database
303
-	 *	@return	    boolean  		    true if OK, false if KO
302
+     *	@param	    string	$database	Name of database
303
+     *	@return	    boolean  		    true if OK, false if KO
304 304
      */
305 305
     function select_db($database)
306 306
     {
@@ -313,15 +313,15 @@  discard block
 block discarded – undo
313 313
 
314 314
 
315 315
     /**
316
-	 *	Connexion to server
316
+     *	Connexion to server
317 317
      *
318
-	 *	@param	    string	$host		database server host
319
-	 *	@param	    string	$login		login
320
-	 *	@param	    string	$passwd		password
321
-	 *	@param		string	$name		name of database (not used for mysql, used for pgsql)
322
-	 *	@param		integer	$port		Port of database server
323
-	 *	@return		SQLite3				Database access handler
324
-	 *	@see		close
318
+     *	@param	    string	$host		database server host
319
+     *	@param	    string	$login		login
320
+     *	@param	    string	$passwd		password
321
+     *	@param		string	$name		name of database (not used for mysql, used for pgsql)
322
+     *	@param		integer	$port		Port of database server
323
+     *	@return		SQLite3				Database access handler
324
+     *	@see		close
325 325
      */
326 326
     function connect($host, $login, $passwd, $name, $port=0)
327 327
     {
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
         try {
338 338
             /*** connect to SQLite database ***/
339 339
             //$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
340
-			$this->db = new SQLite3($database_name);
340
+            $this->db = new SQLite3($database_name);
341 341
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
342 342
         }
343 343
         catch(Exception $e)
@@ -352,13 +352,13 @@  discard block
 block discarded – undo
352 352
 
353 353
 
354 354
     /**
355
-	 *	Return version of database server
355
+     *	Return version of database server
356 356
      *
357
-	 *	@return	        string      Version string
357
+     *	@return	        string      Version string
358 358
      */
359 359
     function getVersion()
360 360
     {
361
-    	$tmp=$this->db->version();
361
+        $tmp=$this->db->version();
362 362
         return $tmp['versionString'];
363 363
     }
364 364
 
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
         if ($ret) {
508 508
             return (object) $ret;
509 509
         }
510
-		return false;
510
+        return false;
511 511
     }
512 512
 
513 513
 
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
         if (! is_object($resultset)) { $resultset=$this->_results; }
526 526
         //return $resultset->fetch(PDO::FETCH_ASSOC);
527 527
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
528
-	    return $ret;
528
+        return $ret;
529 529
     }
530 530
 
531 531
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -597,10 +597,10 @@  discard block
 block discarded – undo
597 597
 
598 598
 
599 599
     /**
600
-	 *	Free last resultset used.
600
+     *	Free last resultset used.
601 601
      *
602
-	 *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
603
-	 *	@return	void
602
+     *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
603
+     *	@return	void
604 604
      */
605 605
     function free($resultset=null)
606 606
     {
@@ -611,10 +611,10 @@  discard block
 block discarded – undo
611 611
     }
612 612
 
613 613
     /**
614
-	 *	Escape a string to insert data
614
+     *	Escape a string to insert data
615 615
      *
616
-	 *  @param	string	$stringtoencode		String to escape
617
-	 *  @return	string						String escaped
616
+     *  @param	string	$stringtoencode		String to escape
617
+     *  @return	string						String escaped
618 618
      */
619 619
     function escape($stringtoencode)
620 620
     {
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
                 return $errorcode_map[$this->db->errorCode()];
668 668
             }*/
669 669
             $errno=$this->db->lastErrorCode();
670
-			if ($errno=='HY000' || $errno == 0)
670
+            if ($errno=='HY000' || $errno == 0)
671 671
             {
672 672
                 if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
673 673
                 elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
@@ -706,9 +706,9 @@  discard block
 block discarded – undo
706 706
     /**
707 707
      * Get last ID after an insert INSERT
708 708
      *
709
-	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
710
-	 * @param	string	$fieldid	Field name
711
-	 * @return  int     			Id of row
709
+     * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
710
+     * @param	string	$fieldid	Field name
711
+     * @return  int     			Id of row
712 712
      */
713 713
     function last_insert_id($tab,$fieldid='rowid')
714 714
     {
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
     /**
790 790
      * Return connexion ID
791 791
      *
792
-	 * @return	        string      Id connexion
792
+     * @return	        string      Id connexion
793 793
      */
794 794
     function DDLGetConnectId()
795 795
     {
@@ -800,15 +800,15 @@  discard block
 block discarded – undo
800 800
 
801 801
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
802 802
     /**
803
-	 *	Create a new database
804
-	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
805
-	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
803
+     *	Create a new database
804
+     *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
805
+     *	We force to create database with charset this->forcecharset and collate this->forcecollate
806 806
      *
807
-	 *	@param	string	$database		Database name to create
808
-	 * 	@param	string	$charset		Charset used to store data
809
-	 * 	@param	string	$collation		Charset used to sort data
810
-	 * 	@param	string	$owner			Username of database owner
811
-	 * 	@return	SQLite3Result   		resource defined if OK, null if KO
807
+     *	@param	string	$database		Database name to create
808
+     * 	@param	string	$charset		Charset used to store data
809
+     * 	@param	string	$collation		Charset used to sort data
810
+     * 	@param	string	$owner			Username of database owner
811
+     * 	@return	SQLite3Result   		resource defined if OK, null if KO
812 812
      */
813 813
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
814 814
     {
@@ -836,9 +836,9 @@  discard block
 block discarded – undo
836 836
     /**
837 837
      *  List tables into a database
838 838
      *
839
-	 *  @param	string		$database	Name of database
840
-	 *  @param	string		$table		Name of table filter ('xxx%')
841
-	 *  @return	array					List of tables in an array
839
+     *  @param	string		$database	Name of database
840
+     *  @param	string		$table		Name of table filter ('xxx%')
841
+     *  @return	array					List of tables in an array
842 842
      */
843 843
     function DDLListTables($database, $table='')
844 844
     {
@@ -864,9 +864,9 @@  discard block
 block discarded – undo
864 864
     /**
865 865
      *  List information of columns into a table.
866 866
      *
867
-	 *	@param	string	$table		Name of table
868
-	 *	@return	array				Tableau des informations des champs de la table
869
-	 *	TODO modify for sqlite
867
+     *	@param	string	$table		Name of table
868
+     *	@return	array				Tableau des informations des champs de la table
869
+     *	TODO modify for sqlite
870 870
      */
871 871
     function DDLInfoTable($table)
872 872
     {
@@ -889,16 +889,16 @@  discard block
 block discarded – undo
889 889
 
890 890
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
891 891
     /**
892
-	 *	Create a table into database
892
+     *	Create a table into database
893 893
      *
894
-	 *	@param	    string	$table 			Nom de la table
895
-	 *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
896
-	 *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
897
-	 *	@param	    string	$type 			Type de la table
898
-	 *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
899
-	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
900
-	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
901
-	 *	@return	    int						<0 if KO, >=0 if OK
894
+     *	@param	    string	$table 			Nom de la table
895
+     *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
896
+     *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
897
+     *	@param	    string	$type 			Type de la table
898
+     *	@param	    array	$unique_keys 	Tableau associatifs Nom de champs qui seront clef unique => valeur
899
+     *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
900
+     *	@param	    array	$keys 			Tableau des champs cles noms => valeur
901
+     *	@return	    int						<0 if KO, >=0 if OK
902 902
      */
903 903
     function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
904 904
     {
@@ -977,21 +977,21 @@  discard block
 block discarded – undo
977 977
     function DDLDropTable($table)
978 978
     {
979 979
         // phpcs:enable
980
-    	$sql = "DROP TABLE ".$table;
980
+        $sql = "DROP TABLE ".$table;
981 981
 
982
-    	if (! $this->query($sql))
983
-    		return -1;
984
-    	else
985
-    		return 1;
982
+        if (! $this->query($sql))
983
+            return -1;
984
+        else
985
+            return 1;
986 986
     }
987 987
 
988 988
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
989 989
     /**
990
-	 *	Return a pointer of line with description of a table or field
990
+     *	Return a pointer of line with description of a table or field
991 991
      *
992
-	 *	@param	string		$table	Name of table
993
-	 *	@param	string		$field	Optionnel : Name of field if we want description of field
994
-	 *	@return	SQLite3Result		Resource
992
+     *	@param	string		$table	Name of table
993
+     *	@param	string		$field	Optionnel : Name of field if we want description of field
994
+     *	@return	SQLite3Result		Resource
995 995
      */
996 996
     function DDLDescTable($table,$field="")
997 997
     {
@@ -1005,13 +1005,13 @@  discard block
 block discarded – undo
1005 1005
 
1006 1006
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1007 1007
     /**
1008
-	 *	Create a new field into table
1008
+     *	Create a new field into table
1009 1009
      *
1010
-	 *	@param	string	$table 				Name of table
1011
-	 *	@param	string	$field_name 		Name of field to add
1012
-	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
1013
-	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1014
-	 *	@return	int							<0 if KO, >0 if OK
1010
+     *	@param	string	$table 				Name of table
1011
+     *	@param	string	$field_name 		Name of field to add
1012
+     *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
1013
+     *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1014
+     *	@return	int							<0 if KO, >0 if OK
1015 1015
      */
1016 1016
     function DDLAddField($table,$field_name,$field_desc,$field_position="")
1017 1017
     {
@@ -1050,12 +1050,12 @@  discard block
 block discarded – undo
1050 1050
 
1051 1051
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1052 1052
     /**
1053
-	 *	Update format of a field into a table
1053
+     *	Update format of a field into a table
1054 1054
      *
1055
-	 *	@param	string	$table 				Name of table
1056
-	 *	@param	string	$field_name 		Name of field to modify
1057
-	 *	@param	string	$field_desc 		Array with description of field format
1058
-	 *	@return	int							<0 if KO, >0 if OK
1055
+     *	@param	string	$table 				Name of table
1056
+     *	@param	string	$field_name 		Name of field to modify
1057
+     *	@param	string	$field_desc 		Array with description of field format
1058
+     *	@return	int							<0 if KO, >0 if OK
1059 1059
      */
1060 1060
     function DDLUpdateField($table,$field_name,$field_desc)
1061 1061
     {
@@ -1074,11 +1074,11 @@  discard block
 block discarded – undo
1074 1074
 
1075 1075
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1076 1076
     /**
1077
-	 *	Drop a field from table
1077
+     *	Drop a field from table
1078 1078
      *
1079
-	 *	@param	string	$table 			Name of table
1080
-	 *	@param	string	$field_name 	Name of field to drop
1081
-	 *	@return	int						<0 if KO, >0 if OK
1079
+     *	@param	string	$table 			Name of table
1080
+     *	@param	string	$field_name 	Name of field to drop
1081
+     *	@return	int						<0 if KO, >0 if OK
1082 1082
      */
1083 1083
     function DDLDropField($table,$field_name)
1084 1084
     {
@@ -1098,11 +1098,11 @@  discard block
 block discarded – undo
1098 1098
     /**
1099 1099
      * 	Create a user and privileges to connect to database (even if database does not exists yet)
1100 1100
      *
1101
-	 *	@param	string	$dolibarr_main_db_host 		Ip serveur
1102
-	 *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1103
-	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1104
-	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1105
-	 *	@return	int									<0 if KO, >=0 if OK
1101
+     *	@param	string	$dolibarr_main_db_host 		Ip serveur
1102
+     *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1103
+     *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1104
+     *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1105
+     *	@return	int									<0 if KO, >=0 if OK
1106 1106
      */
1107 1107
     function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1108 1108
     {
@@ -1143,9 +1143,9 @@  discard block
 block discarded – undo
1143 1143
     }
1144 1144
 
1145 1145
     /**
1146
-	 *	Return charset used to store data in database
1146
+     *	Return charset used to store data in database
1147 1147
      *
1148
-	 *	@return		string		Charset
1148
+     *	@return		string		Charset
1149 1149
      */
1150 1150
     function getDefaultCharacterSetDatabase()
1151 1151
     {
@@ -1153,9 +1153,9 @@  discard block
 block discarded – undo
1153 1153
     }
1154 1154
 
1155 1155
     /**
1156
-	 *	Return list of available charset that can be used to store data in database
1156
+     *	Return list of available charset that can be used to store data in database
1157 1157
      *
1158
-	 *	@return		array		List of Charset
1158
+     *	@return		array		List of Charset
1159 1159
      */
1160 1160
     function getListOfCharacterSet()
1161 1161
     {
@@ -1167,9 +1167,9 @@  discard block
 block discarded – undo
1167 1167
     }
1168 1168
 
1169 1169
     /**
1170
-	 *	Return collation used in database
1170
+     *	Return collation used in database
1171 1171
      *
1172
-	 *	@return		string		Collation value
1172
+     *	@return		string		Collation value
1173 1173
      */
1174 1174
     function getDefaultCollationDatabase()
1175 1175
     {
@@ -1177,9 +1177,9 @@  discard block
 block discarded – undo
1177 1177
     }
1178 1178
 
1179 1179
     /**
1180
-	 *	Return list of available collation that can be used for database
1180
+     *	Return list of available collation that can be used for database
1181 1181
      *
1182
-	 *	@return		array		List of Collation
1182
+     *	@return		array		List of Collation
1183 1183
      */
1184 1184
     function getListOfCollation()
1185 1185
     {
@@ -1191,13 +1191,13 @@  discard block
 block discarded – undo
1191 1191
     }
1192 1192
 
1193 1193
     /**
1194
-	 *	Return full path of dump program
1194
+     *	Return full path of dump program
1195 1195
      *
1196
-	 *	@return		string		Full path of dump program
1196
+     *	@return		string		Full path of dump program
1197 1197
      */
1198 1198
     function getPathOfDump()
1199 1199
     {
1200
-	    // FIXME: not for SQLite
1200
+        // FIXME: not for SQLite
1201 1201
         $fullpathofdump='/pathtomysqldump/mysqldump';
1202 1202
 
1203 1203
         $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
@@ -1211,13 +1211,13 @@  discard block
 block discarded – undo
1211 1211
     }
1212 1212
 
1213 1213
     /**
1214
-	 *	Return full path of restore program
1214
+     *	Return full path of restore program
1215 1215
      *
1216
-	 *	@return		string		Full path of restore program
1216
+     *	@return		string		Full path of restore program
1217 1217
      */
1218 1218
     function getPathOfRestore()
1219 1219
     {
1220
-	    // FIXME: not for SQLite
1220
+        // FIXME: not for SQLite
1221 1221
         $fullpathofimport='/pathtomysql/mysql';
1222 1222
 
1223 1223
         $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
@@ -1233,8 +1233,8 @@  discard block
 block discarded – undo
1233 1233
     /**
1234 1234
      * Return value of server parameters
1235 1235
      *
1236
-	 * @param	string	$filter		Filter list on a particular value
1237
-	 * @return	array				Array of key-values (key=>value)
1236
+     * @param	string	$filter		Filter list on a particular value
1237
+     * @return	array				Array of key-values (key=>value)
1238 1238
      */
1239 1239
     function getServerParametersValues($filter='')
1240 1240
     {
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
             $pragmas = array(
1248 1248
                 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1249 1249
                 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1250
-				'compile_options', 'data_version',	/*'database_list',*/
1250
+                'compile_options', 'data_version',	/*'database_list',*/
1251 1251
                 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1252 1252
                 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1253 1253
                 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
@@ -1282,8 +1282,8 @@  discard block
 block discarded – undo
1282 1282
     /**
1283 1283
      * Return value of server status
1284 1284
      *
1285
-	 * @param	string	$filter		Filter list on a particular value
1286
-	 * @return  array				Array of key-values (key=>value)
1285
+     * @param	string	$filter		Filter list on a particular value
1286
+     * @return  array				Array of key-values (key=>value)
1287 1287
      */
1288 1288
     function getServerStatusValues($filter='')
1289 1289
     {
@@ -1314,7 +1314,7 @@  discard block
 block discarded – undo
1314 1314
     {
1315 1315
         if ($this->db)
1316 1316
         {
1317
-        	$newname=preg_replace('/_/','',$name);
1317
+            $newname=preg_replace('/_/','',$name);
1318 1318
             $localname = __CLASS__ . '::' . 'db' . $newname;
1319 1319
             $reflectClass = new ReflectionClass(__CLASS__);
1320 1320
             $reflectFunction = $reflectClass->getMethod('db' . $newname);
@@ -1381,16 +1381,16 @@  discard block
 block discarded – undo
1381 1381
     }
1382 1382
 
1383 1383
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1384
-	/**
1385
-	 * calc_week
1386
-	 *
1387
-	 * @param 	string	$year				Year
1388
-	 * @param 	string	$month				Month
1389
-	 * @param 	string	$day				Day
1390
-	 * @param 	string	$week_behaviour		Week behaviour
1391
-	 * @param 	string	$calc_year			???
1392
-	 * @return	string						???
1393
-	 */
1384
+    /**
1385
+     * calc_week
1386
+     *
1387
+     * @param 	string	$year				Year
1388
+     * @param 	string	$month				Month
1389
+     * @param 	string	$day				Day
1390
+     * @param 	string	$week_behaviour		Week behaviour
1391
+     * @param 	string	$calc_year			???
1392
+     * @return	string						???
1393
+     */
1394 1394
     private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year)
1395 1395
     {
1396 1396
         // phpcs:enable
@@ -1411,24 +1411,24 @@  discard block
 block discarded – undo
1411 1411
             $calc_year--;
1412 1412
             $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1413 1413
             $weekday= ($weekday + 53*7- $days) % 7;
1414
-      }
1414
+        }
1415 1415
 
1416
-      if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1416
+        if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1417 1417
         $days= $daynr - ($first_daynr+ (7-$weekday));
1418
-      }
1419
-      else {
1418
+        }
1419
+        else {
1420 1420
         $days= $daynr - ($first_daynr - $weekday);
1421
-      }
1421
+        }
1422 1422
 
1423
-      if ($week_year && $days >= 52*7)
1424
-      {
1423
+        if ($week_year && $days >= 52*7)
1424
+        {
1425 1425
         $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1426 1426
         if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1427 1427
         {
1428
-          $calc_year++;
1429
-          return 1;
1428
+            $calc_year++;
1429
+            return 1;
1430
+        }
1430 1431
         }
1431
-      }
1432
-      return floor($days/7+1);
1432
+        return floor($days/7+1);
1433 1433
     }
1434 1434
 }
Please login to merge, or discard this patch.
Braces   +117 added lines, -84 removed lines patch added patch discarded remove patch
@@ -62,8 +62,12 @@  discard block
 block discarded – undo
62 62
         global $conf;
63 63
 
64 64
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
65
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
66
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
65
+        if (! empty($conf->db->character_set)) {
66
+            $this->forcecharset=$conf->db->character_set;
67
+        }
68
+        if (! empty($conf->db->dolibarr_main_db_collation)) {
69
+            $this->forcecollate=$conf->db->dolibarr_main_db_collation;
70
+        }
67 71
 
68 72
         $this->database_user=$user;
69 73
         $this->database_host=$host;
@@ -111,8 +115,7 @@  discard block
 block discarded – undo
111 115
             $this->addCustomFunction('WEEKDAY');
112 116
             $this->addCustomFunction('date_format');
113 117
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
-        }
115
-        else
118
+        } else
116 119
         {
117 120
             // host, login ou password incorrect
118 121
             $this->connected = false;
@@ -149,9 +152,13 @@  discard block
 block discarded – undo
149 152
         {
150 153
             if ($type == 'auto')
151 154
             {
152
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
153
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
154
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
155
+              if (preg_match('/ALTER TABLE/i',$line)) {
156
+                  $type='dml';
157
+              } else if (preg_match('/CREATE TABLE/i',$line)) {
158
+                  $type='dml';
159
+              } else if (preg_match('/DROP TABLE/i',$line)) {
160
+                  $type='dml';
161
+              }
155 162
             }
156 163
 
157 164
             if ($type == 'dml')
@@ -271,9 +278,11 @@  discard block
 block discarded – undo
271 278
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
272 279
             if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
273 280
             {
274
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
281
+				if ($reg[1] == $reg[2]) {
282
+				    // If same table, we remove second one
275 283
                 {
276 284
                     $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
285
+				}
277 286
                 }
278 287
             }
279 288
 
@@ -330,7 +339,9 @@  discard block
 block discarded – undo
330 339
         dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
331 340
 
332 341
         $dir=$main_data_dir;
333
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
342
+        if (empty($dir)) {
343
+            $dir=DOL_DATA_ROOT;
344
+        }
334 345
         // With sqlite, port must be in connect parameters
335 346
         //if (! $newport) $newport=3306;
336 347
         $database_name = $dir.'/database_'.$name.'.sdb';
@@ -339,8 +350,7 @@  discard block
 block discarded – undo
339 350
             //$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
340 351
 			$this->db = new SQLite3($database_name);
341 352
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
342
-        }
343
-        catch(Exception $e)
353
+        } catch(Exception $e)
344 354
         {
345 355
             $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
346 356
             return '';
@@ -383,7 +393,9 @@  discard block
 block discarded – undo
383 393
     {
384 394
         if ($this->db)
385 395
         {
386
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
396
+            if ($this->transaction_opened > 0) {
397
+                dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
398
+            }
387 399
             $this->connected=false;
388 400
             $this->db->close();
389 401
             unset($this->db);    // Clean this->db
@@ -458,8 +470,7 @@  discard block
 block discarded – undo
458 470
             if ($ret) {
459 471
                 $ret->queryString = $query;
460 472
             }
461
-        }
462
-        catch(Exception $e)
473
+        } catch(Exception $e)
463 474
         {
464 475
             $this->error=$this->db->lastErrorMsg();
465 476
         }
@@ -543,8 +554,7 @@  discard block
 block discarded – undo
543 554
         {
544 555
             if (! is_object($resultset)) { $resultset=$this->_results; }
545 556
             return $resultset->fetchArray(SQLITE3_NUM);
546
-        }
547
-        else
557
+        } else
548 558
         {
549 559
             // si le curseur est un booleen on retourne la valeur 0
550 560
             return false;
@@ -607,7 +617,9 @@  discard block
 block discarded – undo
607 617
         // If resultset not provided, we take the last used by connexion
608 618
         if (! is_object($resultset)) { $resultset=$this->_results; }
609 619
         // Si resultset en est un, on libere la memoire
610
-        if ($resultset && is_object($resultset)) $resultset->finalize();
620
+        if ($resultset && is_object($resultset)) {
621
+            $resultset->finalize();
622
+        }
611 623
     }
612 624
 
613 625
     /**
@@ -631,8 +643,7 @@  discard block
 block discarded – undo
631 643
         if (! $this->connected) {
632 644
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
633 645
             return 'DB_ERROR_FAILED_TO_CONNECT';
634
-        }
635
-        else {
646
+        } else {
636 647
             // Constants to convert error code to a generic Dolibarr error code
637 648
             /*$errorcode_map = array(
638 649
             1004 => 'DB_ERROR_CANNOT_CREATE',
@@ -669,14 +680,21 @@  discard block
 block discarded – undo
669 680
             $errno=$this->db->lastErrorCode();
670 681
 			if ($errno=='HY000' || $errno == 0)
671 682
             {
672
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
673
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
674
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
683
+                if (preg_match('/table.*already exists/i',$this->error)) {
684
+                    return 'DB_ERROR_TABLE_ALREADY_EXISTS';
685
+                } elseif (preg_match('/index.*already exists/i',$this->error)) {
686
+                    return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
687
+                } elseif (preg_match('/syntax error/i',$this->error)) {
688
+                    return 'DB_ERROR_SYNTAX';
689
+                }
675 690
             }
676 691
             if ($errno=='23000')
677 692
             {
678
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
679
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
693
+                if (preg_match('/column.* not unique/i',$this->error)) {
694
+                    return 'DB_ERROR_RECORD_ALREADY_EXISTS';
695
+                } elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) {
696
+                    return 'DB_ERROR_RECORD_ALREADY_EXISTS';
697
+                }
680 698
             }
681 699
             if ($errno > 1) {
682 700
                 // TODO Voir la liste des messages d'erreur
@@ -696,8 +714,7 @@  discard block
 block discarded – undo
696 714
         if (! $this->connected) {
697 715
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
698 716
             return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
699
-        }
700
-        else {
717
+        } else {
701 718
             return $this->error;
702 719
         }
703 720
     }
@@ -741,8 +758,7 @@  discard block
 block discarded – undo
741 758
             if ($cryptType == 2)
742 759
             {
743 760
                 $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
744
-            }
745
-            else if ($cryptType == 1)
761
+            } else if ($cryptType == 1)
746 762
             {
747 763
                 $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
748 764
             }
@@ -774,8 +790,7 @@  discard block
 block discarded – undo
774 790
             if ($cryptType == 2)
775 791
             {
776 792
                 $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
777
-            }
778
-            else if ($cryptType == 1)
793
+            } else if ($cryptType == 1)
779 794
             {
780 795
                 $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
781 796
             }
@@ -813,8 +828,12 @@  discard block
 block discarded – undo
813 828
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
814 829
     {
815 830
         // phpcs:enable
816
-        if (empty($charset))   $charset=$this->forcecharset;
817
-        if (empty($collation)) $collation=$this->forcecollate;
831
+        if (empty($charset)) {
832
+            $charset=$this->forcecharset;
833
+        }
834
+        if (empty($collation)) {
835
+            $collation=$this->forcecollate;
836
+        }
818 837
 
819 838
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
820 839
         $sql = 'CREATE DATABASE '.$database;
@@ -846,7 +865,9 @@  discard block
 block discarded – undo
846 865
         $listtables=array();
847 866
 
848 867
         $like = '';
849
-        if ($table) $like = "LIKE '".$table."'";
868
+        if ($table) {
869
+            $like = "LIKE '".$table."'";
870
+        }
850 871
         $sql="SHOW TABLES FROM ".$database." ".$like.";";
851 872
         //print $sql;
852 873
         $result = $this->query($sql);
@@ -913,26 +934,27 @@  discard block
 block discarded – undo
913 934
         {
914 935
             $sqlfields[$i] = $field_name." ";
915 936
             $sqlfields[$i]  .= $field_desc['type'];
916
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
917
-            $sqlfields[$i]  .= "(".$field_desc['value'].")";
918
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
919
-            $sqlfields[$i]  .= " ".$field_desc['attribute'];
920
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
937
+            if( preg_match("/^[^\s]/i",$field_desc['value'])) {
938
+                        $sqlfields[$i]  .= "(".$field_desc['value'].")";
939
+            } else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
940
+                        $sqlfields[$i]  .= " ".$field_desc['attribute'];
941
+            } else if( preg_match("/^[^\s]/i",$field_desc['default']))
921 942
             {
922
-                if(preg_match("/null/i",$field_desc['default']))
923
-                $sqlfields[$i]  .= " default ".$field_desc['default'];
924
-                else
925
-                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
943
+                if(preg_match("/null/i",$field_desc['default'])) {
944
+                                $sqlfields[$i]  .= " default ".$field_desc['default'];
945
+                } else {
946
+                                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
947
+                }
948
+            } else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
949
+                        $sqlfields[$i]  .= " ".$field_desc['null'];
950
+            } else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
951
+                        $sqlfields[$i]  .= " ".$field_desc['extra'];
926 952
             }
927
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
928
-            $sqlfields[$i]  .= " ".$field_desc['null'];
929
-
930
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
931
-            $sqlfields[$i]  .= " ".$field_desc['extra'];
932 953
             $i++;
933 954
         }
934
-        if($primary_key != "")
935
-        $pk = "primary key(".$primary_key.")";
955
+        if($primary_key != "") {
956
+                $pk = "primary key(".$primary_key.")";
957
+        }
936 958
 
937 959
         if(is_array($unique_keys))
938 960
         {
@@ -953,17 +975,21 @@  discard block
 block discarded – undo
953 975
             }
954 976
         }
955 977
         $sql .= implode(',',$sqlfields);
956
-        if($primary_key != "")
957
-        $sql .= ",".$pk;
958
-        if(is_array($unique_keys))
959
-        $sql .= ",".implode(',',$sqluq);
960
-        if(is_array($keys))
961
-        $sql .= ",".implode(',',$sqlk);
978
+        if($primary_key != "") {
979
+                $sql .= ",".$pk;
980
+        }
981
+        if(is_array($unique_keys)) {
982
+                $sql .= ",".implode(',',$sqluq);
983
+        }
984
+        if(is_array($keys)) {
985
+                $sql .= ",".implode(',',$sqlk);
986
+        }
962 987
         $sql .=") type=".$type;
963 988
 
964 989
         dol_syslog($sql,LOG_DEBUG);
965
-        if(! $this -> query($sql))
966
-            return -1;
990
+        if(! $this -> query($sql)) {
991
+                    return -1;
992
+        }
967 993
         return 1;
968 994
     }
969 995
 
@@ -979,10 +1005,11 @@  discard block
 block discarded – undo
979 1005
         // phpcs:enable
980 1006
     	$sql = "DROP TABLE ".$table;
981 1007
 
982
-    	if (! $this->query($sql))
983
-    		return -1;
984
-    	else
985
-    		return 1;
1008
+    	if (! $this->query($sql)) {
1009
+    	    		return -1;
1010
+    	} else {
1011
+    	    		return 1;
1012
+    	}
986 1013
     }
987 1014
 
988 1015
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1020,24 +1047,29 @@  discard block
 block discarded – undo
1020 1047
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1021 1048
         $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1022 1049
         $sql.= $field_desc['type'];
1023
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
1024
-        if (! in_array($field_desc['type'],array('date','datetime')))
1050
+        if(preg_match("/^[^\s]/i",$field_desc['value'])) {
1051
+                if (! in_array($field_desc['type'],array('date','datetime')))
1025 1052
         {
1026 1053
             $sql.= "(".$field_desc['value'].")";
1027 1054
         }
1028
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1029
-        $sql.= " ".$field_desc['attribute'];
1030
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1031
-        $sql.= " ".$field_desc['null'];
1055
+        }
1056
+        if(preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1057
+                $sql.= " ".$field_desc['attribute'];
1058
+        }
1059
+        if(preg_match("/^[^\s]/i",$field_desc['null'])) {
1060
+                $sql.= " ".$field_desc['null'];
1061
+        }
1032 1062
         if(preg_match("/^[^\s]/i",$field_desc['default']))
1033 1063
         {
1034
-            if(preg_match("/null/i",$field_desc['default']))
1035
-            $sql.= " default ".$field_desc['default'];
1036
-            else
1037
-            $sql.= " default '".$field_desc['default']."'";
1064
+            if(preg_match("/null/i",$field_desc['default'])) {
1065
+                        $sql.= " default ".$field_desc['default'];
1066
+            } else {
1067
+                        $sql.= " default '".$field_desc['default']."'";
1068
+            }
1069
+        }
1070
+        if(preg_match("/^[^\s]/i",$field_desc['extra'])) {
1071
+                $sql.= " ".$field_desc['extra'];
1038 1072
         }
1039
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1040
-        $sql.= " ".$field_desc['extra'];
1041 1073
         $sql.= " ".$field_position;
1042 1074
 
1043 1075
         dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
@@ -1067,8 +1099,9 @@  discard block
 block discarded – undo
1067 1099
         }
1068 1100
 
1069 1101
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1070
-        if (! $this->query($sql))
1071
-            return -1;
1102
+        if (! $this->query($sql)) {
1103
+                    return -1;
1104
+        }
1072 1105
         return 1;
1073 1106
     }
1074 1107
 
@@ -1270,8 +1303,7 @@  discard block
 block discarded – undo
1270 1303
                 $obj = $this->fetch_row($resql);
1271 1304
                 //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1272 1305
                 $result[$var] = $obj[0];
1273
-            }
1274
-            else {
1306
+            } else {
1275 1307
                 // TODO Récupérer le message
1276 1308
                 $result[$var] = 'FAIL';
1277 1309
             }
@@ -1341,11 +1373,12 @@  discard block
 block discarded – undo
1341 1373
     {
1342 1374
         // phpcs:enable
1343 1375
         $y = $year;
1344
-        if ($y == 0 && $month == 0) return 0;
1376
+        if ($y == 0 && $month == 0) {
1377
+            return 0;
1378
+        }
1345 1379
         $num = (365* $y + 31 * ($month - 1) + $day);
1346 1380
         if ($month <= 2) {
1347
-            $y--; }
1348
-        else {
1381
+            $y--; } else {
1349 1382
             $num -= floor(($month * 4 + 23) / 10);
1350 1383
         }
1351 1384
         $temp = floor(($y / 100 + 1) * 3 / 4);
@@ -1405,8 +1438,9 @@  discard block
 block discarded – undo
1405 1438
 
1406 1439
         if ($month == 1 && $day <= 7-$weekday)
1407 1440
         {
1408
-            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1409
-                return 0;
1441
+            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4))) {
1442
+                            return 0;
1443
+            }
1410 1444
             $week_year= 1;
1411 1445
             $calc_year--;
1412 1446
             $first_daynr-= ($days=self::calc_days_in_year($calc_year));
@@ -1415,8 +1449,7 @@  discard block
 block discarded – undo
1415 1449
 
1416 1450
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1417 1451
         $days= $daynr - ($first_daynr+ (7-$weekday));
1418
-      }
1419
-      else {
1452
+      } else {
1420 1453
         $days= $daynr - ($first_daynr - $weekday);
1421 1454
       }
1422 1455
 
Please login to merge, or discard this patch.
Spacing   +253 added lines, -253 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
  *	\brief      Class file to manage Dolibarr database access for a SQLite database
30 30
  */
31 31
 
32
-require_once DOL_BASE_PATH . '/core/db/DoliDB.class.php';
32
+require_once DOL_BASE_PATH.'/core/db/DoliDB.class.php';
33 33
 
34 34
 /**
35 35
  *	Class to manage Dolibarr database access for a SQLite database
@@ -37,17 +37,17 @@  discard block
 block discarded – undo
37 37
 class DoliDBSqlite3 extends DoliDB
38 38
 {
39 39
     //! Database type
40
-    public $type='sqlite3';
40
+    public $type = 'sqlite3';
41 41
     //! Database label
42
-    const LABEL='Sqlite3';
42
+    const LABEL = 'Sqlite3';
43 43
     //! Version min database
44
-    const VERSIONMIN='3.0.0';
44
+    const VERSIONMIN = '3.0.0';
45 45
 	/** @var SQLite3Result Resultset of last query */
46 46
 	private $_results;
47 47
 
48
-    const WEEK_MONDAY_FIRST=1;
48
+    const WEEK_MONDAY_FIRST = 1;
49 49
     const WEEK_YEAR = 2;
50
-    const WEEK_FIRST_WEEKDAY=4;
50
+    const WEEK_FIRST_WEEKDAY = 4;
51 51
 
52 52
 
53 53
     /**
@@ -61,19 +61,19 @@  discard block
 block discarded – undo
61 61
 	 *	@param	    string	$name		Nom de la database
62 62
 	 *	@param	    int		$port		Port of database server
63 63
      */
64
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
64
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
65 65
     {
66 66
         global $conf;
67 67
 
68 68
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
69
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
70
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
69
+        if (!empty($conf->db->character_set)) $this->forcecharset = $conf->db->character_set;
70
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
71 71
 
72
-        $this->database_user=$user;
73
-        $this->database_host=$host;
74
-        $this->database_port=$port;
72
+        $this->database_user = $user;
73
+        $this->database_host = $host;
74
+        $this->database_port = $port;
75 75
 
76
-        $this->transaction_opened=0;
76
+        $this->transaction_opened = 0;
77 77
 
78 78
         //print "Name DB: $host,$user,$pass,$name<br>";
79 79
 
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
             $this->database_selected = false;
125 125
             $this->database_name = '';
126 126
             //$this->error=sqlite_connect_error();
127
-            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error,LOG_ERR);
127
+            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error, LOG_ERR);
128 128
         }
129 129
 
130 130
         return $this->ok;
@@ -138,14 +138,14 @@  discard block
 block discarded – undo
138 138
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
139 139
      *  @return    string   		SQL request line converted
140 140
      */
141
-    static function convertSQLFromMysql($line,$type='ddl')
141
+    static function convertSQLFromMysql($line, $type = 'ddl')
142 142
     {
143 143
         // Removed empty line if this is a comment line for SVN tagging
144
-        if (preg_match('/^--\s\$Id/i',$line)) {
144
+        if (preg_match('/^--\s\$Id/i', $line)) {
145 145
             return '';
146 146
         }
147 147
         // Return line if this is a comment
148
-        if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
148
+        if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
149 149
         {
150 150
             return $line;
151 151
         }
@@ -153,114 +153,114 @@  discard block
 block discarded – undo
153 153
         {
154 154
             if ($type == 'auto')
155 155
             {
156
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
157
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
158
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
156
+              if (preg_match('/ALTER TABLE/i', $line)) $type = 'dml';
157
+              else if (preg_match('/CREATE TABLE/i', $line)) $type = 'dml';
158
+              else if (preg_match('/DROP TABLE/i', $line)) $type = 'dml';
159 159
             }
160 160
 
161 161
             if ($type == 'dml')
162 162
             {
163
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
163
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
164 164
 
165 165
                 // we are inside create table statement so lets process datatypes
166
-                if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
167
-                    $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
168
-                    $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
169
-                    $line=preg_replace('/,$/','',$line);
166
+                if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
167
+                    $line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
168
+                    $line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
169
+                    $line = preg_replace('/,$/', '', $line);
170 170
                 }
171 171
 
172 172
                 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
173
-                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
174
-                    $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 integer PRIMARY KEY AUTOINCREMENT',$line);
173
+                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
174
+                    $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 integer PRIMARY KEY AUTOINCREMENT', $line);
175 175
                     //$line = "-- ".$line." replaced by --\n".$newline;
176
-                    $line=$newline;
176
+                    $line = $newline;
177 177
                 }
178 178
 
179 179
                 // tinyint type conversion
180
-                $line=str_replace('tinyint','smallint',$line);
180
+                $line = str_replace('tinyint', 'smallint', $line);
181 181
 
182 182
                 // nuke unsigned
183
-                $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
183
+                $line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
184 184
 
185 185
                 // blob -> text
186
-                $line=preg_replace('/\w*blob/i','text',$line);
186
+                $line = preg_replace('/\w*blob/i', 'text', $line);
187 187
 
188 188
                 // tinytext/mediumtext -> text
189
-                $line=preg_replace('/tinytext/i','text',$line);
190
-                $line=preg_replace('/mediumtext/i','text',$line);
189
+                $line = preg_replace('/tinytext/i', 'text', $line);
190
+                $line = preg_replace('/mediumtext/i', 'text', $line);
191 191
 
192 192
                 // change not null datetime field to null valid ones
193 193
                 // (to support remapping of "zero time" to null
194
-                $line=preg_replace('/datetime not null/i','datetime',$line);
195
-                $line=preg_replace('/datetime/i','timestamp',$line);
194
+                $line = preg_replace('/datetime not null/i', 'datetime', $line);
195
+                $line = preg_replace('/datetime/i', 'timestamp', $line);
196 196
 
197 197
                 // double -> numeric
198
-                $line=preg_replace('/^double/i','numeric',$line);
199
-                $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
198
+                $line = preg_replace('/^double/i', 'numeric', $line);
199
+                $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
200 200
                 // float -> numeric
201
-                $line=preg_replace('/^float/i','numeric',$line);
202
-                $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
201
+                $line = preg_replace('/^float/i', 'numeric', $line);
202
+                $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
203 203
 
204 204
                 // unique index(field1,field2)
205
-                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
205
+                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
206 206
                 {
207
-                    $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
207
+                    $line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
208 208
                 }
209 209
 
210 210
                 // We remove end of requests "AFTER fieldxxx"
211
-                $line=preg_replace('/AFTER [a-z0-9_]+/i','',$line);
211
+                $line = preg_replace('/AFTER [a-z0-9_]+/i', '', $line);
212 212
 
213 213
                 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
214
-                $line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line);
214
+                $line = preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i', 'DROP INDEX', $line);
215 215
 
216 216
                 // Translate order to rename fields
217
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
217
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
218 218
                 {
219 219
                     $line = "-- ".$line." replaced by --\n";
220
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
220
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
221 221
                 }
222 222
 
223 223
                 // Translate order to modify field format
224
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
224
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
225 225
                 {
226 226
                     $line = "-- ".$line." replaced by --\n";
227
-                    $newreg3=$reg[3];
228
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
229
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
230
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
231
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
232
-                    $newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3);
233
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
227
+                    $newreg3 = $reg[3];
228
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
229
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
230
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
231
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
232
+                    $newreg3 = preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i', '', $newreg3);
233
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
234 234
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
235 235
                 }
236 236
 
237 237
                 // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
238 238
                 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
239
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
239
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
240 240
                 {
241 241
                     $line = "-- ".$line." replaced by --\n";
242
-                    $line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
242
+                    $line .= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
243 243
                 }
244 244
 
245 245
                 // Translate order to drop foreign keys
246 246
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
247
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
247
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
248 248
                 {
249 249
                     $line = "-- ".$line." replaced by --\n";
250
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
250
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
251 251
                 }
252 252
 
253 253
                 // alter table add [unique] [index] (field1, field2 ...)
254 254
                 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
255
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
255
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
256 256
                 {
257
-                    $fieldlist=$reg[4];
258
-                    $idxname=$reg[3];
259
-                    $tablename=$reg[1];
257
+                    $fieldlist = $reg[4];
258
+                    $idxname = $reg[3];
259
+                    $tablename = $reg[1];
260 260
                     $line = "-- ".$line." replaced by --\n";
261
-                    $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
261
+                    $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
262 262
                 }
263
-                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)) {
263
+                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)) {
264 264
                     // Pour l'instant les contraintes ne sont pas créées
265 265
                     dol_syslog(get_class().'::query line emptied');
266 266
                     $line = 'SELECT 0;';
@@ -273,24 +273,24 @@  discard block
 block discarded – undo
273 273
 
274 274
             // Delete using criteria on other table must not declare twice the deleted table
275 275
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
276
-            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
276
+            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
277 277
             {
278 278
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
279 279
                 {
280
-                    $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
280
+                    $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
281 281
                 }
282 282
             }
283 283
 
284 284
             // Remove () in the tables in FROM if one table
285
-            $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
285
+            $line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
286 286
             //print $line."\n";
287 287
 
288 288
             // Remove () in the tables in FROM if two table
289
-            $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);
289
+            $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);
290 290
             //print $line."\n";
291 291
 
292 292
             // Remove () in the tables in FROM if two table
293
-            $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);
293
+            $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);
294 294
             //print $line."\n";
295 295
 
296 296
             //print "type=".$type." newline=".$line."<br>\n";
@@ -327,14 +327,14 @@  discard block
 block discarded – undo
327 327
 	 *	@return		SQLite3				Database access handler
328 328
 	 *	@see		close
329 329
      */
330
-    function connect($host, $login, $passwd, $name, $port=0)
330
+    function connect($host, $login, $passwd, $name, $port = 0)
331 331
     {
332 332
         global $main_data_dir;
333 333
 
334
-        dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
334
+        dol_syslog(get_class($this)."::connect name=".$name, LOG_DEBUG);
335 335
 
336
-        $dir=$main_data_dir;
337
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
336
+        $dir = $main_data_dir;
337
+        if (empty($dir)) $dir = DOL_DATA_ROOT;
338 338
         // With sqlite, port must be in connect parameters
339 339
         //if (! $newport) $newport=3306;
340 340
         $database_name = $dir.'/database_'.$name.'.sdb';
@@ -344,9 +344,9 @@  discard block
 block discarded – undo
344 344
 			$this->db = new SQLite3($database_name);
345 345
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
346 346
         }
347
-        catch(Exception $e)
347
+        catch (Exception $e)
348 348
         {
349
-            $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
349
+            $this->error = self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
350 350
             return '';
351 351
         }
352 352
 
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
      */
363 363
     function getVersion()
364 364
     {
365
-    	$tmp=$this->db->version();
365
+    	$tmp = $this->db->version();
366 366
         return $tmp['versionString'];
367 367
     }
368 368
 
@@ -387,10 +387,10 @@  discard block
 block discarded – undo
387 387
     {
388 388
         if ($this->db)
389 389
         {
390
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
391
-            $this->connected=false;
390
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
391
+            $this->connected = false;
392 392
             $this->db->close();
393
-            unset($this->db);    // Clean this->db
393
+            unset($this->db); // Clean this->db
394 394
             return true;
395 395
         }
396 396
         return false;
@@ -405,14 +405,14 @@  discard block
 block discarded – undo
405 405
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
406 406
      *	@return	SQLite3Result			Resultset of answer
407 407
      */
408
-    function query($query,$usesavepoint=0,$type='auto')
408
+    function query($query, $usesavepoint = 0, $type = 'auto')
409 409
     {
410
-        $ret=null;
410
+        $ret = null;
411 411
         $query = trim($query);
412 412
         $this->error = 0;
413 413
 
414 414
         // Convert MySQL syntax to SQLite syntax
415
-        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)) {
415
+        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)) {
416 416
             // Ajout d'une clef étrangère à la table
417 417
             // procédure de remplacement de la table pour ajouter la contrainte
418 418
             // Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
@@ -420,19 +420,19 @@  discard block
 block discarded – undo
420 420
             $foreignFields = $reg[5];
421 421
             $foreignTable = $reg[4];
422 422
             $localfields = $reg[3];
423
-            $constraintname=trim($reg[2]);
424
-            $tablename=trim($reg[1]);
423
+            $constraintname = trim($reg[2]);
424
+            $tablename = trim($reg[1]);
425 425
 
426
-            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='" . $tablename . "'");
426
+            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='".$tablename."'");
427 427
 
428 428
             // 1- Renommer la table avec un nom temporaire
429
-            $this->query('ALTER TABLE ' . $tablename . ' RENAME TO tmp_' . $tablename);
429
+            $this->query('ALTER TABLE '.$tablename.' RENAME TO tmp_'.$tablename);
430 430
 
431 431
             // 2- Recréer la table avec la contrainte ajoutée
432 432
 
433 433
             // on bricole la requete pour ajouter la contrainte
434 434
             $descTable = substr($descTable, 0, strlen($descTable) - 1);
435
-            $descTable .= ", CONSTRAINT " . $constraintname . " FOREIGN KEY (" . $localfields . ") REFERENCES " .$foreignTable . "(" . $foreignFields . ")";
435
+            $descTable .= ", CONSTRAINT ".$constraintname." FOREIGN KEY (".$localfields.") REFERENCES ".$foreignTable."(".$foreignFields.")";
436 436
 
437 437
             // fermeture de l'instruction
438 438
             $descTable .= ')';
@@ -441,15 +441,15 @@  discard block
 block discarded – undo
441 441
             $this->query($descTable);
442 442
 
443 443
             // 3- Transférer les données
444
-            $this->query('INSERT INTO ' . $tablename . ' SELECT * FROM tmp_' . $tablename);
444
+            $this->query('INSERT INTO '.$tablename.' SELECT * FROM tmp_'.$tablename);
445 445
 
446 446
             // 4- Supprimer la table temporaire
447
-            $this->query('DROP TABLE tmp_' . $tablename);
447
+            $this->query('DROP TABLE tmp_'.$tablename);
448 448
 
449 449
             // dummy statement
450
-            $query="SELECT 0";
450
+            $query = "SELECT 0";
451 451
         } else {
452
-            $query=$this->convertSQLFromMysql($query,$type);
452
+            $query = $this->convertSQLFromMysql($query, $type);
453 453
         }
454 454
         //print "After convertSQLFromMysql:\n".$query."<br>\n";
455 455
 
@@ -458,20 +458,20 @@  discard block
 block discarded – undo
458 458
         // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
459 459
         try {
460 460
             //$ret = $this->db->exec($query);
461
-            $ret = $this->db->query($query);        // $ret is a Sqlite3Result
461
+            $ret = $this->db->query($query); // $ret is a Sqlite3Result
462 462
             if ($ret) {
463 463
                 $ret->queryString = $query;
464 464
             }
465 465
         }
466
-        catch(Exception $e)
466
+        catch (Exception $e)
467 467
         {
468
-            $this->error=$this->db->lastErrorMsg();
468
+            $this->error = $this->db->lastErrorMsg();
469 469
         }
470 470
 
471
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
471
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
472 472
         {
473 473
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
474
-            if (! is_object($ret) || $this->error)
474
+            if (!is_object($ret) || $this->error)
475 475
             {
476 476
                 $this->lastqueryerror = $query;
477 477
                 $this->lasterror = $this->error();
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
 
482 482
                 $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
483 483
 
484
-                if (preg_match('/[0-9]/',$this->lasterrno)) {
484
+                if (preg_match('/[0-9]/', $this->lasterrno)) {
485 485
                     $errormsg .= ' ('.$this->lasterrno.')';
486 486
                 }
487 487
 
488 488
                 dol_syslog($errormsg, LOG_ERR);
489 489
             }
490
-            $this->lastquery=$query;
490
+            $this->lastquery = $query;
491 491
             $this->_results = $ret;
492 492
         }
493 493
 
@@ -505,7 +505,7 @@  discard block
 block discarded – undo
505 505
     {
506 506
         // phpcs:enable
507 507
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
508
-        if (! is_object($resultset)) { $resultset=$this->_results; }
508
+        if (!is_object($resultset)) { $resultset = $this->_results; }
509 509
         //return $resultset->fetch(PDO::FETCH_OBJ);
510 510
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
511 511
         if ($ret) {
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
     {
527 527
         // phpcs:enable
528 528
         // If resultset not provided, we take the last used by connexion
529
-        if (! is_object($resultset)) { $resultset=$this->_results; }
529
+        if (!is_object($resultset)) { $resultset = $this->_results; }
530 530
         //return $resultset->fetch(PDO::FETCH_ASSOC);
531 531
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
532 532
 	    return $ret;
@@ -543,9 +543,9 @@  discard block
 block discarded – undo
543 543
     {
544 544
         // phpcs:enable
545 545
         // If resultset not provided, we take the last used by connexion
546
-        if (! is_bool($resultset))
546
+        if (!is_bool($resultset))
547 547
         {
548
-            if (! is_object($resultset)) { $resultset=$this->_results; }
548
+            if (!is_object($resultset)) { $resultset = $this->_results; }
549 549
             return $resultset->fetchArray(SQLITE3_NUM);
550 550
         }
551 551
         else
@@ -569,9 +569,9 @@  discard block
 block discarded – undo
569 569
         // FIXME: SQLite3Result does not have a queryString member
570 570
 
571 571
         // If resultset not provided, we take the last used by connexion
572
-        if (! is_object($resultset)) { $resultset=$this->_results; }
572
+        if (!is_object($resultset)) { $resultset = $this->_results; }
573 573
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
574
-            return $this->db->querySingle("SELECT count(*) FROM (" . $resultset->queryString . ") q");
574
+            return $this->db->querySingle("SELECT count(*) FROM (".$resultset->queryString.") q");
575 575
         }
576 576
         return 0;
577 577
     }
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
         // FIXME: SQLite3Result does not have a queryString member
591 591
 
592 592
         // If resultset not provided, we take the last used by connexion
593
-        if (! is_object($resultset)) { $resultset=$this->_results; }
593
+        if (!is_object($resultset)) { $resultset = $this->_results; }
594 594
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
595 595
             return $this->num_rows($resultset);
596 596
         }
@@ -606,10 +606,10 @@  discard block
 block discarded – undo
606 606
 	 *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
607 607
 	 *	@return	void
608 608
      */
609
-    function free($resultset=null)
609
+    function free($resultset = null)
610 610
     {
611 611
         // If resultset not provided, we take the last used by connexion
612
-        if (! is_object($resultset)) { $resultset=$this->_results; }
612
+        if (!is_object($resultset)) { $resultset = $this->_results; }
613 613
         // Si resultset en est un, on libere la memoire
614 614
         if ($resultset && is_object($resultset)) $resultset->finalize();
615 615
     }
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
      */
633 633
     function errno()
634 634
     {
635
-        if (! $this->connected) {
635
+        if (!$this->connected) {
636 636
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
637 637
             return 'DB_ERROR_FAILED_TO_CONNECT';
638 638
         }
@@ -670,23 +670,23 @@  discard block
 block discarded – undo
670 670
             {
671 671
                 return $errorcode_map[$this->db->errorCode()];
672 672
             }*/
673
-            $errno=$this->db->lastErrorCode();
674
-			if ($errno=='HY000' || $errno == 0)
673
+            $errno = $this->db->lastErrorCode();
674
+			if ($errno == 'HY000' || $errno == 0)
675 675
             {
676
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
677
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
678
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
676
+                if (preg_match('/table.*already exists/i', $this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
677
+                elseif (preg_match('/index.*already exists/i', $this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
678
+                elseif (preg_match('/syntax error/i', $this->error))          return 'DB_ERROR_SYNTAX';
679 679
             }
680
-            if ($errno=='23000')
680
+            if ($errno == '23000')
681 681
             {
682
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
683
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
682
+                if (preg_match('/column.* not unique/i', $this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
683
+                elseif (preg_match('/PRIMARY KEY must be unique/i', $this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
684 684
             }
685 685
             if ($errno > 1) {
686 686
                 // TODO Voir la liste des messages d'erreur
687 687
             }
688 688
 
689
-            return ($errno?'DB_ERROR_'.$errno:'0');
689
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
690 690
         }
691 691
     }
692 692
 
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
      */
698 698
     function error()
699 699
     {
700
-        if (! $this->connected) {
700
+        if (!$this->connected) {
701 701
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
702 702
             return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
703 703
         }
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 	 * @param	string	$fieldid	Field name
715 715
 	 * @return  int     			Id of row
716 716
      */
717
-    function last_insert_id($tab,$fieldid='rowid')
717
+    function last_insert_id($tab, $fieldid = 'rowid')
718 718
     {
719 719
         // phpcs:enable
720 720
         return $this->db->lastInsertRowId();
@@ -728,17 +728,17 @@  discard block
 block discarded – undo
728 728
      *  @param	int		$withQuotes     Return string with quotes
729 729
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
730 730
      */
731
-    function encrypt($fieldorvalue, $withQuotes=0)
731
+    function encrypt($fieldorvalue, $withQuotes = 0)
732 732
     {
733 733
         global $conf;
734 734
 
735 735
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
736
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
736
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
737 737
 
738 738
         //Encryption key
739
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
739
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
740 740
 
741
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
741
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
742 742
 
743 743
         if ($cryptType && !empty($cryptKey))
744 744
         {
@@ -766,10 +766,10 @@  discard block
 block discarded – undo
766 766
         global $conf;
767 767
 
768 768
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
769
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
769
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
770 770
 
771 771
         //Encryption key
772
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
772
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
773 773
 
774 774
         $return = $value;
775 775
 
@@ -814,24 +814,24 @@  discard block
 block discarded – undo
814 814
 	 * 	@param	string	$owner			Username of database owner
815 815
 	 * 	@return	SQLite3Result   		resource defined if OK, null if KO
816 816
      */
817
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
817
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
818 818
     {
819 819
         // phpcs:enable
820
-        if (empty($charset))   $charset=$this->forcecharset;
821
-        if (empty($collation)) $collation=$this->forcecollate;
820
+        if (empty($charset))   $charset = $this->forcecharset;
821
+        if (empty($collation)) $collation = $this->forcecollate;
822 822
 
823 823
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
824 824
         $sql = 'CREATE DATABASE '.$database;
825
-        $sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
825
+        $sql .= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
826 826
 
827
-        dol_syslog($sql,LOG_DEBUG);
828
-        $ret=$this->query($sql);
829
-        if (! $ret)
827
+        dol_syslog($sql, LOG_DEBUG);
828
+        $ret = $this->query($sql);
829
+        if (!$ret)
830 830
         {
831 831
             // We try again for compatibility with Mysql < 4.1.1
832 832
             $sql = 'CREATE DATABASE '.$database;
833
-            $ret=$this->query($sql);
834
-            dol_syslog($sql,LOG_DEBUG);
833
+            $ret = $this->query($sql);
834
+            dol_syslog($sql, LOG_DEBUG);
835 835
         }
836 836
         return $ret;
837 837
     }
@@ -844,19 +844,19 @@  discard block
 block discarded – undo
844 844
 	 *  @param	string		$table		Name of table filter ('xxx%')
845 845
 	 *  @return	array					List of tables in an array
846 846
      */
847
-    function DDLListTables($database, $table='')
847
+    function DDLListTables($database, $table = '')
848 848
     {
849 849
         // phpcs:enable
850
-        $listtables=array();
850
+        $listtables = array();
851 851
 
852 852
         $like = '';
853 853
         if ($table) $like = "LIKE '".$table."'";
854
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
854
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
855 855
         //print $sql;
856 856
         $result = $this->query($sql);
857 857
         if ($result)
858 858
         {
859
-            while($row = $this->fetch_row($result))
859
+            while ($row = $this->fetch_row($result))
860 860
             {
861 861
                 $listtables[] = $row[0];
862 862
             }
@@ -875,15 +875,15 @@  discard block
 block discarded – undo
875 875
     function DDLInfoTable($table)
876 876
     {
877 877
         // phpcs:enable
878
-        $infotables=array();
878
+        $infotables = array();
879 879
 
880
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
880
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
881 881
 
882
-        dol_syslog($sql,LOG_DEBUG);
882
+        dol_syslog($sql, LOG_DEBUG);
883 883
         $result = $this->query($sql);
884 884
         if ($result)
885 885
         {
886
-            while($row = $this->fetch_row($result))
886
+            while ($row = $this->fetch_row($result))
887 887
             {
888 888
                 $infotables[] = $row;
889 889
             }
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
905 905
 	 *	@return	    int						<0 if KO, >=0 if OK
906 906
      */
907
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
907
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
908 908
     {
909 909
         // phpcs:enable
910 910
         // FIXME: $fulltext_keys parameter is unused
@@ -912,61 +912,61 @@  discard block
 block discarded – undo
912 912
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
913 913
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
914 914
         $sql = "create table ".$table."(";
915
-        $i=0;
916
-        foreach($fields as $field_name => $field_desc)
915
+        $i = 0;
916
+        foreach ($fields as $field_name => $field_desc)
917 917
         {
918 918
             $sqlfields[$i] = $field_name." ";
919 919
             $sqlfields[$i]  .= $field_desc['type'];
920
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
920
+            if (preg_match("/^[^\s]/i", $field_desc['value']))
921 921
             $sqlfields[$i]  .= "(".$field_desc['value'].")";
922
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
922
+            else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
923 923
             $sqlfields[$i]  .= " ".$field_desc['attribute'];
924
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
924
+            else if (preg_match("/^[^\s]/i", $field_desc['default']))
925 925
             {
926
-                if(preg_match("/null/i",$field_desc['default']))
926
+                if (preg_match("/null/i", $field_desc['default']))
927 927
                 $sqlfields[$i]  .= " default ".$field_desc['default'];
928 928
                 else
929 929
                 $sqlfields[$i]  .= " default '".$field_desc['default']."'";
930 930
             }
931
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
931
+            else if (preg_match("/^[^\s]/i", $field_desc['null']))
932 932
             $sqlfields[$i]  .= " ".$field_desc['null'];
933 933
 
934
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
934
+            else if (preg_match("/^[^\s]/i", $field_desc['extra']))
935 935
             $sqlfields[$i]  .= " ".$field_desc['extra'];
936 936
             $i++;
937 937
         }
938
-        if($primary_key != "")
938
+        if ($primary_key != "")
939 939
         $pk = "primary key(".$primary_key.")";
940 940
 
941
-        if(is_array($unique_keys))
941
+        if (is_array($unique_keys))
942 942
         {
943 943
             $i = 0;
944
-            foreach($unique_keys as $key => $value)
944
+            foreach ($unique_keys as $key => $value)
945 945
             {
946 946
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
947 947
                 $i++;
948 948
             }
949 949
         }
950
-        if(is_array($keys))
950
+        if (is_array($keys))
951 951
         {
952 952
             $i = 0;
953
-            foreach($keys as $key => $value)
953
+            foreach ($keys as $key => $value)
954 954
             {
955 955
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
956 956
                 $i++;
957 957
             }
958 958
         }
959
-        $sql .= implode(',',$sqlfields);
960
-        if($primary_key != "")
959
+        $sql .= implode(',', $sqlfields);
960
+        if ($primary_key != "")
961 961
         $sql .= ",".$pk;
962
-        if(is_array($unique_keys))
963
-        $sql .= ",".implode(',',$sqluq);
964
-        if(is_array($keys))
965
-        $sql .= ",".implode(',',$sqlk);
966
-        $sql .=") type=".$type;
967
-
968
-        dol_syslog($sql,LOG_DEBUG);
969
-        if(! $this -> query($sql))
962
+        if (is_array($unique_keys))
963
+        $sql .= ",".implode(',', $sqluq);
964
+        if (is_array($keys))
965
+        $sql .= ",".implode(',', $sqlk);
966
+        $sql .= ") type=".$type;
967
+
968
+        dol_syslog($sql, LOG_DEBUG);
969
+        if (!$this -> query($sql))
970 970
             return -1;
971 971
         return 1;
972 972
     }
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
         // phpcs:enable
984 984
     	$sql = "DROP TABLE ".$table;
985 985
 
986
-    	if (! $this->query($sql))
986
+    	if (!$this->query($sql))
987 987
     		return -1;
988 988
     	else
989 989
     		return 1;
@@ -997,12 +997,12 @@  discard block
 block discarded – undo
997 997
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
998 998
 	 *	@return	SQLite3Result		Resource
999 999
      */
1000
-    function DDLDescTable($table,$field="")
1000
+    function DDLDescTable($table, $field = "")
1001 1001
     {
1002 1002
         // phpcs:enable
1003
-        $sql="DESC ".$table." ".$field;
1003
+        $sql = "DESC ".$table." ".$field;
1004 1004
 
1005
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
1005
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
1006 1006
         $this->_results = $this->query($sql);
1007 1007
         return $this->_results;
1008 1008
     }
@@ -1017,35 +1017,35 @@  discard block
 block discarded – undo
1017 1017
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1018 1018
 	 *	@return	int							<0 if KO, >0 if OK
1019 1019
      */
1020
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
1020
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1021 1021
     {
1022 1022
         // phpcs:enable
1023 1023
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1024 1024
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1025
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1026
-        $sql.= $field_desc['type'];
1027
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
1028
-        if (! in_array($field_desc['type'],array('date','datetime')))
1025
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1026
+        $sql .= $field_desc['type'];
1027
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
1028
+        if (!in_array($field_desc['type'], array('date', 'datetime')))
1029 1029
         {
1030
-            $sql.= "(".$field_desc['value'].")";
1030
+            $sql .= "(".$field_desc['value'].")";
1031 1031
         }
1032
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1033
-        $sql.= " ".$field_desc['attribute'];
1034
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1035
-        $sql.= " ".$field_desc['null'];
1036
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
1032
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1033
+        $sql .= " ".$field_desc['attribute'];
1034
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
1035
+        $sql .= " ".$field_desc['null'];
1036
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
1037 1037
         {
1038
-            if(preg_match("/null/i",$field_desc['default']))
1039
-            $sql.= " default ".$field_desc['default'];
1038
+            if (preg_match("/null/i", $field_desc['default']))
1039
+            $sql .= " default ".$field_desc['default'];
1040 1040
             else
1041
-            $sql.= " default '".$field_desc['default']."'";
1041
+            $sql .= " default '".$field_desc['default']."'";
1042 1042
         }
1043
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1044
-        $sql.= " ".$field_desc['extra'];
1045
-        $sql.= " ".$field_position;
1043
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
1044
+        $sql .= " ".$field_desc['extra'];
1045
+        $sql .= " ".$field_position;
1046 1046
 
1047
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1048
-        if(! $this->query($sql))
1047
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1048
+        if (!$this->query($sql))
1049 1049
         {
1050 1050
             return -1;
1051 1051
         }
@@ -1061,17 +1061,17 @@  discard block
 block discarded – undo
1061 1061
 	 *	@param	string	$field_desc 		Array with description of field format
1062 1062
 	 *	@return	int							<0 if KO, >0 if OK
1063 1063
      */
1064
-    function DDLUpdateField($table,$field_name,$field_desc)
1064
+    function DDLUpdateField($table, $field_name, $field_desc)
1065 1065
     {
1066 1066
         // phpcs:enable
1067 1067
         $sql = "ALTER TABLE ".$table;
1068 1068
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1069 1069
         if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1070
-            $sql.="(".$field_desc['value'].")";
1070
+            $sql .= "(".$field_desc['value'].")";
1071 1071
         }
1072 1072
 
1073
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1074
-        if (! $this->query($sql))
1073
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1074
+        if (!$this->query($sql))
1075 1075
             return -1;
1076 1076
         return 1;
1077 1077
     }
@@ -1084,14 +1084,14 @@  discard block
 block discarded – undo
1084 1084
 	 *	@param	string	$field_name 	Name of field to drop
1085 1085
 	 *	@return	int						<0 if KO, >0 if OK
1086 1086
      */
1087
-    function DDLDropField($table,$field_name)
1087
+    function DDLDropField($table, $field_name)
1088 1088
     {
1089 1089
         // phpcs:enable
1090
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1091
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1092
-        if (! $this->query($sql))
1090
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1091
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
1092
+        if (!$this->query($sql))
1093 1093
         {
1094
-            $this->error=$this->lasterror();
1094
+            $this->error = $this->lasterror();
1095 1095
             return -1;
1096 1096
         }
1097 1097
         return 1;
@@ -1108,38 +1108,38 @@  discard block
 block discarded – undo
1108 1108
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1109 1109
 	 *	@return	int									<0 if KO, >=0 if OK
1110 1110
      */
1111
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1111
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1112 1112
     {
1113 1113
         // phpcs:enable
1114 1114
         $sql = "INSERT INTO user ";
1115
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1116
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1117
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1115
+        $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1116
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1117
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1118 1118
 
1119
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1120
-        $resql=$this->query($sql);
1121
-        if (! $resql)
1119
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1120
+        $resql = $this->query($sql);
1121
+        if (!$resql)
1122 1122
         {
1123 1123
             return -1;
1124 1124
         }
1125 1125
 
1126 1126
         $sql = "INSERT INTO db ";
1127
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1128
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1129
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1127
+        $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1128
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1129
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1130 1130
 
1131 1131
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1132
-        $resql=$this->query($sql);
1133
-        if (! $resql)
1132
+        $resql = $this->query($sql);
1133
+        if (!$resql)
1134 1134
         {
1135 1135
             return -1;
1136 1136
         }
1137 1137
 
1138
-        $sql="FLUSH Privileges";
1138
+        $sql = "FLUSH Privileges";
1139 1139
 
1140 1140
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1141
-        $resql=$this->query($sql);
1142
-        if (! $resql)
1141
+        $resql = $this->query($sql);
1142
+        if (!$resql)
1143 1143
         {
1144 1144
             return -1;
1145 1145
         }
@@ -1164,7 +1164,7 @@  discard block
 block discarded – undo
1164 1164
     function getListOfCharacterSet()
1165 1165
     {
1166 1166
         $liste = array();
1167
-        $i=0;
1167
+        $i = 0;
1168 1168
         $liste[$i]['charset'] = 'UTF-8';
1169 1169
         $liste[$i]['description'] = 'UTF-8';
1170 1170
         return $liste;
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
     function getListOfCollation()
1189 1189
     {
1190 1190
         $liste = array();
1191
-        $i=0;
1191
+        $i = 0;
1192 1192
         $liste[$i]['charset'] = 'UTF-8';
1193 1193
         $liste[$i]['description'] = 'UTF-8';
1194 1194
         return $liste;
@@ -1202,14 +1202,14 @@  discard block
 block discarded – undo
1202 1202
     function getPathOfDump()
1203 1203
     {
1204 1204
 	    // FIXME: not for SQLite
1205
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1205
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1206 1206
 
1207
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1207
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1208 1208
         if ($resql)
1209 1209
         {
1210
-            $liste=$this->fetch_array($resql);
1211
-            $basedir=$liste['Value'];
1212
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1210
+            $liste = $this->fetch_array($resql);
1211
+            $basedir = $liste['Value'];
1212
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1213 1213
         }
1214 1214
         return $fullpathofdump;
1215 1215
     }
@@ -1222,14 +1222,14 @@  discard block
 block discarded – undo
1222 1222
     function getPathOfRestore()
1223 1223
     {
1224 1224
 	    // FIXME: not for SQLite
1225
-        $fullpathofimport='/pathtomysql/mysql';
1225
+        $fullpathofimport = '/pathtomysql/mysql';
1226 1226
 
1227
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1227
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1228 1228
         if ($resql)
1229 1229
         {
1230
-            $liste=$this->fetch_array($resql);
1231
-            $basedir=$liste['Value'];
1232
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1230
+            $liste = $this->fetch_array($resql);
1231
+            $basedir = $liste['Value'];
1232
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1233 1233
         }
1234 1234
         return $fullpathofimport;
1235 1235
     }
@@ -1240,18 +1240,18 @@  discard block
 block discarded – undo
1240 1240
 	 * @param	string	$filter		Filter list on a particular value
1241 1241
 	 * @return	array				Array of key-values (key=>value)
1242 1242
      */
1243
-    function getServerParametersValues($filter='')
1243
+    function getServerParametersValues($filter = '')
1244 1244
     {
1245
-        $result=array();
1245
+        $result = array();
1246 1246
         static $pragmas;
1247
-        if (! isset($pragmas)) {
1247
+        if (!isset($pragmas)) {
1248 1248
             // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1249 1249
             // indépendante de la base de données.
1250 1250
             // cf. http://www.sqlite.org/pragma.html
1251 1251
             $pragmas = array(
1252 1252
                 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1253 1253
                 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1254
-				'compile_options', 'data_version',	/*'database_list',*/
1254
+				'compile_options', 'data_version', /*'database_list',*/
1255 1255
                 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1256 1256
                 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1257 1257
                 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
@@ -1266,9 +1266,9 @@  discard block
 block discarded – undo
1266 1266
         }
1267 1267
 
1268 1268
         // TODO prendre en compte le filtre
1269
-        foreach($pragmas as $var) {
1269
+        foreach ($pragmas as $var) {
1270 1270
             $sql = "PRAGMA $var";
1271
-            $resql=$this->query($sql);
1271
+            $resql = $this->query($sql);
1272 1272
             if ($resql)
1273 1273
             {
1274 1274
                 $obj = $this->fetch_row($resql);
@@ -1289,9 +1289,9 @@  discard block
 block discarded – undo
1289 1289
 	 * @param	string	$filter		Filter list on a particular value
1290 1290
 	 * @return  array				Array of key-values (key=>value)
1291 1291
      */
1292
-    function getServerStatusValues($filter='')
1292
+    function getServerStatusValues($filter = '')
1293 1293
     {
1294
-        $result=array();
1294
+        $result = array();
1295 1295
         /*
1296 1296
         $sql='SHOW STATUS';
1297 1297
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
@@ -1318,10 +1318,10 @@  discard block
 block discarded – undo
1318 1318
     {
1319 1319
         if ($this->db)
1320 1320
         {
1321
-        	$newname=preg_replace('/_/','',$name);
1322
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1321
+        	$newname = preg_replace('/_/', '', $name);
1322
+            $localname = __CLASS__.'::'.'db'.$newname;
1323 1323
             $reflectClass = new ReflectionClass(__CLASS__);
1324
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1324
+            $reflectFunction = $reflectClass->getMethod('db'.$newname);
1325 1325
             if ($arg_count < 0) {
1326 1326
                 $arg_count = $reflectFunction->getNumberOfParameters();
1327 1327
             }
@@ -1346,7 +1346,7 @@  discard block
 block discarded – undo
1346 1346
         // phpcs:enable
1347 1347
         $y = $year;
1348 1348
         if ($y == 0 && $month == 0) return 0;
1349
-        $num = (365* $y + 31 * ($month - 1) + $day);
1349
+        $num = (365 * $y + 31 * ($month - 1) + $day);
1350 1350
         if ($month <= 2) {
1351 1351
             $y--; }
1352 1352
         else {
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
     private static function calc_days_in_year($year)
1382 1382
     {
1383 1383
         // phpcs:enable
1384
-        return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1384
+        return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
1385 1385
     }
1386 1386
 
1387 1387
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -1398,41 +1398,41 @@  discard block
 block discarded – undo
1398 1398
     private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year)
1399 1399
     {
1400 1400
         // phpcs:enable
1401
-        $daynr=self::calc_daynr($year,$month,$day);
1402
-        $first_daynr=self::calc_daynr($year,1,1);
1403
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1404
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1405
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1401
+        $daynr = self::calc_daynr($year, $month, $day);
1402
+        $first_daynr = self::calc_daynr($year, 1, 1);
1403
+        $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1404
+        $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1405
+        $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1406 1406
 
1407
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1408
-        $calc_year=$year;
1407
+        $weekday = self::calc_weekday($first_daynr, !$monday_first);
1408
+        $calc_year = $year;
1409 1409
 
1410
-        if ($month == 1 && $day <= 7-$weekday)
1410
+        if ($month == 1 && $day <= 7 - $weekday)
1411 1411
         {
1412 1412
             if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1413 1413
                 return 0;
1414
-            $week_year= 1;
1414
+            $week_year = 1;
1415 1415
             $calc_year--;
1416
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1417
-            $weekday= ($weekday + 53*7- $days) % 7;
1416
+            $first_daynr -= ($days = self::calc_days_in_year($calc_year));
1417
+            $weekday = ($weekday + 53 * 7 - $days) % 7;
1418 1418
       }
1419 1419
 
1420 1420
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1421
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1421
+        $days = $daynr - ($first_daynr + (7 - $weekday));
1422 1422
       }
1423 1423
       else {
1424
-        $days= $daynr - ($first_daynr - $weekday);
1424
+        $days = $daynr - ($first_daynr - $weekday);
1425 1425
       }
1426 1426
 
1427
-      if ($week_year && $days >= 52*7)
1427
+      if ($week_year && $days >= 52 * 7)
1428 1428
       {
1429
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1429
+        $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
1430 1430
         if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1431 1431
         {
1432 1432
           $calc_year++;
1433 1433
           return 1;
1434 1434
         }
1435 1435
       }
1436
-      return floor($days/7+1);
1436
+      return floor($days / 7 + 1);
1437 1437
     }
1438 1438
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/get_info.php 3 patches
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -66,12 +66,12 @@  discard block
 block discarded – undo
66 66
 $appli=constant('DOL_APPLICATION_TITLE');
67 67
 if (! empty($conf->global->MAIN_APPLICATION_TITLE))
68 68
 {
69
-	$appli=$conf->global->MAIN_APPLICATION_TITLE;
70
-	if (preg_match('/\d\.\d/', $appli))
71
-	{
72
-		if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
73
-	}
74
-	else $appli.=" ".DOL_VERSION;
69
+    $appli=$conf->global->MAIN_APPLICATION_TITLE;
70
+    if (preg_match('/\d\.\d/', $appli))
71
+    {
72
+        if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
73
+    }
74
+    else $appli.=" ".DOL_VERSION;
75 75
 }
76 76
 else $appli.=" ".DOL_VERSION;
77 77
 
@@ -80,21 +80,21 @@  discard block
 block discarded – undo
80 80
 $logouttext='';
81 81
 if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
82 82
 {
83
-	//$logouthtmltext=$appli.'<br>';
84
-	if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
85
-	{
86
-		$logouthtmltext.=$langs->trans("Logout").'<br>';
87
-
88
-		$logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
89
-		//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
90
-		$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
91
-		$logouttext .='</a>';
92
-	}
93
-	else
94
-	{
95
-		$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
96
-		$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
97
-	}
83
+    //$logouthtmltext=$appli.'<br>';
84
+    if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
85
+    {
86
+        $logouthtmltext.=$langs->trans("Logout").'<br>';
87
+
88
+        $logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
89
+        //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
90
+        $logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
91
+        $logouttext .='</a>';
92
+    }
93
+    else
94
+    {
95
+        $logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
96
+        $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
97
+    }
98 98
 }
99 99
 
100 100
 print '<div class="login_block_getinfo">'."\n";
@@ -117,19 +117,19 @@  discard block
 block discarded – undo
117 117
 $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
118 118
 if (is_numeric($result))
119 119
 {
120
-	if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
121
-	else  $toprightmenu=$hookmanager->resPrint;						// replace
120
+    if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
121
+    else  $toprightmenu=$hookmanager->resPrint;						// replace
122 122
 }
123 123
 else $toprightmenu.=$result;	// For backward compatibility
124 124
 
125 125
 // Link to module builder
126 126
 if (! empty($conf->modulebuilder->enabled))
127 127
 {
128
-	$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
129
-	//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
130
-	$text.='<span class="fa fa-bug atoplogin"></span>';
131
-	$text.='</a>';
132
-	$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
128
+    $text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
129
+    //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
130
+    $text.='<span class="fa fa-bug atoplogin"></span>';
131
+    $text.='</a>';
132
+    $toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
133 133
 }
134 134
 
135 135
 // Link to print main content area
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -27,31 +27,31 @@  discard block
 block discarded – undo
27 27
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');		// Not disabled cause need to load personalized language
28 28
 //if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
29 29
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');		// Not disabled cause need to do translations
30
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
30
+if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
31
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
32 32
 //if (! defined('NOLOGIN')) define('NOLOGIN',1);					// Not disabled cause need to load personalized language
33
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU',1);
33
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', 1);
34 34
 
35 35
 require_once '../main.inc.php';
36 36
 
37
-if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09'));	// If language was forced on URL by the main.inc.php
37
+if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL by the main.inc.php
38 38
 
39 39
 $langs->load("main");
40 40
 
41
-$right=($langs->trans("DIRECTION")=='rtl'?'left':'right');
42
-$left=($langs->trans("DIRECTION")=='rtl'?'right':'left');
41
+$right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
42
+$left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
43 43
 
44 44
 
45 45
 /*
46 46
  * View
47 47
  */
48 48
 
49
-$title=$langs->trans("Info");
49
+$title = $langs->trans("Info");
50 50
 
51 51
 // URL http://mydolibarr/core/search_page?dol_use_jmobile=1 can be used for tests
52
-$head='<!-- Quick access -->'."\n";
53
-$arrayofjs=array();
54
-$arrayofcss=array();
52
+$head = '<!-- Quick access -->'."\n";
53
+$arrayofjs = array();
54
+$arrayofcss = array();
55 55
 top_htmlhead($head, $title, 0, 0, $arrayofjs, $arrayofcss);
56 56
 
57 57
 
@@ -60,39 +60,39 @@  discard block
 block discarded – undo
60 60
 print '<div style="padding: 20px;">';
61 61
 //print '<br>';
62 62
 
63
-$nbofsearch=0;
63
+$nbofsearch = 0;
64 64
 
65 65
 // Define link to login card
66
-$appli=constant('DOL_APPLICATION_TITLE');
67
-if (! empty($conf->global->MAIN_APPLICATION_TITLE))
66
+$appli = constant('DOL_APPLICATION_TITLE');
67
+if (!empty($conf->global->MAIN_APPLICATION_TITLE))
68 68
 {
69
-	$appli=$conf->global->MAIN_APPLICATION_TITLE;
69
+	$appli = $conf->global->MAIN_APPLICATION_TITLE;
70 70
 	if (preg_match('/\d\.\d/', $appli))
71 71
 	{
72
-		if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
72
+		if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
73 73
 	}
74
-	else $appli.=" ".DOL_VERSION;
74
+	else $appli .= " ".DOL_VERSION;
75 75
 }
76
-else $appli.=" ".DOL_VERSION;
76
+else $appli .= " ".DOL_VERSION;
77 77
 
78
-if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
78
+if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
79 79
 
80
-$logouttext='';
80
+$logouttext = '';
81 81
 if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
82 82
 {
83 83
 	//$logouthtmltext=$appli.'<br>';
84 84
 	if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
85 85
 	{
86
-		$logouthtmltext.=$langs->trans("Logout").'<br>';
86
+		$logouthtmltext .= $langs->trans("Logout").'<br>';
87 87
 
88
-		$logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
88
+		$logouttext .= '<a href="'.DOL_URL_ROOT.'/user/logout.php">';
89 89
 		//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
90
-		$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
91
-		$logouttext .='</a>';
90
+		$logouttext .= '<span class="fa fa-sign-out atoplogin"></span>';
91
+		$logouttext .= '</a>';
92 92
 	}
93 93
 	else
94 94
 	{
95
-		$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
95
+		$logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
96 96
 		$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
97 97
 	}
98 98
 }
@@ -100,36 +100,36 @@  discard block
 block discarded – undo
100 100
 print '<div class="login_block_getinfo">'."\n";
101 101
 
102 102
 // Add login user link
103
-$toprightmenu.='<div class="login_block_user">';
103
+$toprightmenu .= '<div class="login_block_user">';
104 104
 
105 105
 // Login name with photo and tooltip
106
-$mode=-1;
107
-$toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
108
-$toprightmenu.=$user->getNomUrl($mode, '', -1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
109
-$toprightmenu.='</div></div>';
106
+$mode = -1;
107
+$toprightmenu .= '<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
108
+$toprightmenu .= $user->getNomUrl($mode, '', -1, 0, 11, 0, ($user->firstname ? 'firstname' : -1), 'atoplogin');
109
+$toprightmenu .= '</div></div>';
110 110
 
111
-$toprightmenu.='</div>'."\n";
111
+$toprightmenu .= '</div>'."\n";
112 112
 
113
-$toprightmenu.='<div class="login_block_other">';
113
+$toprightmenu .= '<div class="login_block_other">';
114 114
 
115 115
 // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
116
-$parameters=array();
117
-$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
116
+$parameters = array();
117
+$result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
118 118
 if (is_numeric($result))
119 119
 {
120
-	if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
121
-	else  $toprightmenu=$hookmanager->resPrint;						// replace
120
+	if (empty($result)) $toprightmenu .= $hookmanager->resPrint; // add
121
+	else  $toprightmenu = $hookmanager->resPrint; // replace
122 122
 }
123
-else $toprightmenu.=$result;	// For backward compatibility
123
+else $toprightmenu .= $result; // For backward compatibility
124 124
 
125 125
 // Link to module builder
126
-if (! empty($conf->modulebuilder->enabled))
126
+if (!empty($conf->modulebuilder->enabled))
127 127
 {
128
-	$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
128
+	$text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
129 129
 	//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
130
-	$text.='<span class="fa fa-bug atoplogin"></span>';
131
-	$text.='</a>';
132
-	$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
130
+	$text .= '<span class="fa fa-bug atoplogin"></span>';
131
+	$text .= '</a>';
132
+	$toprightmenu .= @Form::textwithtooltip('', $langs->trans("ModuleBuilder"), 2, 1, $text, 'login_block_elem', 2);
133 133
 }
134 134
 
135 135
 // Link to print main content area
@@ -194,13 +194,13 @@  discard block
 block discarded – undo
194 194
 */
195 195
 
196 196
 // Logout link
197
-if (GETPOST('withlogout','int')) $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
197
+if (GETPOST('withlogout', 'int')) $toprightmenu .= @Form::textwithtooltip('', $logouthtmltext, 2, 1, $logouttext, 'login_block_elem', 2);
198 198
 
199
-$toprightmenu.='</div>';
199
+$toprightmenu .= '</div>';
200 200
 
201 201
 print $toprightmenu;
202 202
 
203
-print "</div>\n";		// end div class="login_block"
203
+print "</div>\n"; // end div class="login_block"
204 204
 
205 205
 print '</div>';
206 206
 print '</body></html>'."\n";
Please login to merge, or discard this patch.
Braces   +39 added lines, -14 removed lines patch added patch discarded remove patch
@@ -27,14 +27,23 @@  discard block
 block discarded – undo
27 27
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');		// Not disabled cause need to load personalized language
28 28
 //if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
29 29
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');		// Not disabled cause need to do translations
30
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
30
+if (! defined('NOCSRFCHECK')) {
31
+    define('NOCSRFCHECK',1);
32
+}
33
+if (! defined('NOTOKENRENEWAL')) {
34
+    define('NOTOKENRENEWAL',1);
35
+}
32 36
 //if (! defined('NOLOGIN')) define('NOLOGIN',1);					// Not disabled cause need to load personalized language
33
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU',1);
37
+if (! defined('NOREQUIREMENU')) {
38
+    define('NOREQUIREMENU',1);
39
+}
34 40
 
35 41
 require_once '../main.inc.php';
36 42
 
37
-if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09'));	// If language was forced on URL by the main.inc.php
43
+if (GETPOST('lang', 'aZ09')) {
44
+    $langs->setDefaultLang(GETPOST('lang', 'aZ09'));
45
+}
46
+// If language was forced on URL by the main.inc.php
38 47
 
39 48
 $langs->load("main");
40 49
 
@@ -69,13 +78,20 @@  discard block
 block discarded – undo
69 78
 	$appli=$conf->global->MAIN_APPLICATION_TITLE;
70 79
 	if (preg_match('/\d\.\d/', $appli))
71 80
 	{
72
-		if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
81
+		if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
82
+		    $appli.=" (".DOL_VERSION.")";
83
+		}
84
+		// If new title contains a version that is different than core
85
+	} else {
86
+	    $appli.=" ".DOL_VERSION;
73 87
 	}
74
-	else $appli.=" ".DOL_VERSION;
88
+	} else {
89
+    $appli.=" ".DOL_VERSION;
75 90
 }
76
-else $appli.=" ".DOL_VERSION;
77 91
 
78
-if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
92
+if (! empty($conf->global->MAIN_FEATURES_LEVEL)) {
93
+    $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
94
+}
79 95
 
80 96
 $logouttext='';
81 97
 if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
@@ -89,8 +105,7 @@  discard block
 block discarded – undo
89 105
 		//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
90 106
 		$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
91 107
 		$logouttext .='</a>';
92
-	}
93
-	else
108
+	} else
94 109
 	{
95 110
 		$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
96 111
 		$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
@@ -117,10 +132,18 @@  discard block
 block discarded – undo
117 132
 $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
118 133
 if (is_numeric($result))
119 134
 {
120
-	if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
121
-	else  $toprightmenu=$hookmanager->resPrint;						// replace
135
+	if (empty($result)) {
136
+	    $toprightmenu.=$hookmanager->resPrint;
137
+	}
138
+	// add
139
+	else {
140
+	    $toprightmenu=$hookmanager->resPrint;
141
+	}
142
+	// replace
143
+} else {
144
+    $toprightmenu.=$result;
122 145
 }
123
-else $toprightmenu.=$result;	// For backward compatibility
146
+// For backward compatibility
124 147
 
125 148
 // Link to module builder
126 149
 if (! empty($conf->modulebuilder->enabled))
@@ -194,7 +217,9 @@  discard block
 block discarded – undo
194 217
 */
195 218
 
196 219
 // Logout link
197
-if (GETPOST('withlogout','int')) $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
220
+if (GETPOST('withlogout','int')) {
221
+    $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
222
+}
198 223
 
199 224
 $toprightmenu.='</div>';
200 225
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_builddoc.inc.php 3 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
     }
41 41
     else
42 42
     {
43
-   		// Reload to get all modified line records and be ready for hooks
43
+            // Reload to get all modified line records and be ready for hooks
44 44
         $ret = $object->fetch($id);
45 45
         $ret = $object->fetch_thirdparty();
46 46
         /*if (empty($object->id) || ! $object->id > 0)
@@ -50,10 +50,10 @@  discard block
 block discarded – undo
50 50
         }*/
51 51
 
52 52
         // Save last template used to generate document
53
-    	if (GETPOST('model','alpha'))
54
-    	{
55
-    	    $object->setDocModel($user, GETPOST('model','alpha'));
56
-    	}
53
+        if (GETPOST('model','alpha'))
54
+        {
55
+            $object->setDocModel($user, GETPOST('model','alpha'));
56
+        }
57 57
 
58 58
         // Special case to force bank account
59 59
         //if (property_exists($object, 'fk_bank'))
@@ -91,17 +91,17 @@  discard block
 block discarded – undo
91 91
         }
92 92
         else
93 93
         {
94
-        	if (empty($donotredirect))	// This is set when include is done by bulk action "Bill Orders"
95
-        	{
96
-	            setEventMessages($langs->trans("FileGenerated"), null);
94
+            if (empty($donotredirect))	// This is set when include is done by bulk action "Bill Orders"
95
+            {
96
+                setEventMessages($langs->trans("FileGenerated"), null);
97 97
 
98
-	            $urltoredirect = $_SERVER['REQUEST_URI'];
99
-	            $urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
100
-	            $urltoredirect = preg_replace('/action=builddoc&?/', '', $urltoredirect);	// To avoid infinite loop
98
+                $urltoredirect = $_SERVER['REQUEST_URI'];
99
+                $urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
100
+                $urltoredirect = preg_replace('/action=builddoc&?/', '', $urltoredirect);	// To avoid infinite loop
101 101
 
102
-	            header('Location: '.$urltoredirect.'#builddoc');
103
-	            exit;
104
-        	}
102
+                header('Location: '.$urltoredirect.'#builddoc');
103
+                exit;
104
+            }
105 105
         }
106 106
     }
107 107
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -34,9 +34,9 @@  discard block
 block discarded – undo
34 34
 if ($action == 'builddoc' && $permissioncreate)
35 35
 {
36 36
 
37
-    if (is_numeric(GETPOST('model','alpha')))
37
+    if (is_numeric(GETPOST('model', 'alpha')))
38 38
     {
39
-        $error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model"));
39
+        $error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model"));
40 40
     }
41 41
     else
42 42
     {
@@ -50,44 +50,44 @@  discard block
 block discarded – undo
50 50
         }*/
51 51
 
52 52
         // Save last template used to generate document
53
-    	if (GETPOST('model','alpha'))
53
+    	if (GETPOST('model', 'alpha'))
54 54
     	{
55
-    	    $object->setDocModel($user, GETPOST('model','alpha'));
55
+    	    $object->setDocModel($user, GETPOST('model', 'alpha'));
56 56
     	}
57 57
 
58 58
         // Special case to force bank account
59 59
         //if (property_exists($object, 'fk_bank'))
60 60
         //{
61
-            if (GETPOST('fk_bank','int')) { // this field may come from an external module
62
-                $object->fk_bank = GETPOST('fk_bank','int');
63
-            } else if (! empty($object->fk_account)) {
61
+            if (GETPOST('fk_bank', 'int')) { // this field may come from an external module
62
+                $object->fk_bank = GETPOST('fk_bank', 'int');
63
+            } else if (!empty($object->fk_account)) {
64 64
                 $object->fk_bank = $object->fk_account;
65 65
             }
66 66
         //}
67 67
 
68 68
         $outputlangs = $langs;
69
-        $newlang='';
69
+        $newlang = '';
70 70
 
71
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
72
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) $newlang=$object->thirdparty->default_lang;  // for proposal, order, invoice, ...
73
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang=$object->default_lang;                  // for thirdparty
74
-        if (! empty($newlang))
71
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
72
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) $newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ...
73
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang = $object->default_lang; // for thirdparty
74
+        if (!empty($newlang))
75 75
         {
76
-            $outputlangs = new Translate("",$conf);
76
+            $outputlangs = new Translate("", $conf);
77 77
             $outputlangs->setDefaultLang($newlang);
78 78
         }
79 79
 
80 80
         // To be sure vars is defined
81
-        if (empty($hidedetails)) $hidedetails=0;
82
-        if (empty($hidedesc)) $hidedesc=0;
83
-        if (empty($hideref)) $hideref=0;
84
-        if (empty($moreparams)) $moreparams=null;
81
+        if (empty($hidedetails)) $hidedetails = 0;
82
+        if (empty($hidedesc)) $hidedesc = 0;
83
+        if (empty($hideref)) $hideref = 0;
84
+        if (empty($moreparams)) $moreparams = null;
85 85
 
86
-        $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
86
+        $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
87 87
         if ($result <= 0)
88 88
         {
89 89
             setEventMessages($object->error, $object->errors, 'errors');
90
-            $action='';
90
+            $action = '';
91 91
         }
92 92
         else
93 93
         {
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 
98 98
 	            $urltoredirect = $_SERVER['REQUEST_URI'];
99 99
 	            $urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
100
-	            $urltoredirect = preg_replace('/action=builddoc&?/', '', $urltoredirect);	// To avoid infinite loop
100
+	            $urltoredirect = preg_replace('/action=builddoc&?/', '', $urltoredirect); // To avoid infinite loop
101 101
 
102 102
 	            header('Location: '.$urltoredirect.'#builddoc');
103 103
 	            exit;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 {
112 112
     require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
113 113
 
114
-    if (empty($object->id) || ! $object->id > 0)
114
+    if (empty($object->id) || !$object->id > 0)
115 115
     {
116 116
         // Reload to get all modified line records and be ready for hooks
117 117
         $ret = $object->fetch($id);
@@ -119,9 +119,9 @@  discard block
 block discarded – undo
119 119
     }
120 120
 
121 121
     $langs->load("other");
122
-    $filetodelete=GETPOST('file','alpha');
123
-    $file =	$upload_dir	. '/' .	$filetodelete;
124
-    $ret=dol_delete_file($file,0,0,0,$object);
122
+    $filetodelete = GETPOST('file', 'alpha');
123
+    $file = $upload_dir.'/'.$filetodelete;
124
+    $ret = dol_delete_file($file, 0, 0, 0, $object);
125 125
     if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
126 126
     else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors');
127 127
 
Please login to merge, or discard this patch.
Braces   +33 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,8 +37,7 @@  discard block
 block discarded – undo
37 37
     if (is_numeric(GETPOST('model','alpha')))
38 38
     {
39 39
         $error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model"));
40
-    }
41
-    else
40
+    } else
42 41
     {
43 42
    		// Reload to get all modified line records and be ready for hooks
44 43
         $ret = $object->fetch($id);
@@ -68,9 +67,17 @@  discard block
 block discarded – undo
68 67
         $outputlangs = $langs;
69 68
         $newlang='';
70 69
 
71
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
72
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) $newlang=$object->thirdparty->default_lang;  // for proposal, order, invoice, ...
73
-        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang=$object->default_lang;                  // for thirdparty
70
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
71
+            $newlang=GETPOST('lang_id','aZ09');
72
+        }
73
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) {
74
+            $newlang=$object->thirdparty->default_lang;
75
+        }
76
+        // for proposal, order, invoice, ...
77
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) {
78
+            $newlang=$object->default_lang;
79
+        }
80
+        // for thirdparty
74 81
         if (! empty($newlang))
75 82
         {
76 83
             $outputlangs = new Translate("",$conf);
@@ -78,22 +85,31 @@  discard block
 block discarded – undo
78 85
         }
79 86
 
80 87
         // To be sure vars is defined
81
-        if (empty($hidedetails)) $hidedetails=0;
82
-        if (empty($hidedesc)) $hidedesc=0;
83
-        if (empty($hideref)) $hideref=0;
84
-        if (empty($moreparams)) $moreparams=null;
88
+        if (empty($hidedetails)) {
89
+            $hidedetails=0;
90
+        }
91
+        if (empty($hidedesc)) {
92
+            $hidedesc=0;
93
+        }
94
+        if (empty($hideref)) {
95
+            $hideref=0;
96
+        }
97
+        if (empty($moreparams)) {
98
+            $moreparams=null;
99
+        }
85 100
 
86 101
         $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
87 102
         if ($result <= 0)
88 103
         {
89 104
             setEventMessages($object->error, $object->errors, 'errors');
90 105
             $action='';
91
-        }
92
-        else
106
+        } else
93 107
         {
94
-        	if (empty($donotredirect))	// This is set when include is done by bulk action "Bill Orders"
108
+        	if (empty($donotredirect)) {
109
+        	    // This is set when include is done by bulk action "Bill Orders"
95 110
         	{
96 111
 	            setEventMessages($langs->trans("FileGenerated"), null);
112
+        	}
97 113
 
98 114
 	            $urltoredirect = $_SERVER['REQUEST_URI'];
99 115
 	            $urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
@@ -122,8 +138,11 @@  discard block
 block discarded – undo
122 138
     $filetodelete=GETPOST('file','alpha');
123 139
     $file =	$upload_dir	. '/' .	$filetodelete;
124 140
     $ret=dol_delete_file($file,0,0,0,$object);
125
-    if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
126
-    else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors');
141
+    if ($ret) {
142
+        setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
143
+    } else {
144
+        setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors');
145
+    }
127 146
 
128 147
     // Make a redirect to avoid to keep the remove_file into the url that create side effects
129 148
     $urltoredirect = $_SERVER['REQUEST_URI'];
Please login to merge, or discard this patch.