Completed
Branch develop (f8a444)
by
unknown
32:44
created
htdocs/compta/deplacement/class/deplacementstats.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@
 block discarded – undo
45 45
 	 *
46 46
 	 * @param 	DoliDB		$db		   Database handler
47 47
 	 * @param 	int			$socid	   Id third party
48
-     * @param   mixed		$userid    Id user for filter or array of user ids
48
+     * @param   integer		$userid    Id user for filter or array of user ids
49 49
 	 * @return 	void
50 50
 	 */
51 51
 	function __construct($db, $socid=0, $userid=0)
Please login to merge, or discard this patch.
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -31,21 +31,21 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class DeplacementStats extends Stats
33 33
 {
34
-    public $table_element;
34
+	public $table_element;
35 35
 
36
-    var $socid;
37
-    var $userid;
36
+	var $socid;
37
+	var $userid;
38 38
 
39
-    var $from;
40
-    var $field;
41
-    var $where;
39
+	var $from;
40
+	var $field;
41
+	var $where;
42 42
 
43 43
 	/**
44 44
 	 * Constructor
45 45
 	 *
46 46
 	 * @param 	DoliDB		$db		   Database handler
47 47
 	 * @param 	int			$socid	   Id third party
48
-     * @param   mixed		$userid    Id user for filter or array of user ids
48
+	 * @param   mixed		$userid    Id user for filter or array of user ids
49 49
 	 * @return 	void
50 50
 	 */
51 51
 	function __construct($db, $socid=0, $userid=0)
@@ -53,8 +53,8 @@  discard block
 block discarded – undo
53 53
 		global $conf;
54 54
 
55 55
 		$this->db = $db;
56
-        $this->socid = $socid;
57
-        $this->userid = $userid;
56
+		$this->socid = $socid;
57
+		$this->userid = $userid;
58 58
 
59 59
 		$object=new Deplacement($this->db);
60 60
 		$this->from = MAIN_DB_PREFIX.$object->table_element;
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 			$this->where.=" AND fk_soc = ".$this->socid;
68 68
 		}
69 69
 		if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
70
-        else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
70
+		else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
71 71
 	}
72 72
 
73 73
 
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 		$sql.= " WHERE YEAR(dated) = ".$year;
101 101
 		$sql.= " AND ".$this->where;
102 102
 		$sql.= " GROUP BY dm";
103
-        $sql.= $this->db->order('dm','DESC');
103
+		$sql.= $this->db->order('dm','DESC');
104 104
 
105 105
 		$res=$this->_getNbByMonth($year, $sql);
106 106
 		//var_dump($res);print '<br>';
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
142 142
 		$sql.= " AND ".$this->where;
143 143
 		$sql.= " GROUP BY dm";
144
-        $sql.= $this->db->order('dm','DESC');
144
+		$sql.= $this->db->order('dm','DESC');
145 145
 
146 146
 		return $this->_getAverageByMonth($year, $sql);
147 147
 	}
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		$sql.= " FROM ".$this->from;
158 158
 		$sql.= " WHERE ".$this->where;
159 159
 		$sql.= " GROUP BY year";
160
-        $sql.= $this->db->order('year','DESC');
160
+		$sql.= $this->db->order('year','DESC');
161 161
 
162 162
 		return $this->_getAllByYear($sql);
163 163
 	}
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -22,8 +22,8 @@  discard block
 block discarded – undo
22 22
  *       \ingroup    factures
23 23
  *       \brief      Fichier de la classe de gestion des stats des deplacement et notes de frais
24 24
  */
25
-include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php';
26
-include_once DOL_DOCUMENT_ROOT . '/compta/deplacement/class/deplacement.class.php';
25
+include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php';
26
+include_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php';
27 27
 
28 28
 /**
29 29
  *       \class      DeplacementStats
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
      * @param   mixed		$userid    Id user for filter or array of user ids
49 49
 	 * @return 	void
50 50
 	 */
51
-	function __construct($db, $socid=0, $userid=0)
51
+	function __construct($db, $socid = 0, $userid = 0)
52 52
 	{
53 53
 		global $conf;
54 54
 
@@ -56,18 +56,18 @@  discard block
 block discarded – undo
56 56
         $this->socid = $socid;
57 57
         $this->userid = $userid;
58 58
 
59
-		$object=new Deplacement($this->db);
59
+		$object = new Deplacement($this->db);
60 60
 		$this->from = MAIN_DB_PREFIX.$object->table_element;
61
-		$this->field='km';
61
+		$this->field = 'km';
62 62
 
63 63
 		$this->where = " fk_statut > 0";
64
-		$this->where.= " AND entity = ".$conf->entity;
64
+		$this->where .= " AND entity = ".$conf->entity;
65 65
 		if ($this->socid)
66 66
 		{
67
-			$this->where.=" AND fk_soc = ".$this->socid;
67
+			$this->where .= " AND fk_soc = ".$this->socid;
68 68
 		}
69
-		if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
70
-        else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
69
+		if (is_array($this->userid) && count($this->userid) > 0) $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')';
70
+        else if ($this->userid > 0) $this->where .= ' AND fk_user = '.$this->userid;
71 71
 	}
72 72
 
73 73
 
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	function getNbByYear()
80 80
 	{
81 81
 		$sql = "SELECT YEAR(dated) as dm, count(*)";
82
-		$sql.= " FROM ".$this->from;
83
-		$sql.= " GROUP BY dm DESC";
84
-		$sql.= " WHERE ".$this->where;
82
+		$sql .= " FROM ".$this->from;
83
+		$sql .= " GROUP BY dm DESC";
84
+		$sql .= " WHERE ".$this->where;
85 85
 
86 86
 		return $this->_getNbByYear($sql);
87 87
 	}
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
 	function getNbByMonth($year)
97 97
 	{
98 98
 		$sql = "SELECT MONTH(dated) as dm, count(*)";
99
-		$sql.= " FROM ".$this->from;
100
-		$sql.= " WHERE YEAR(dated) = ".$year;
101
-		$sql.= " AND ".$this->where;
102
-		$sql.= " GROUP BY dm";
103
-        $sql.= $this->db->order('dm','DESC');
99
+		$sql .= " FROM ".$this->from;
100
+		$sql .= " WHERE YEAR(dated) = ".$year;
101
+		$sql .= " AND ".$this->where;
102
+		$sql .= " GROUP BY dm";
103
+        $sql .= $this->db->order('dm', 'DESC');
104 104
 
105
-		$res=$this->_getNbByMonth($year, $sql);
105
+		$res = $this->_getNbByMonth($year, $sql);
106 106
 		//var_dump($res);print '<br>';
107 107
 		return $res;
108 108
 	}
@@ -117,13 +117,13 @@  discard block
 block discarded – undo
117 117
 	function getAmountByMonth($year)
118 118
 	{
119 119
 		$sql = "SELECT date_format(dated,'%m') as dm, sum(".$this->field.")";
120
-		$sql.= " FROM ".$this->from;
121
-		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
122
-		$sql.= " AND ".$this->where;
123
-		$sql.= " GROUP BY dm";
124
-		$sql.= $this->db->order('dm','DESC');
120
+		$sql .= " FROM ".$this->from;
121
+		$sql .= " WHERE date_format(dated,'%Y') = '".$year."'";
122
+		$sql .= " AND ".$this->where;
123
+		$sql .= " GROUP BY dm";
124
+		$sql .= $this->db->order('dm', 'DESC');
125 125
 
126
-		$res=$this->_getAmountByMonth($year, $sql);
126
+		$res = $this->_getAmountByMonth($year, $sql);
127 127
 		//var_dump($res);print '<br>';
128 128
 		return $res;
129 129
 	}
@@ -137,11 +137,11 @@  discard block
 block discarded – undo
137 137
 	function getAverageByMonth($year)
138 138
 	{
139 139
 		$sql = "SELECT date_format(dated,'%m') as dm, avg(".$this->field.")";
140
-		$sql.= " FROM ".$this->from;
141
-		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
142
-		$sql.= " AND ".$this->where;
143
-		$sql.= " GROUP BY dm";
144
-        $sql.= $this->db->order('dm','DESC');
140
+		$sql .= " FROM ".$this->from;
141
+		$sql .= " WHERE date_format(dated,'%Y') = '".$year."'";
142
+		$sql .= " AND ".$this->where;
143
+		$sql .= " GROUP BY dm";
144
+        $sql .= $this->db->order('dm', 'DESC');
145 145
 
146 146
 		return $this->_getAverageByMonth($year, $sql);
147 147
 	}
@@ -154,10 +154,10 @@  discard block
 block discarded – undo
154 154
 	function getAllByYear()
155 155
 	{
156 156
 		$sql = "SELECT date_format(dated,'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg";
157
-		$sql.= " FROM ".$this->from;
158
-		$sql.= " WHERE ".$this->where;
159
-		$sql.= " GROUP BY year";
160
-        $sql.= $this->db->order('year','DESC');
157
+		$sql .= " FROM ".$this->from;
158
+		$sql .= " WHERE ".$this->where;
159
+		$sql .= " GROUP BY year";
160
+        $sql .= $this->db->order('year', 'DESC');
161 161
 
162 162
 		return $this->_getAllByYear($sql);
163 163
 	}
Please login to merge, or discard this patch.
Braces   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -66,8 +66,11 @@
 block discarded – undo
66 66
 		{
67 67
 			$this->where.=" AND fk_soc = ".$this->socid;
68 68
 		}
69
-		if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
70
-        else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
69
+		if (is_array($this->userid) && count($this->userid) > 0) {
70
+			$this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
71
+		} else if ($this->userid > 0) {
72
+        	$this->where.=' AND fk_user = '.$this->userid;
73
+        }
71 74
 	}
72 75
 
73 76
 
Please login to merge, or discard this patch.
htdocs/core/class/html.formintervention.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@
 block discarded – undo
50 50
 	 *	@param  string	$htmlname   Nom de la zone html
51 51
 	 *	@param	int		$maxlength	Maximum length of label
52 52
 	 *	@param	int		$showempty	Show empty line
53
-	 *	@return int         		Nbre of project if OK, <0 if KO
53
+	 *	@return string         		Nbre of project if OK, <0 if KO
54 54
 	 */
55 55
 	function select_interventions($socid=-1, $selected='', $htmlname='interventionid', $maxlength=16, $showempty=1)
56 56
 	{
Please login to merge, or discard this patch.
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -27,19 +27,19 @@
 block discarded – undo
27 27
  */
28 28
 class FormIntervention
29 29
 {
30
-    var $db;
31
-    var $error;
30
+	var $db;
31
+	var $error;
32 32
 
33 33
 
34
-    /**
35
-     * Constructor
36
-     *
37
-     * @param		DoliDB		$db      Database handler
38
-     */
39
-    public function __construct($db)
40
-    {
41
-        $this->db = $db;
42
-    }
34
+	/**
35
+	 * Constructor
36
+	 *
37
+	 * @param		DoliDB		$db      Database handler
38
+	 */
39
+	public function __construct($db)
40
+	{
41
+		$this->db = $db;
42
+	}
43 43
 
44 44
 
45 45
 	/**
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -52,30 +52,30 @@  discard block
 block discarded – undo
52 52
 	 *	@param	int		$showempty	Show empty line
53 53
 	 *	@return int         		Nbre of project if OK, <0 if KO
54 54
 	 */
55
-	function select_interventions($socid=-1, $selected='', $htmlname='interventionid', $maxlength=16, $showempty=1)
55
+	function select_interventions($socid = -1, $selected = '', $htmlname = 'interventionid', $maxlength = 16, $showempty = 1)
56 56
 	{
57
-		global $db,$user,$conf,$langs;
57
+		global $db, $user, $conf, $langs;
58 58
 
59
-		$out='';
59
+		$out = '';
60 60
 
61
-		$hideunselectables=false;
61
+		$hideunselectables = false;
62 62
 
63 63
 		// Search all contacts
64 64
 		$sql = 'SELECT f.rowid, f.ref, f.fk_soc, f.fk_statut';
65
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'fichinter as f';
66
-		$sql.= " WHERE f.entity = ".$conf->entity;
65
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'fichinter as f';
66
+		$sql .= " WHERE f.entity = ".$conf->entity;
67 67
 		if ($socid != '')
68 68
 		{
69
-			if ($socid == '0') $sql.= " AND (f.fk_soc = 0 OR f.fk_soc IS NULL)";
70
-			else $sql.= " AND f.fk_soc = ".$socid;
69
+			if ($socid == '0') $sql .= " AND (f.fk_soc = 0 OR f.fk_soc IS NULL)";
70
+			else $sql .= " AND f.fk_soc = ".$socid;
71 71
 		}
72 72
 
73 73
 		dol_syslog(get_class($this)."::select_intervention", LOG_DEBUG);
74
-		$resql=$db->query($sql);
74
+		$resql = $db->query($sql);
75 75
 		if ($resql)
76 76
 		{
77
-			$out.='<select id="interventionid" class="flat" name="'.$htmlname.'">';
78
-			if ($showempty) $out.='<option value="0">&nbsp;</option>';
77
+			$out .= '<select id="interventionid" class="flat" name="'.$htmlname.'">';
78
+			if ($showempty) $out .= '<option value="0">&nbsp;</option>';
79 79
 			$num = $db->num_rows($resql);
80 80
 			$i = 0;
81 81
 			if ($num)
@@ -84,49 +84,49 @@  discard block
 block discarded – undo
84 84
 				{
85 85
 					$obj = $db->fetch_object($resql);
86 86
 					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
87
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
87
+					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$user->rights->societe->lire)
88 88
 					{
89 89
 						// Do nothing
90 90
 					}
91 91
 					else
92 92
 					{
93
-						$labeltoshow=dol_trunc($obj->ref,18);
93
+						$labeltoshow = dol_trunc($obj->ref, 18);
94 94
 						if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
95 95
 						{
96
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
96
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
97 97
 						}
98 98
 						else
99 99
 						{
100
-							$disabled=0;
101
-							if (! $obj->fk_statut > 0)
100
+							$disabled = 0;
101
+							if (!$obj->fk_statut > 0)
102 102
 							{
103
-								$disabled=1;
104
-								$labeltoshow.=' ('.$langs->trans("Draft").')';
103
+								$disabled = 1;
104
+								$labeltoshow .= ' ('.$langs->trans("Draft").')';
105 105
 							}
106
-							if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
106
+							if ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
107 107
 							{
108
-								$disabled=1;
109
-								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
108
+								$disabled = 1;
109
+								$labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
110 110
 							}
111 111
 
112 112
 							if ($hideunselectables && $disabled)
113 113
 							{
114
-								$resultat='';
114
+								$resultat = '';
115 115
 							}
116 116
 							else
117 117
 							{
118
-								$resultat='<option value="'.$obj->rowid.'"';
119
-								if ($disabled) $resultat.=' disabled';
120
-								$resultat.='>'.$labeltoshow;
121
-								$resultat.='</option>';
118
+								$resultat = '<option value="'.$obj->rowid.'"';
119
+								if ($disabled) $resultat .= ' disabled';
120
+								$resultat .= '>'.$labeltoshow;
121
+								$resultat .= '</option>';
122 122
 							}
123
-							$out.=$resultat;
123
+							$out .= $resultat;
124 124
 						}
125 125
 					}
126 126
 					$i++;
127 127
 				}
128 128
 			}
129
-			$out.='</select>';
129
+			$out .= '</select>';
130 130
 			$db->free($resql);
131 131
 			return $out;
132 132
 		}
Please login to merge, or discard this patch.
Braces   +15 added lines, -12 removed lines patch added patch discarded remove patch
@@ -66,8 +66,11 @@  discard block
 block discarded – undo
66 66
 		$sql.= " WHERE f.entity = ".$conf->entity;
67 67
 		if ($socid != '')
68 68
 		{
69
-			if ($socid == '0') $sql.= " AND (f.fk_soc = 0 OR f.fk_soc IS NULL)";
70
-			else $sql.= " AND f.fk_soc = ".$socid;
69
+			if ($socid == '0') {
70
+				$sql.= " AND (f.fk_soc = 0 OR f.fk_soc IS NULL)";
71
+			} else {
72
+				$sql.= " AND f.fk_soc = ".$socid;
73
+			}
71 74
 		}
72 75
 
73 76
 		dol_syslog(get_class($this)."::select_intervention", LOG_DEBUG);
@@ -75,7 +78,9 @@  discard block
 block discarded – undo
75 78
 		if ($resql)
76 79
 		{
77 80
 			$out.='<select id="interventionid" class="flat" name="'.$htmlname.'">';
78
-			if ($showempty) $out.='<option value="0">&nbsp;</option>';
81
+			if ($showempty) {
82
+				$out.='<option value="0">&nbsp;</option>';
83
+			}
79 84
 			$num = $db->num_rows($resql);
80 85
 			$i = 0;
81 86
 			if ($num)
@@ -87,15 +92,13 @@  discard block
 block discarded – undo
87 92
 					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
88 93
 					{
89 94
 						// Do nothing
90
-					}
91
-					else
95
+					} else
92 96
 					{
93 97
 						$labeltoshow=dol_trunc($obj->ref,18);
94 98
 						if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
95 99
 						{
96 100
 							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
97
-						}
98
-						else
101
+						} else
99 102
 						{
100 103
 							$disabled=0;
101 104
 							if (! $obj->fk_statut > 0)
@@ -112,11 +115,12 @@  discard block
 block discarded – undo
112 115
 							if ($hideunselectables && $disabled)
113 116
 							{
114 117
 								$resultat='';
115
-							}
116
-							else
118
+							} else
117 119
 							{
118 120
 								$resultat='<option value="'.$obj->rowid.'"';
119
-								if ($disabled) $resultat.=' disabled';
121
+								if ($disabled) {
122
+									$resultat.=' disabled';
123
+								}
120 124
 								$resultat.='>'.$labeltoshow;
121 125
 								$resultat.='</option>';
122 126
 							}
@@ -129,8 +133,7 @@  discard block
 block discarded – undo
129 133
 			$out.='</select>';
130 134
 			$db->free($resql);
131 135
 			return $out;
132
-		}
133
-		else
136
+		} else
134 137
 		{
135 138
 			dol_print_error($db);
136 139
 			return '';
Please login to merge, or discard this patch.
htdocs/core/class/html.formmargin.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@
 block discarded – undo
51 51
 	 *
52 52
 	 * 	@param	CommonObject	$object			Object we want to get margin information for
53 53
 	 * 	@param 	boolean			$force_price	True of not
54
-	 * 	@return array							Array with info
54
+	 * 	@return integer							Array with info
55 55
 	 */
56 56
 	function getMarginInfosArray($object, $force_price=false)
57 57
 	{
Please login to merge, or discard this patch.
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -28,21 +28,21 @@  discard block
 block discarded – undo
28 28
  */
29 29
 class FormMargin
30 30
 {
31
-    var $db;
32
-    var $error;
31
+	var $db;
32
+	var $error;
33 33
 
34 34
 
35
-    /**
36
-     *	Constructor
37
-     *
38
-     *	@param	DoliDB		$db      Database handler
39
-     */
40
-    function __construct($db)
41
-    {
42
-        $this->db = $db;
35
+	/**
36
+	 *	Constructor
37
+	 *
38
+	 *	@param	DoliDB		$db      Database handler
39
+	 */
40
+	function __construct($db)
41
+	{
42
+		$this->db = $db;
43 43
 
44
-        return 1;
45
-    }
44
+		return 1;
45
+	}
46 46
 
47 47
 
48 48
 
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 					//}
143 143
 					//else
144 144
 					//{
145
-					    $marginInfos['margin_on_products'] += $pv - $pa;
145
+						$marginInfos['margin_on_products'] += $pv - $pa;
146 146
 					//}
147 147
 				}
148 148
 				elseif ($type == 1) {  // service
@@ -192,26 +192,26 @@  discard block
 block discarded – undo
192 192
 	{
193 193
 		global $langs, $conf, $user;
194 194
 
195
-    	if (! empty($user->societe_id)) return;
195
+		if (! empty($user->societe_id)) return;
196 196
 
197
-    	if (! $user->rights->margins->liretous) return;
197
+		if (! $user->rights->margins->liretous) return;
198 198
 
199
-        $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
199
+		$rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
200 200
 
201 201
 		$marginInfo = $this->getMarginInfosArray($object, $force_price);
202 202
 
203 203
 		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
204 204
 		{
205 205
 			print $langs->trans('ShowMarginInfos').' : ';
206
-	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
207
-	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
208
-	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
206
+			$hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
207
+			print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
208
+			print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
209 209
 
210
-    	    print '<script>$(document).ready(function() {
210
+			print '<script>$(document).ready(function() {
211 211
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
212 212
         	    $("span#hideMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 1); $(".margininfos").hide(); $("span#hideMarginInfos").addClass("hideobject"); $("span#showMarginInfos").removeClass("hideobject");})});
213 213
       	        });</script>';
214
-    	    if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
214
+			if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
215 215
 		}
216 216
 
217 217
 		print '<!-- Margin table -->'."\n";
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 	 * 	@param 	boolean			$force_price	True of not
55 55
 	 * 	@return array							Array with info
56 56
 	 */
57
-	function getMarginInfosArray($object, $force_price=false)
57
+	function getMarginInfosArray($object, $force_price = false)
58 58
 	{
59 59
 		global $conf, $db;
60 60
 
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 				'total_mark_rate' => ''
78 78
 		);
79 79
 
80
-		foreach($object->lines as $line)
80
+		foreach ($object->lines as $line)
81 81
 		{
82 82
 			if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price)
83 83
 			{
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 			}
95 95
 
96 96
 			$pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
97
-			$pa_ht = ($pv < 0 ? - $line->pa_ht : $line->pa_ht);      // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
97
+			$pa_ht = ($pv < 0 ? -$line->pa_ht : $line->pa_ht); // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
98 98
 			$pa = $line->qty * $pa_ht;
99 99
 			
100 100
 			// calcul des marges
@@ -102,8 +102,8 @@  discard block
 block discarded – undo
102 102
 				if ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '1') { // remise globale considérée comme produit
103 103
 					$marginInfos['pa_products'] += $pa;
104 104
 					$marginInfos['pv_products'] += $pv;
105
-					$marginInfos['pa_total'] +=  $pa;
106
-					$marginInfos['pv_total'] +=  $pv;
105
+					$marginInfos['pa_total'] += $pa;
106
+					$marginInfos['pv_total'] += $pv;
107 107
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
108 108
 					//if ($pv < 0)
109 109
 					//{
@@ -115,8 +115,8 @@  discard block
 block discarded – undo
115 115
 				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
116 116
 					$marginInfos['pa_services'] += $pa;
117 117
 					$marginInfos['pv_services'] += $pv;
118
-					$marginInfos['pa_total'] +=  $pa;
119
-					$marginInfos['pv_total'] +=  $pv;
118
+					$marginInfos['pa_total'] += $pa;
119
+					$marginInfos['pv_total'] += $pv;
120 120
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
121 121
 					//if ($pv < 0)
122 122
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
@@ -129,12 +129,12 @@  discard block
 block discarded – undo
129 129
 				}
130 130
 			}
131 131
 			else {
132
-				$type=$line->product_type?$line->product_type:$line->fk_product_type;
132
+				$type = $line->product_type ? $line->product_type : $line->fk_product_type;
133 133
 				if ($type == 0) {  // product
134 134
 					$marginInfos['pa_products'] += $pa;
135 135
 					$marginInfos['pv_products'] += $pv;
136
-					$marginInfos['pa_total'] +=  $pa;
137
-					$marginInfos['pv_total'] +=  $pv;
136
+					$marginInfos['pa_total'] += $pa;
137
+					$marginInfos['pv_total'] += $pv;
138 138
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
139 139
 					//if ($pv < 0)
140 140
 					//{
@@ -148,8 +148,8 @@  discard block
 block discarded – undo
148 148
 				elseif ($type == 1) {  // service
149 149
 					$marginInfos['pa_services'] += $pa;
150 150
 					$marginInfos['pv_services'] += $pv;
151
-					$marginInfos['pa_total'] +=  $pa;
152
-					$marginInfos['pv_total'] +=  $pv;
151
+					$marginInfos['pa_total'] += $pa;
152
+					$marginInfos['pv_total'] += $pv;
153 153
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
154 154
 					//if ($pv < 0)
155 155
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
@@ -188,24 +188,24 @@  discard block
 block discarded – undo
188 188
 	 * 	@param 	boolean			$force_price	Force price
189 189
 	 * 	@return	void
190 190
 	 */
191
-	function displayMarginInfos($object, $force_price=false)
191
+	function displayMarginInfos($object, $force_price = false)
192 192
 	{
193 193
 		global $langs, $conf, $user;
194 194
 
195
-    	if (! empty($user->societe_id)) return;
195
+    	if (!empty($user->societe_id)) return;
196 196
 
197
-    	if (! $user->rights->margins->liretous) return;
197
+    	if (!$user->rights->margins->liretous) return;
198 198
 
199 199
         $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
200 200
 
201 201
 		$marginInfo = $this->getMarginInfosArray($object, $force_price);
202 202
 
203
-		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
203
+		if (!empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
204 204
 		{
205 205
 			print $langs->trans('ShowMarginInfos').' : ';
206 206
 	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
207
-	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
208
-	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
207
+	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? '' : 'hideobject').'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</span>';
208
+	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? 'hideobject' : '').'">'.img_picto($langs->trans("Enabled"), 'switch_on').'</span>';
209 209
 
210 210
     	    print '<script>$(document).ready(function() {
211 211
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
@@ -224,13 +224,13 @@  discard block
 block discarded – undo
224 224
 		else
225 225
 			print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
226 226
 		print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
227
-		if (! empty($conf->global->DISPLAY_MARGIN_RATES))
227
+		if (!empty($conf->global->DISPLAY_MARGIN_RATES))
228 228
 			print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
229
-		if (! empty($conf->global->DISPLAY_MARK_RATES))
229
+		if (!empty($conf->global->DISPLAY_MARK_RATES))
230 230
 			print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
231 231
 		print '</tr>';
232 232
 
233
-		if (! empty($conf->product->enabled))
233
+		if (!empty($conf->product->enabled))
234 234
 		{
235 235
 			//if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) {
236 236
 			print '<tr class="oddeven">';
@@ -238,38 +238,38 @@  discard block
 block discarded – undo
238 238
 			print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
239 239
 			print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
240 240
 			print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
241
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
242
-				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
243
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
244
-				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
241
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
242
+				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '') ? '' : price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
243
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
244
+				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '') ? '' : price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
245 245
 			print '</tr>';
246 246
 		}
247 247
 
248
-		if (! empty($conf->service->enabled))
248
+		if (!empty($conf->service->enabled))
249 249
 		{
250 250
 			print '<tr class="oddeven">';
251 251
 			print '<td>'.$langs->trans('MarginOnServices').'</td>';
252 252
 			print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
253 253
 			print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
254 254
 			print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
255
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
256
-				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
257
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
258
-				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
255
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
256
+				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '') ? '' : price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
257
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
258
+				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '') ? '' : price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
259 259
 			print '</tr>';
260 260
 		}
261 261
 
262
-		if (! empty($conf->product->enabled) && ! empty($conf->service->enabled))
262
+		if (!empty($conf->product->enabled) && !empty($conf->service->enabled))
263 263
 		{
264 264
 			print '<tr class="liste_total">';
265 265
 			print '<td>'.$langs->trans('TotalMargin').'</td>';
266 266
 			print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
267 267
 			print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
268 268
 			print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
269
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
270
-				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
271
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
272
-				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
269
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
270
+				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
271
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
272
+				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
273 273
 			print '</tr>';
274 274
 		}
275 275
 		print '</table>';
Please login to merge, or discard this patch.
Braces   +69 added lines, -48 removed lines patch added patch discarded remove patch
@@ -83,10 +83,12 @@  discard block
 block discarded – undo
83 83
 			{
84 84
 				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
85 85
 				$product = new ProductFournisseur($db);
86
-				if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
87
-					$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
88
-				if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == "2" && $product->fourn_unitcharges > 0)
89
-					$line->pa_ht += $product->fourn_unitcharges;
86
+				if ($product->fetch_product_fournisseur_price($line->fk_fournprice)) {
87
+									$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
88
+				}
89
+				if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == "2" && $product->fourn_unitcharges > 0) {
90
+									$line->pa_ht += $product->fourn_unitcharges;
91
+				}
90 92
 			}
91 93
 			// si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
92 94
 			if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
@@ -111,8 +113,7 @@  discard block
 block discarded – undo
111 113
 					//}
112 114
 					//else
113 115
 						$marginInfos['margin_on_products'] += $pv - $pa;
114
-				}
115
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
116
+				} elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
116 117
 					$marginInfos['pa_services'] += $pa;
117 118
 					$marginInfos['pv_services'] += $pv;
118 119
 					$marginInfos['pa_total'] +=  $pa;
@@ -122,13 +123,11 @@  discard block
 block discarded – undo
122 123
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
123 124
 					//else
124 125
 						$marginInfos['margin_on_services'] += $pv - $pa;
125
-				}
126
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
126
+				} elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
127 127
 					$marginInfos['pa_total'] += $pa;
128 128
 					$marginInfos['pv_total'] += $pv;
129 129
 				}
130
-			}
131
-			else {
130
+			} else {
132 131
 				$type=$line->product_type?$line->product_type:$line->fk_product_type;
133 132
 				if ($type == 0) {  // product
134 133
 					$marginInfos['pa_products'] += $pa;
@@ -144,8 +143,7 @@  discard block
 block discarded – undo
144 143
 					//{
145 144
 					    $marginInfos['margin_on_products'] += $pv - $pa;
146 145
 					//}
147
-				}
148
-				elseif ($type == 1) {  // service
146
+				} elseif ($type == 1) {  // service
149 147
 					$marginInfos['pa_services'] += $pa;
150 148
 					$marginInfos['pv_services'] += $pv;
151 149
 					$marginInfos['pa_total'] +=  $pa;
@@ -158,25 +156,31 @@  discard block
 block discarded – undo
158 156
 				}
159 157
 			}
160 158
 		}
161
-		if ($marginInfos['pa_products'] > 0)
162
-			$marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
163
-		if ($marginInfos['pv_products'] > 0)
164
-			$marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
159
+		if ($marginInfos['pa_products'] > 0) {
160
+					$marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
161
+		}
162
+		if ($marginInfos['pv_products'] > 0) {
163
+					$marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
164
+		}
165 165
 
166
-		if ($marginInfos['pa_services'] > 0)
167
-			$marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
168
-		if ($marginInfos['pv_services'] > 0)
169
-			$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
166
+		if ($marginInfos['pa_services'] > 0) {
167
+					$marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
168
+		}
169
+		if ($marginInfos['pv_services'] > 0) {
170
+					$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
171
+		}
170 172
 
171 173
 		// if credit note, margin = -1 * (abs(selling_price) - buying_price)
172 174
 		//if ($marginInfos['pv_total'] < 0)
173 175
 		//	$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
174 176
 		//else
175 177
 			$marginInfos['total_margin'] = $marginInfos['pv_total'] - $marginInfos['pa_total'];
176
-		if ($marginInfos['pa_total'] > 0)
177
-			$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
178
-		if ($marginInfos['pv_total'] > 0)
179
-			$marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
178
+		if ($marginInfos['pa_total'] > 0) {
179
+					$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
180
+		}
181
+		if ($marginInfos['pv_total'] > 0) {
182
+					$marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
183
+		}
180 184
 
181 185
 		return $marginInfos;
182 186
 	}
@@ -192,17 +196,23 @@  discard block
 block discarded – undo
192 196
 	{
193 197
 		global $langs, $conf, $user;
194 198
 
195
-    	if (! empty($user->societe_id)) return;
199
+    	if (! empty($user->societe_id)) {
200
+    		return;
201
+    	}
196 202
 
197
-    	if (! $user->rights->margins->liretous) return;
203
+    	if (! $user->rights->margins->liretous) {
204
+    		return;
205
+    	}
198 206
 
199 207
         $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
200 208
 
201 209
 		$marginInfo = $this->getMarginInfosArray($object, $force_price);
202 210
 
203
-		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
211
+		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON)) {
212
+			// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
204 213
 		{
205 214
 			print $langs->trans('ShowMarginInfos').' : ';
215
+		}
206 216
 	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
207 217
 	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
208 218
 	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
@@ -211,7 +221,9 @@  discard block
 block discarded – undo
211 221
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
212 222
         	    $("span#hideMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 1); $(".margininfos").hide(); $("span#hideMarginInfos").addClass("hideobject"); $("span#showMarginInfos").removeClass("hideobject");})});
213 223
       	        });</script>';
214
-    	    if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
224
+    	    if (!empty($hidemargininfos)) {
225
+    	    	print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
226
+    	    }
215 227
 		}
216 228
 
217 229
 		print '<!-- Margin table -->'."\n";
@@ -219,15 +231,18 @@  discard block
 block discarded – undo
219 231
 		print '<tr class="liste_titre">';
220 232
 		print '<td class="liste_titre">'.$langs->trans('Margins').'</td>';
221 233
 		print '<td class="liste_titre" align="right">'.$langs->trans('SellingPrice').'</td>';
222
-		if ($conf->global->MARGIN_TYPE == "1")
223
-			print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
224
-		else
225
-			print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
234
+		if ($conf->global->MARGIN_TYPE == "1") {
235
+					print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
236
+		} else {
237
+					print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
238
+		}
226 239
 		print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
227
-		if (! empty($conf->global->DISPLAY_MARGIN_RATES))
228
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
229
-		if (! empty($conf->global->DISPLAY_MARK_RATES))
230
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
240
+		if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
241
+					print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
242
+		}
243
+		if (! empty($conf->global->DISPLAY_MARK_RATES)) {
244
+					print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
245
+		}
231 246
 		print '</tr>';
232 247
 
233 248
 		if (! empty($conf->product->enabled))
@@ -238,10 +253,12 @@  discard block
 block discarded – undo
238 253
 			print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
239 254
 			print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
240 255
 			print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
241
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
242
-				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
243
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
244
-				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
256
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
257
+							print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
258
+			}
259
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
260
+							print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
261
+			}
245 262
 			print '</tr>';
246 263
 		}
247 264
 
@@ -252,10 +269,12 @@  discard block
 block discarded – undo
252 269
 			print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
253 270
 			print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
254 271
 			print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
255
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
256
-				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
257
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
258
-				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
272
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
273
+							print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
274
+			}
275
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
276
+							print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
277
+			}
259 278
 			print '</tr>';
260 279
 		}
261 280
 
@@ -266,10 +285,12 @@  discard block
 block discarded – undo
266 285
 			print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
267 286
 			print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
268 287
 			print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
269
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
270
-				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
271
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
272
-				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
288
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
289
+							print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
290
+			}
291
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
292
+							print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
293
+			}
273 294
 			print '</tr>';
274 295
 		}
275 296
 		print '</table>';
Please login to merge, or discard this patch.
htdocs/core/db/mssql.class.php 4 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
      *  @param  int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
320 320
      *                   		 		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.
321 321
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
322
-     *  @return false|resource|true		Resultset of answer
322
+     *  @return resource		Resultset of answer
323 323
 	 */
324 324
 	function query($query,$usesavepoint=0,$type='auto')
325 325
 	{
@@ -516,7 +516,7 @@  discard block
 block discarded – undo
516 516
 	 *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
517 517
 	 *
518 518
 	 *	@param	resource	$resultset   Curseur de la requete voulue
519
-	 *	@return int		    Nombre de lignes
519
+	 *	@return string		    Nombre de lignes
520 520
 	 *	@see    num_rows
521 521
 	 */
522 522
 	function affected_rows($resultset)
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 	 *	Free last resultset used.
536 536
 	 *
537 537
 	 *	@param  resource	$resultset   Curseur de la requete voulue
538
-	 *	@return	bool
538
+	 *	@return	boolean|null
539 539
 	 */
540 540
 	function free($resultset=null)
541 541
 	{
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
 	/**
1016 1016
 	 *	Return list of available charset that can be used to store data in database
1017 1017
 	 *
1018
-	 *	@return		array		List of Charset
1018
+	 *	@return		string		List of Charset
1019 1019
 	 */
1020 1020
 	function getListOfCharacterSet()
1021 1021
 	{
Please login to merge, or discard this patch.
Indentation   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 	/** @var resource Resultset of last query */
45 45
 	private $_results;
46 46
 
47
-    /**
47
+	/**
48 48
 	 *	Constructor.
49 49
 	 *	This create an opened connexion to a database server and eventually to a database
50 50
 	 *
@@ -54,14 +54,14 @@  discard block
 block discarded – undo
54 54
 	 *	@param	    string	$pass		Mot de passe
55 55
 	 *	@param	    string	$name		Nom de la database
56 56
 	 *	@param	    int		$port		Port of database server
57
-     */
57
+	 */
58 58
 	function __construct($type, $host, $user, $pass, $name='', $port=0)
59 59
 	{
60 60
 		global $langs;
61 61
 
62 62
 		$this->database_user=$user;
63
-        $this->database_host=$host;
64
-        $this->database_port=$port;
63
+		$this->database_host=$host;
64
+		$this->database_port=$port;
65 65
 		$this->transaction_opened=0;
66 66
 
67 67
 		if (! function_exists("mssql_connect"))
@@ -127,13 +127,13 @@  discard block
 block discarded – undo
127 127
 		return $this->ok;
128 128
 	}
129 129
 
130
-    /**
131
-     *  Convert a SQL request in Mysql syntax to native syntax
132
-     *
133
-     *  @param     string	$line   SQL request line to convert
134
-     *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
135
-     *  @return    string   		SQL request line converted
136
-     */
130
+	/**
131
+	 *  Convert a SQL request in Mysql syntax to native syntax
132
+	 *
133
+	 *  @param     string	$line   SQL request line to convert
134
+	 *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
135
+	 *  @return    string   		SQL request line converted
136
+	 */
137 137
 	static function convertSQLFromMysql($line,$type='ddl')
138 138
 	{
139 139
 		return $line;
@@ -173,11 +173,11 @@  discard block
 block discarded – undo
173 173
 		//$this->query('SET NAMES '.$this->forcecharset);
174 174
 		//print "Resultat fonction connect: ".$this->db;
175 175
 		$set_options=array('SET ANSI_PADDING ON;',
176
-		    "SET ANSI_NULLS ON;",
177
-		    "SET ANSI_WARNINGS ON;",
178
-		    "SET ARITHABORT ON;",
179
-		    "SET CONCAT_NULL_YIELDS_NULL ON;",
180
-		    "SET QUOTED_IDENTIFIER ON;"
176
+			"SET ANSI_NULLS ON;",
177
+			"SET ANSI_WARNINGS ON;",
178
+			"SET ARITHABORT ON;",
179
+			"SET CONCAT_NULL_YIELDS_NULL ON;",
180
+			"SET QUOTED_IDENTIFIER ON;"
181 181
 		);
182 182
 		mssql_query(implode(' ',$set_options),$this->db);
183 183
 
@@ -194,8 +194,8 @@  discard block
 block discarded – undo
194 194
 		$resql=$this->query("SELECT @@VERSION");
195 195
 		if ($resql)
196 196
 		{
197
-            $version=$this->fetch_array($resql);
198
-            return $version['computed'];
197
+			$version=$this->fetch_array($resql);
198
+			return $version['computed'];
199 199
 		}
200 200
 		else return '';
201 201
 	}
@@ -210,22 +210,22 @@  discard block
 block discarded – undo
210 210
 		return 'php mssql driver';
211 211
 	}
212 212
 
213
-    /**
214
-     *  Close database connexion
215
-     *
216
-     *  @return     bool     True if disconnect successfull, false otherwise
217
-     *  @see        connect
218
-     */
219
-    function close()
220
-    {
221
-        if ($this->db)
222
-        {
223
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
224
-          $this->connected=false;
225
-          return mssql_close($this->db);
226
-        }
227
-        return false;
228
-    }
213
+	/**
214
+	 *  Close database connexion
215
+	 *
216
+	 *  @return     bool     True if disconnect successfull, false otherwise
217
+	 *  @see        connect
218
+	 */
219
+	function close()
220
+	{
221
+		if ($this->db)
222
+		{
223
+		  if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
224
+		  $this->connected=false;
225
+		  return mssql_close($this->db);
226
+		}
227
+		return false;
228
+	}
229 229
 
230 230
 
231 231
 	/**
@@ -236,12 +236,12 @@  discard block
 block discarded – undo
236 236
 	function begin()
237 237
 	{
238 238
 
239
-	    $res=mssql_query('select @@TRANCOUNT');
240
-	    $this->transaction_opened=mssql_result($res, 0, 0);
239
+		$res=mssql_query('select @@TRANCOUNT');
240
+		$this->transaction_opened=mssql_result($res, 0, 0);
241 241
 
242
-	    if ($this->transaction_opened == 0)
242
+		if ($this->transaction_opened == 0)
243 243
 		{
244
-		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
244
+			//return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
245 245
 			$ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
246 246
 			if ($ret)
247 247
 			{
@@ -256,19 +256,19 @@  discard block
 block discarded – undo
256 256
 	}
257 257
 
258 258
 	/**
259
-     * Validate a database transaction
260
-     *
261
-     * @param	string	$log        Add more log to default log line
262
-     * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
259
+	 * Validate a database transaction
260
+	 *
261
+	 * @param	string	$log        Add more log to default log line
262
+	 * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
263 263
 	 */
264 264
 	function commit($log='')
265 265
 	{
266
-	    $res=mssql_query('select @@TRANCOUNT');
267
-	    $this->transaction_opened=mssql_result($res, 0, 0);
266
+		$res=mssql_query('select @@TRANCOUNT');
267
+		$this->transaction_opened=mssql_result($res, 0, 0);
268 268
 
269 269
 		if ($this->transaction_opened == 1)
270 270
 		{
271
-		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
271
+			//return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
272 272
 			$ret=mssql_query("COMMIT TRANSACTION",$this->db);
273 273
 			if ($ret)
274 274
 			{
@@ -296,8 +296,8 @@  discard block
 block discarded – undo
296 296
 	 */
297 297
 	function rollback($log='')
298 298
 	{
299
-	    $res=mssql_query('select @@TRANCOUNT');
300
-	    $this->transaction_opened=mssql_result($res, 0, 0);
299
+		$res=mssql_query('select @@TRANCOUNT');
300
+		$this->transaction_opened=mssql_result($res, 0, 0);
301 301
 
302 302
 		if ($this->transaction_opened == 1)
303 303
 		{
@@ -314,13 +314,13 @@  discard block
 block discarded – undo
314 314
 	}
315 315
 
316 316
 	/**
317
-     *  Execute a SQL request and return the resultset
318
-     *
319
-     *  @param	string	$query          SQL query string
320
-     *  @param  int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
321
-     *                   		 		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.
322
-     *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
323
-     *  @return false|resource|true		Resultset of answer
317
+	 *  Execute a SQL request and return the resultset
318
+	 *
319
+	 *  @param	string	$query          SQL query string
320
+	 *  @param  int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
321
+	 *                   		 		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.
322
+	 *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
323
+	 *  @return false|resource|true		Resultset of answer
324 324
 	 */
325 325
 	function query($query,$usesavepoint=0,$type='auto')
326 326
 	{
@@ -337,85 +337,85 @@  discard block
 block discarded – undo
337 337
 
338 338
 		if ($type=="auto" || $type='dml')
339 339
 		{
340
-    		$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
341
-    		$query=preg_replace('/double/i','float',$query);
342
-    		$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
343
-    		$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
344
-    		$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
345
-
346
-    		$matches=array();
347
-    		$original_query='';
348
-    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
349
-    		{
350
-                $original_query=$query;
351
-                $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
352
-                if ($matches[2]) {
353
-                    //check if columun is nullable cause Sql server only allow 1 null value if unique index.
354
-                    $fields=explode(",",trim($matches[4]));
355
-                    $fields_clear=array_map('trim',$fields);
356
-                    $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
357
-                    $query_comp=array();
358
-                    foreach($infos as $fld) {
359
-                        if ($fld->IS_NULLABLE == 'YES') {
360
-                            $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
361
-                        }
362
-                    }
363
-                    if (! empty($query_comp))
364
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
365
-                }
366
-    		}
367
-    		else
368
-    		{
369
-    		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
370
-    		    {
371
-                    $original_query=$query;
372
-                    $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
373
-    		    }
374
-    		}
340
+			$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
341
+			$query=preg_replace('/double/i','float',$query);
342
+			$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
343
+			$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
344
+			$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
345
+
346
+			$matches=array();
347
+			$original_query='';
348
+			if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
349
+			{
350
+				$original_query=$query;
351
+				$query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
352
+				if ($matches[2]) {
353
+					//check if columun is nullable cause Sql server only allow 1 null value if unique index.
354
+					$fields=explode(",",trim($matches[4]));
355
+					$fields_clear=array_map('trim',$fields);
356
+					$infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
357
+					$query_comp=array();
358
+					foreach($infos as $fld) {
359
+						if ($fld->IS_NULLABLE == 'YES') {
360
+							$query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
361
+						}
362
+					}
363
+					if (! empty($query_comp))
364
+						$query.=" WHERE ".implode(" AND ",$query_comp);
365
+				}
366
+			}
367
+			else
368
+			{
369
+				if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
370
+				{
371
+					$original_query=$query;
372
+					$query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
373
+				}
374
+			}
375 375
 
376 376
 		}
377 377
 
378 378
 		if ($type=="auto" || $type='ddl')
379 379
 		{
380
-    		$itemfound = stripos($query, " limit ");
381
-    		if ($itemfound !== false) {
382
-    			// Extraire le nombre limite
383
-    			$number = stristr($query, " limit ");
384
-    			$number = substr($number, 7);
385
-    			// Inserer l'instruction TOP et le nombre limite
386
-    			$query = str_ireplace("select ", "select top ".$number." ", $query);
387
-    			// Supprimer l'instruction MySql
388
-    			$query = str_ireplace(" limit ".$number, "", $query);
389
-    		}
390
-
391
-    		$itemfound = stripos($query, " week(");
392
-    		if ($itemfound !== false) {
393
-    			// Recreer une requete sans instruction Mysql
394
-    			$positionMySql = stripos($query, " week(");
395
-    			$newquery = substr($query, 0, $positionMySql);
396
-
397
-    			// Recuperer la date passee en parametre
398
-    			$extractvalue = stristr($query, " week(");
399
-    			$extractvalue = substr($extractvalue, 6);
400
-    			$positionMySql = stripos($extractvalue, ")");
401
-    			// Conserver la fin de la requete
402
-    			$endofquery = substr($extractvalue, $positionMySql);
403
-    			$extractvalue = substr($extractvalue, 0, $positionMySql);
404
-
405
-    			// Remplacer l'instruction MySql en Sql Server
406
-    			// Inserer la date en parametre et le reste de la requete
407
-    			$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
408
-    		}
409
-    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
410
-    	   {
411
-    	       //var_dump($query);
412
-    	       //var_dump($matches);
413
-    	       //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
414
-    	       $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
415
-    	       @mssql_query($sql, $this->db);
416
-    	       $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
417
-
418
-    	   }
380
+			$itemfound = stripos($query, " limit ");
381
+			if ($itemfound !== false) {
382
+				// Extraire le nombre limite
383
+				$number = stristr($query, " limit ");
384
+				$number = substr($number, 7);
385
+				// Inserer l'instruction TOP et le nombre limite
386
+				$query = str_ireplace("select ", "select top ".$number." ", $query);
387
+				// Supprimer l'instruction MySql
388
+				$query = str_ireplace(" limit ".$number, "", $query);
389
+			}
390
+
391
+			$itemfound = stripos($query, " week(");
392
+			if ($itemfound !== false) {
393
+				// Recreer une requete sans instruction Mysql
394
+				$positionMySql = stripos($query, " week(");
395
+				$newquery = substr($query, 0, $positionMySql);
396
+
397
+				// Recuperer la date passee en parametre
398
+				$extractvalue = stristr($query, " week(");
399
+				$extractvalue = substr($extractvalue, 6);
400
+				$positionMySql = stripos($extractvalue, ")");
401
+				// Conserver la fin de la requete
402
+				$endofquery = substr($extractvalue, $positionMySql);
403
+				$extractvalue = substr($extractvalue, 0, $positionMySql);
404
+
405
+				// Remplacer l'instruction MySql en Sql Server
406
+				// Inserer la date en parametre et le reste de la requete
407
+				$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
408
+			}
409
+		   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
410
+		   {
411
+			   //var_dump($query);
412
+			   //var_dump($matches);
413
+			   //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
414
+			   $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
415
+			   @mssql_query($sql, $this->db);
416
+			   $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
417
+
418
+		   }
419 419
 		}
420 420
 		//print "<!--".$query."-->";
421 421
 
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 
434 434
 		if (!empty($post_query))
435 435
 		{
436
-		    @mssql_query($post_query, $this->db);
436
+			@mssql_query($post_query, $this->db);
437 437
 		}
438 438
 
439 439
 		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
 				$result = mssql_query("SELECT @@ERROR as code", $this->db);
445 445
 				$row = mssql_fetch_array($result);
446 446
 
447
-                $this->lastqueryerror = $query;
447
+				$this->lastqueryerror = $query;
448 448
 				$this->lasterror = $this->error();
449 449
 				$this->lasterrno = $row["code"];
450 450
 
@@ -473,10 +473,10 @@  discard block
 block discarded – undo
473 473
 	}
474 474
 
475 475
 	/**
476
-     *	Return datas as an array
477
-     *
478
-     *	@param	resource	$resultset  Resultset of request
479
-     *	@return	array|false				Array or false if KO or end of cursor
476
+	 *	Return datas as an array
477
+	 *
478
+	 *	@param	resource	$resultset  Resultset of request
479
+	 *	@return	array|false				Array or false if KO or end of cursor
480 480
 	 */
481 481
 	function fetch_array($resultset)
482 482
 	{
@@ -487,10 +487,10 @@  discard block
 block discarded – undo
487 487
 
488 488
 
489 489
 	/**
490
-     *	Return datas as an array
491
-     *
492
-     *	@param	resource	$resultset  Resultset of request
493
-     *	@return	array|false				Array or false if KO or end of cursor
490
+	 *	Return datas as an array
491
+	 *
492
+	 *	@param	resource	$resultset  Resultset of request
493
+	 *	@return	array|false				Array or false if KO or end of cursor
494 494
 	 */
495 495
 	function fetch_row($resultset)
496 496
 	{
@@ -500,11 +500,11 @@  discard block
 block discarded – undo
500 500
 	}
501 501
 
502 502
 	/**
503
-     *	Return number of lines for result of a SELECT
504
-     *
505
-     *	@param	resource	$resultset  Resulset of requests
506
-     *	@return int		    			Nb of lines
507
-     *	@see    affected_rows
503
+	 *	Return number of lines for result of a SELECT
504
+	 *
505
+	 *	@param	resource	$resultset  Resulset of requests
506
+	 *	@return int		    			Nb of lines
507
+	 *	@see    affected_rows
508 508
 	 */
509 509
 	function num_rows($resultset)
510 510
 	{
@@ -571,9 +571,9 @@  discard block
 block discarded – undo
571 571
 	}
572 572
 
573 573
 	/**
574
-     *	Return generic error code of last operation.
575
-     *
576
-     *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
574
+	 *	Return generic error code of last operation.
575
+	 *
576
+	 *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
577 577
 	 */
578 578
 	function errno()
579 579
 	{
@@ -660,12 +660,12 @@  discard block
 block discarded – undo
660 660
 	}
661 661
 
662 662
 	/**
663
-     *  Encrypt sensitive data in database
664
-     *  Warning: This function includes the escape, so it must use direct value
665
-     *
666
-     *  @param  string  $fieldorvalue   Field name or value to encrypt
667
-     *  @param	int		$withQuotes     Return string with quotes
668
-     *  @return string          		XXX(field) or XXX('value') or field or 'value'
663
+	 *  Encrypt sensitive data in database
664
+	 *  Warning: This function includes the escape, so it must use direct value
665
+	 *
666
+	 *  @param  string  $fieldorvalue   Field name or value to encrypt
667
+	 *  @param	int		$withQuotes     Return string with quotes
668
+	 *  @return string          		XXX(field) or XXX('value') or field or 'value'
669 669
 	 */
670 670
 	function encrypt($fieldorvalue, $withQuotes=0)
671 671
 	{
@@ -682,10 +682,10 @@  discard block
 block discarded – undo
682 682
 	}
683 683
 
684 684
 	/**
685
-     *	Decrypt sensitive data in database
686
-     *
687
-     *	@param	string	$value			Value to decrypt
688
-     * 	@return	string					Decrypted value if used
685
+	 *	Decrypt sensitive data in database
686
+	 *
687
+	 *	@param	string	$value			Value to decrypt
688
+	 * 	@return	string					Decrypted value if used
689 689
 	 */
690 690
 	function decrypt($value)
691 691
 	{
@@ -712,8 +712,8 @@  discard block
 block discarded – undo
712 712
 		$resql=$this->query('SELECT CONNECTION_ID()');
713 713
 		if ($resql)
714 714
 		{
715
-            $row=$this->fetch_row($resql);
716
-            return $row[0];
715
+			$row=$this->fetch_row($resql);
716
+			return $row[0];
717 717
 		}
718 718
 		else return '?';
719 719
 	}
@@ -731,12 +731,12 @@  discard block
 block discarded – undo
731 731
 	 */
732 732
 	function DDLCreateDb($database,$charset='',$collation='',$owner='')
733 733
 	{
734
-        /*if (empty($charset))   $charset=$this->forcecharset;
734
+		/*if (empty($charset))   $charset=$this->forcecharset;
735 735
         if (empty($collation)) $collation=$this->forcecollate;
736 736
         */
737 737
 
738 738
 		$sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
739
-        //TODO: Check if we need to force a charset
739
+		//TODO: Check if we need to force a charset
740 740
 		//$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
741 741
 		$ret=$this->query($sql);
742 742
 
@@ -747,11 +747,11 @@  discard block
 block discarded – undo
747 747
 		mssql_query($sql,$this->db);
748 748
 
749 749
 		$sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
750
-	    @mssql_query($sql,$this->db);
751
-	    $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
752
-	    @mssql_query($sql,$this->db);
750
+		@mssql_query($sql,$this->db);
751
+		$sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
752
+		@mssql_query($sql,$this->db);
753 753
 
754
-	    return $ret;
754
+		return $ret;
755 755
 	}
756 756
 
757 757
 	/**
@@ -759,7 +759,7 @@  discard block
 block discarded – undo
759 759
 	 *
760 760
 	 *  @param	string		$database	Name of database
761 761
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
762
-     *  @return	array					List of tables in an array
762
+	 *  @return	array					List of tables in an array
763 763
 	 */
764 764
 	function DDLListTables($database,$table='')
765 765
 	{
@@ -968,48 +968,48 @@  discard block
 block discarded – undo
968 968
 	 */
969 969
 	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
970 970
 	{
971
-	    $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
972
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
973
-        $resql=$this->query($sql);
974
-        if (! $resql)
975
-        {
976
-            if ($this->lasterrno != '15025')
977
-            {
978
-	            return -1;
979
-            }
980
-            else
971
+		$sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
972
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
973
+		$resql=$this->query($sql);
974
+		if (! $resql)
975
+		{
976
+			if ($this->lasterrno != '15025')
981 977
 			{
982
-            	// If user already exists, we continue to set permissions
983
-            	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
984
-            }
985
-        }
986
-        $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
987
-        $ressql=$this->query($sql);
988
-        if (! $ressql)
989
-        {
990
-            dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
991
-            return -1;
992
-        }
993
-        else
994
-        {
995
-            if ($num)
996
-            {
997
-                $this->select_db($dolibarr_main_db_name);
998
-                $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
999
-                $this->query($sql);
1000
-                $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1001
-                $this->query($sql);
1002
-            }
1003
-        }
1004
-	    return 1;
978
+				return -1;
979
+			}
980
+			else
981
+			{
982
+				// If user already exists, we continue to set permissions
983
+				dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
984
+			}
985
+		}
986
+		$sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
987
+		$ressql=$this->query($sql);
988
+		if (! $ressql)
989
+		{
990
+			dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
991
+			return -1;
992
+		}
993
+		else
994
+		{
995
+			if ($num)
996
+			{
997
+				$this->select_db($dolibarr_main_db_name);
998
+				$sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
999
+				$this->query($sql);
1000
+				$sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1001
+				$this->query($sql);
1002
+			}
1003
+		}
1004
+		return 1;
1005 1005
 	}
1006 1006
 
1007
-    /**
1008
-     *	Return charset used to store data in database
1009
-     *
1010
-     *	@return		string		Charset
1011
-     */
1012
-    function getDefaultCharacterSetDatabase()
1007
+	/**
1008
+	 *	Return charset used to store data in database
1009
+	 *
1010
+	 *	@return		string		Charset
1011
+	 */
1012
+	function getDefaultCharacterSetDatabase()
1013 1013
 	{
1014 1014
 		// FIXME: Dummy method
1015 1015
 		// TODO: Implement
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
 		// FIXME: Dummy method
1070 1070
 		// TODO: Implement
1071 1071
 
1072
-	    return '';
1072
+		return '';
1073 1073
 	}
1074 1074
 
1075 1075
 	/**
@@ -1082,7 +1082,7 @@  discard block
 block discarded – undo
1082 1082
 		// FIXME: Dummy method
1083 1083
 		// TODO: Implement
1084 1084
 
1085
-	    return '';
1085
+		return '';
1086 1086
 	}
1087 1087
 
1088 1088
 	/**
@@ -1123,7 +1123,7 @@  discard block
 block discarded – undo
1123 1123
 	 * @return     string              field's name escaped
1124 1124
 	 */
1125 1125
 	function EscapeFieldName($fieldname) {
1126
-	    return "[".$fieldname."]";
1126
+		return "[".$fieldname."]";
1127 1127
 	}
1128 1128
 
1129 1129
 
@@ -1135,28 +1135,28 @@  discard block
 block discarded – undo
1135 1135
 	 * @return false|object
1136 1136
 	 */
1137 1137
 	function GetFieldInformation($table,$fields) {
1138
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1139
-	    if (is_array($fields))
1140
-	    {
1141
-	        $where=" IN ('".implode("','",$fields)."')";
1142
-	    }
1143
-	    else
1144
-	    {
1145
-	        $where="='".$this->escape($fields)."'";
1146
-	    }
1147
-	    $result=array();
1148
-	    $ret=mssql_query($sql.$where,$this->db);
1149
-	    if ($ret)
1150
-	    {
1151
-	        while($obj=mssql_fetch_object($ret))
1152
-	        {
1153
-	            $result[]=$obj;
1154
-	        }
1155
-	    }
1156
-	    else
1157
-	        return false;
1158
-
1159
-	    return $result;
1138
+		$sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1139
+		if (is_array($fields))
1140
+		{
1141
+			$where=" IN ('".implode("','",$fields)."')";
1142
+		}
1143
+		else
1144
+		{
1145
+			$where="='".$this->escape($fields)."'";
1146
+		}
1147
+		$result=array();
1148
+		$ret=mssql_query($sql.$where,$this->db);
1149
+		if ($ret)
1150
+		{
1151
+			while($obj=mssql_fetch_object($ret))
1152
+			{
1153
+				$result[]=$obj;
1154
+			}
1155
+		}
1156
+		else
1157
+			return false;
1158
+
1159
+		return $result;
1160 1160
 	}
1161 1161
 
1162 1162
 }
Please login to merge, or discard this patch.
Spacing   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  *	\brief			Fichier de la classe permettant de gerer une base MSSQL
25 25
  */
26 26
 
27
-require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
27
+require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
28 28
 
29 29
 /**
30 30
  *	Classe de gestion de la database de dolibarr
@@ -32,15 +32,15 @@  discard block
 block discarded – undo
32 32
 class DoliDBMssql extends DoliDB
33 33
 {
34 34
 	//! Database type
35
-	public $type='mssql';
35
+	public $type = 'mssql';
36 36
 	//! Database label
37
-	const LABEL='MSSQL';
37
+	const LABEL = 'MSSQL';
38 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
39
+	var $forcecharset = 'latin1'; // Can't be static as it may be forced with a dynamic value
40 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
41
+	var $forcecollate = 'latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value
42 42
 	//! Version min database
43
-	const VERSIONMIN='2000';
43
+	const VERSIONMIN = '2000';
44 44
 	/** @var resource Resultset of last query */
45 45
 	private $_results;
46 46
 
@@ -55,30 +55,30 @@  discard block
 block discarded – undo
55 55
 	 *	@param	    string	$name		Nom de la database
56 56
 	 *	@param	    int		$port		Port of database server
57 57
      */
58
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
58
+	function __construct($type, $host, $user, $pass, $name = '', $port = 0)
59 59
 	{
60 60
 		global $langs;
61 61
 
62
-		$this->database_user=$user;
63
-        $this->database_host=$host;
64
-        $this->database_port=$port;
65
-		$this->transaction_opened=0;
62
+		$this->database_user = $user;
63
+        $this->database_host = $host;
64
+        $this->database_port = $port;
65
+		$this->transaction_opened = 0;
66 66
 
67
-		if (! function_exists("mssql_connect"))
67
+		if (!function_exists("mssql_connect"))
68 68
 		{
69 69
 			$this->connected = false;
70 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);
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 73
 			return $this->ok;
74 74
 		}
75 75
 
76
-		if (! $host)
76
+		if (!$host)
77 77
 		{
78 78
 			$this->connected = false;
79 79
 			$this->ok = false;
80
-			$this->error=$langs->trans("ErrorWrongHostParameter");
81
-			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
80
+			$this->error = $langs->trans("ErrorWrongHostParameter");
81
+			dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters", LOG_ERR);
82 82
 			return $this->ok;
83 83
 		}
84 84
 
@@ -96,8 +96,8 @@  discard block
 block discarded – undo
96 96
 			// host, login ou password incorrect
97 97
 			$this->connected = false;
98 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);
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 101
 		}
102 102
 
103 103
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -114,8 +114,8 @@  discard block
 block discarded – undo
114 114
 				$this->database_selected = false;
115 115
 				$this->database_name = '';
116 116
 				$this->ok = false;
117
-				$this->error=$this->error();
118
-				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
117
+				$this->error = $this->error();
118
+				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error, LOG_ERR);
119 119
 			}
120 120
 		}
121 121
 		else
@@ -134,7 +134,7 @@  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')
137
+	static function convertSQLFromMysql($line, $type = 'ddl')
138 138
 	{
139 139
 		return $line;
140 140
 	}
@@ -161,25 +161,25 @@  discard block
 block discarded – undo
161 161
 	 *	@return		false|resource|true	Database access handler
162 162
 	 *	@see		close
163 163
 	 */
164
-	function connect($host, $login, $passwd, $name, $port=0)
164
+	function connect($host, $login, $passwd, $name, $port = 0)
165 165
 	{
166 166
 		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
167
-		$newhost=$host;
168
-		if ($port) $newhost.=':'.$port;
169
-		$this->db  = @mssql_connect($newhost, $login, $passwd);
167
+		$newhost = $host;
168
+		if ($port) $newhost .= ':'.$port;
169
+		$this->db = @mssql_connect($newhost, $login, $passwd);
170 170
 		//force les enregistrement en latin1 si la base est en utf8 par defaut
171 171
 		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
172 172
 		// les nouvelles version de Dolibarr car force par l'install Dolibarr.
173 173
 		//$this->query('SET NAMES '.$this->forcecharset);
174 174
 		//print "Resultat fonction connect: ".$this->db;
175
-		$set_options=array('SET ANSI_PADDING ON;',
175
+		$set_options = array('SET ANSI_PADDING ON;',
176 176
 		    "SET ANSI_NULLS ON;",
177 177
 		    "SET ANSI_WARNINGS ON;",
178 178
 		    "SET ARITHABORT ON;",
179 179
 		    "SET CONCAT_NULL_YIELDS_NULL ON;",
180 180
 		    "SET QUOTED_IDENTIFIER ON;"
181 181
 		);
182
-		mssql_query(implode(' ',$set_options),$this->db);
182
+		mssql_query(implode(' ', $set_options), $this->db);
183 183
 
184 184
 		return $this->db;
185 185
 	}
@@ -191,10 +191,10 @@  discard block
 block discarded – undo
191 191
 	 */
192 192
 	function getVersion()
193 193
 	{
194
-		$resql=$this->query("SELECT @@VERSION");
194
+		$resql = $this->query("SELECT @@VERSION");
195 195
 		if ($resql)
196 196
 		{
197
-            $version=$this->fetch_array($resql);
197
+            $version = $this->fetch_array($resql);
198 198
             return $version['computed'];
199 199
 		}
200 200
 		else return '';
@@ -220,8 +220,8 @@  discard block
 block discarded – undo
220 220
     {
221 221
         if ($this->db)
222 222
         {
223
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
224
-          $this->connected=false;
223
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
224
+          $this->connected = false;
225 225
           return mssql_close($this->db);
226 226
         }
227 227
         return false;
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
 	function begin()
237 237
 	{
238 238
 
239
-	    $res=mssql_query('select @@TRANCOUNT');
240
-	    $this->transaction_opened=mssql_result($res, 0, 0);
239
+	    $res = mssql_query('select @@TRANCOUNT');
240
+	    $this->transaction_opened = mssql_result($res, 0, 0);
241 241
 
242 242
 	    if ($this->transaction_opened == 0)
243 243
 		{
244 244
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
245
-			$ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
245
+			$ret = mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;", $this->db);
246 246
 			if ($ret)
247 247
 			{
248
-				dol_syslog("BEGIN Transaction",LOG_DEBUG);
248
+				dol_syslog("BEGIN Transaction", LOG_DEBUG);
249 249
 			}
250 250
 			return $ret;
251 251
 		}
@@ -261,18 +261,18 @@  discard block
 block discarded – undo
261 261
      * @param	string	$log        Add more log to default log line
262 262
      * @return  bool         		true if validation is OK or transaction level no started, false if ERROR
263 263
 	 */
264
-	function commit($log='')
264
+	function commit($log = '')
265 265
 	{
266
-	    $res=mssql_query('select @@TRANCOUNT');
267
-	    $this->transaction_opened=mssql_result($res, 0, 0);
266
+	    $res = mssql_query('select @@TRANCOUNT');
267
+	    $this->transaction_opened = mssql_result($res, 0, 0);
268 268
 
269 269
 		if ($this->transaction_opened == 1)
270 270
 		{
271 271
 		    //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
272
-			$ret=mssql_query("COMMIT TRANSACTION",$this->db);
272
+			$ret = mssql_query("COMMIT TRANSACTION", $this->db);
273 273
 			if ($ret)
274 274
 			{
275
-				dol_syslog("COMMIT Transaction",LOG_DEBUG);
275
+				dol_syslog("COMMIT Transaction", LOG_DEBUG);
276 276
 				return true;
277 277
 			}
278 278
 			else
@@ -294,15 +294,15 @@  discard block
 block discarded – undo
294 294
 	 * @param	string	$log	Add more log to default log line
295 295
 	 * @return	bool             true si annulation ok ou transaction non ouverte, false en cas d'erreur
296 296
 	 */
297
-	function rollback($log='')
297
+	function rollback($log = '')
298 298
 	{
299
-	    $res=mssql_query('select @@TRANCOUNT');
300
-	    $this->transaction_opened=mssql_result($res, 0, 0);
299
+	    $res = mssql_query('select @@TRANCOUNT');
300
+	    $this->transaction_opened = mssql_result($res, 0, 0);
301 301
 
302 302
 		if ($this->transaction_opened == 1)
303 303
 		{
304
-			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
305
-			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
304
+			$ret = mssql_query("ROLLBACK TRANSACTION", $this->db);
305
+			dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
306 306
 			return $ret;
307 307
 		}
308 308
 		elseif ($this->transaction_opened > 1)
@@ -322,60 +322,60 @@  discard block
 block discarded – undo
322 322
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
323 323
      *  @return false|resource|true		Resultset of answer
324 324
 	 */
325
-	function query($query,$usesavepoint=0,$type='auto')
325
+	function query($query, $usesavepoint = 0, $type = 'auto')
326 326
 	{
327 327
 		$query = trim($query);
328 328
 
329
-		if (preg_match('/^--/',$query)) return true;
329
+		if (preg_match('/^--/', $query)) return true;
330 330
 
331 331
 		// Conversion syntaxe MySql vers MSDE.
332 332
 		$query = str_ireplace("now()", "getdate()", $query);
333 333
 		// Erreur SQL: cannot update timestamp field
334 334
 		$query = str_ireplace(", tms = tms", "", $query);
335 335
 
336
-		$query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
336
+		$query = preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/", "$1[$2]$3", $query);
337 337
 
338
-		if ($type=="auto" || $type='dml')
338
+		if ($type == "auto" || $type = 'dml')
339 339
 		{
340
-    		$query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
341
-    		$query=preg_replace('/double/i','float',$query);
342
-    		$query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
343
-    		$query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
344
-    		$query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
345
-
346
-    		$matches=array();
347
-    		$original_query='';
348
-    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
340
+    		$query = preg_replace('/AUTO_INCREMENT/i', 'IDENTITY', $query);
341
+    		$query = preg_replace('/double/i', 'float', $query);
342
+    		$query = preg_replace('/float\((.*)\)/', 'numeric($1)', $query);
343
+    		$query = preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i', '$1', $query);
344
+    		$query = preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i', "$1VARCHAR(MAX)$3", $query);
345
+
346
+    		$matches = array();
347
+    		$original_query = '';
348
+    		if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query, $matches))
349 349
     		{
350
-                $original_query=$query;
351
-                $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
350
+                $original_query = $query;
351
+                $query = "CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
352 352
                 if ($matches[2]) {
353 353
                     //check if columun is nullable cause Sql server only allow 1 null value if unique index.
354
-                    $fields=explode(",",trim($matches[4]));
355
-                    $fields_clear=array_map('trim',$fields);
356
-                    $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
357
-                    $query_comp=array();
358
-                    foreach($infos as $fld) {
354
+                    $fields = explode(",", trim($matches[4]));
355
+                    $fields_clear = array_map('trim', $fields);
356
+                    $infos = $this->GetFieldInformation(trim($matches[1]), $fields_clear);
357
+                    $query_comp = array();
358
+                    foreach ($infos as $fld) {
359 359
                         if ($fld->IS_NULLABLE == 'YES') {
360
-                            $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
360
+                            $query_comp[] = $fld->COLUMN_NAME." IS NOT NULL";
361 361
                         }
362 362
                     }
363
-                    if (! empty($query_comp))
364
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
363
+                    if (!empty($query_comp))
364
+                        $query .= " WHERE ".implode(" AND ", $query_comp);
365 365
                 }
366 366
     		}
367 367
     		else
368 368
     		{
369 369
     		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
370 370
     		    {
371
-                    $original_query=$query;
372
-                    $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
371
+                    $original_query = $query;
372
+                    $query = "ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
373 373
     		    }
374 374
     		}
375 375
 
376 376
 		}
377 377
 
378
-		if ($type=="auto" || $type='ddl')
378
+		if ($type == "auto" || $type = 'ddl')
379 379
 		{
380 380
     		$itemfound = stripos($query, " limit ");
381 381
     		if ($itemfound !== false) {
@@ -406,22 +406,22 @@  discard block
 block discarded – undo
406 406
     			// Inserer la date en parametre et le reste de la requete
407 407
     			$query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
408 408
     		}
409
-    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
409
+    	   if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i', $query, $matches))
410 410
     	   {
411 411
     	       //var_dump($query);
412 412
     	       //var_dump($matches);
413 413
     	       //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
414
-    	       $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
414
+    	       $sql = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
415 415
     	       @mssql_query($sql, $this->db);
416
-    	       $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
416
+    	       $post_query = 'SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
417 417
 
418 418
     	   }
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'))) dol_syslog('sql='.$query, LOG_DEBUG);
423 423
 
424
-		if (! $this->database_name)
424
+		if (!$this->database_name)
425 425
 		{
426 426
 			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
427 427
 			$ret = mssql_query($query, $this->db);
@@ -436,10 +436,10 @@  discard block
 block discarded – undo
436 436
 		    @mssql_query($post_query, $this->db);
437 437
 		}
438 438
 
439
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
439
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
440 440
 		{
441 441
 			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
442
-			if (! $ret)
442
+			if (!$ret)
443 443
 			{
444 444
 				$result = mssql_query("SELECT @@ERROR as code", $this->db);
445 445
 				$row = mssql_fetch_array($result);
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 				if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
453 453
 				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
454 454
 			}
455
-			$this->lastquery=$query;
455
+			$this->lastquery = $query;
456 456
 			$this->_results = $ret;
457 457
 		}
458 458
 
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
 	function fetch_object($resultset)
469 469
 	{
470 470
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
471
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
471
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
472 472
 		return mssql_fetch_object($resultset);
473 473
 	}
474 474
 
@@ -481,7 +481,7 @@  discard block
 block discarded – undo
481 481
 	function fetch_array($resultset)
482 482
 	{
483 483
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
484
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
484
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
485 485
 		return mssql_fetch_array($resultset);
486 486
 	}
487 487
 
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 	function fetch_row($resultset)
496 496
 	{
497 497
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
498
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
498
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
499 499
 		return @mssql_fetch_row($resultset);
500 500
 	}
501 501
 
@@ -509,7 +509,7 @@  discard block
 block discarded – undo
509 509
 	function num_rows($resultset)
510 510
 	{
511 511
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
512
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
512
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
513 513
 		return mssql_num_rows($resultset);
514 514
 	}
515 515
 
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
 	function affected_rows($resultset)
524 524
 	{
525 525
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
526
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
526
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
527 527
 		// mssql necessite un link de base pour cette fonction contrairement
528 528
 		// a pqsql qui prend un resultset
529 529
 		$rsRows = mssql_query("select @@rowcount as rows", $this->db);
@@ -538,10 +538,10 @@  discard block
 block discarded – undo
538 538
 	 *	@param  resource	$resultset   Curseur de la requete voulue
539 539
 	 *	@return	bool
540 540
 	 */
541
-	function free($resultset=null)
541
+	function free($resultset = null)
542 542
 	{
543 543
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
544
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
544
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
545 545
 		// Si resultset en est un, on libere la memoire
546 546
 		if (is_resource($resultset)) mssql_free_result($resultset);
547 547
 	}
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 */
568 568
 	function idate($param)
569 569
 	{
570
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
570
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
571 571
 	}
572 572
 
573 573
 	/**
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 	 */
578 578
 	function errno()
579 579
 	{
580
-		if (! $this->connected)
580
+		if (!$this->connected)
581 581
 		{
582 582
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
583 583
 			return 'DB_ERROR_FAILED_TO_CONNECT';
@@ -618,8 +618,8 @@  discard block
 block discarded – undo
618 618
 			{
619 619
 				return $errorcode_map[$this->lasterrno];
620 620
 			}
621
-			$errno=$this->lasterrno;
622
-			return ($errno?'DB_ERROR_'.$errno:'0');
621
+			$errno = $this->lasterrno;
622
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
623 623
 		}
624 624
 	}
625 625
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	 */
631 631
 	function error()
632 632
 	{
633
-		if (! $this->connected) {
633
+		if (!$this->connected) {
634 634
 			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
635 635
 			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
636 636
 		}
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 	 * @param	string	$fieldid	Field name
647 647
 	 * @return  int     			Id of row or -1 on error
648 648
 	 */
649
-	function last_insert_id($tab,$fieldid='rowid')
649
+	function last_insert_id($tab, $fieldid = 'rowid')
650 650
 	{
651 651
 		$res = $this->query("SELECT @@IDENTITY as id");
652 652
 		if ($res && $data = $this->fetch_array($res))
@@ -667,18 +667,18 @@  discard block
 block discarded – undo
667 667
      *  @param	int		$withQuotes     Return string with quotes
668 668
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
669 669
 	 */
670
-	function encrypt($fieldorvalue, $withQuotes=0)
670
+	function encrypt($fieldorvalue, $withQuotes = 0)
671 671
 	{
672 672
 		global $conf;
673 673
 
674 674
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
675
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
675
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
676 676
 
677 677
 		//Encryption key
678
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
678
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
679 679
 
680 680
 		$return = $fieldorvalue;
681
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
681
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
682 682
 	}
683 683
 
684 684
 	/**
@@ -692,10 +692,10 @@  discard block
 block discarded – undo
692 692
 		global $conf;
693 693
 
694 694
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
695
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
695
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
696 696
 
697 697
 		//Encryption key
698
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
698
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
699 699
 
700 700
 		$return = $value;
701 701
 		return $return;
@@ -709,10 +709,10 @@  discard block
 block discarded – undo
709 709
 	 */
710 710
 	function DDLGetConnectId()
711 711
 	{
712
-		$resql=$this->query('SELECT CONNECTION_ID()');
712
+		$resql = $this->query('SELECT CONNECTION_ID()');
713 713
 		if ($resql)
714 714
 		{
715
-            $row=$this->fetch_row($resql);
715
+            $row = $this->fetch_row($resql);
716 716
             return $row[0];
717 717
 		}
718 718
 		else return '?';
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
 	 * 	@param	string	$owner			Username of database owner
730 730
 	 * 	@return	false|resource|true		resource defined if OK, false if KO
731 731
 	 */
732
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
732
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
733 733
 	{
734 734
         /*if (empty($charset))   $charset=$this->forcecharset;
735 735
         if (empty($collation)) $collation=$this->forcecollate;
@@ -738,18 +738,18 @@  discard block
 block discarded – undo
738 738
 		$sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
739 739
         //TODO: Check if we need to force a charset
740 740
 		//$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
741
-		$ret=$this->query($sql);
741
+		$ret = $this->query($sql);
742 742
 
743 743
 		$this->select_db($database);
744
-		$sql="CREATE USER [$owner] FOR LOGIN [$owner]";
745
-		mssql_query($sql,$this->db);
746
-		$sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
747
-		mssql_query($sql,$this->db);
744
+		$sql = "CREATE USER [$owner] FOR LOGIN [$owner]";
745
+		mssql_query($sql, $this->db);
746
+		$sql = "ALTER ROLE [db_owner] ADD MEMBER [$owner]";
747
+		mssql_query($sql, $this->db);
748 748
 
749
-		$sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
750
-	    @mssql_query($sql,$this->db);
751
-	    $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
752
-	    @mssql_query($sql,$this->db);
749
+		$sql = "ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
750
+	    @mssql_query($sql, $this->db);
751
+	    $sql = "ALTER DATABASE [$database] SET ANSI_NULL ON;";
752
+	    @mssql_query($sql, $this->db);
753 753
 
754 754
 	    return $ret;
755 755
 	}
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
762 762
      *  @return	array					List of tables in an array
763 763
 	 */
764
-	function DDLListTables($database,$table='')
764
+	function DDLListTables($database, $table = '')
765 765
 	{
766 766
 		$this->_results = mssql_list_tables($database, $this->db);
767 767
 		return $this->_results;
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 		// TODO: Implement
781 781
 		// May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
782 782
 
783
-		$infotables=array();
783
+		$infotables = array();
784 784
 		return $infotables;
785 785
 	}
786 786
 
@@ -796,68 +796,68 @@  discard block
 block discarded – undo
796 796
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
797 797
 	 *	@return	    int						<0 if KO, >=0 if OK
798 798
 	 */
799
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
799
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
800 800
 	{
801 801
 		// FIXME: $fulltext_keys parameter is unused
802 802
 
803 803
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
804 804
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
805 805
 		$sql = "create table ".$table."(";
806
-		$i=0;
807
-		foreach($fields as $field_name => $field_desc)
806
+		$i = 0;
807
+		foreach ($fields as $field_name => $field_desc)
808 808
 		{
809 809
 			$sqlfields[$i] = $field_name." ";
810 810
 			$sqlfields[$i]  .= $field_desc['type'];
811
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
811
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
812 812
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
813
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
813
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
814 814
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
815
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
815
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
816 816
 			{
817
-				if(preg_match("/null/i",$field_desc['default']))
817
+				if (preg_match("/null/i", $field_desc['default']))
818 818
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
819 819
 				else
820 820
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
821 821
 			}
822
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
822
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
823 823
 			$sqlfields[$i]  .= " ".$field_desc['null'];
824 824
 
825
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
825
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
826 826
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
827 827
 			$i++;
828 828
 		}
829
-		if($primary_key != "")
829
+		if ($primary_key != "")
830 830
 		$pk = "primary key(".$primary_key.")";
831 831
 
832
-		if(is_array($unique_keys))
832
+		if (is_array($unique_keys))
833 833
 		{
834 834
 			$i = 0;
835
-			foreach($unique_keys as $key => $value)
835
+			foreach ($unique_keys as $key => $value)
836 836
 			{
837 837
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
838 838
 				$i++;
839 839
 			}
840 840
 		}
841
-		if(is_array($keys))
841
+		if (is_array($keys))
842 842
 		{
843 843
 			$i = 0;
844
-			foreach($keys as $key => $value)
844
+			foreach ($keys as $key => $value)
845 845
 			{
846 846
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
847 847
 				$i++;
848 848
 			}
849 849
 		}
850
-		$sql .= implode(',',$sqlfields);
851
-		if($primary_key != "")
850
+		$sql .= implode(',', $sqlfields);
851
+		if ($primary_key != "")
852 852
 		$sql .= ",".$pk;
853
-		if(is_array($unique_keys))
854
-		$sql .= ",".implode(',',$sqluq);
855
-		if(is_array($keys))
856
-		$sql .= ",".implode(',',$sqlk);
857
-		$sql .=") type=".$type;
853
+		if (is_array($unique_keys))
854
+		$sql .= ",".implode(',', $sqluq);
855
+		if (is_array($keys))
856
+		$sql .= ",".implode(',', $sqlk);
857
+		$sql .= ") type=".$type;
858 858
 
859 859
 		dol_syslog($sql);
860
-		if(! $this -> query($sql))
860
+		if (!$this -> query($sql))
861 861
 		return -1;
862 862
 		else
863 863
 		return 1;
@@ -870,9 +870,9 @@  discard block
 block discarded – undo
870 870
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
871 871
 	 *	@return	false|resource|true	Resource
872 872
 	 */
873
-	function DDLDescTable($table,$field="")
873
+	function DDLDescTable($table, $field = "")
874 874
 	{
875
-		$sql="DESC ".$table." ".$field;
875
+		$sql = "DESC ".$table." ".$field;
876 876
 
877 877
 		dol_syslog($sql);
878 878
 		$this->_results = $this->query($sql);
@@ -888,28 +888,28 @@  discard block
 block discarded – undo
888 888
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
889 889
 	 *	@return	int							<0 if KO, >0 if OK
890 890
 	 */
891
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
891
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
892 892
 	{
893 893
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
894 894
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
895
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
895
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
896 896
 		$sql .= $field_desc['type'];
897
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
897
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
898 898
 		$sql  .= "(".$field_desc['value'].")";
899
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
899
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
900 900
 		$sql  .= " ".$field_desc['attribute'];
901
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
901
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
902 902
 		$sql  .= " ".$field_desc['null'];
903
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
904
-		if(preg_match("/null/i",$field_desc['default']))
903
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
904
+		if (preg_match("/null/i", $field_desc['default']))
905 905
 		$sql  .= " default ".$field_desc['default'];
906 906
 		else
907 907
 		$sql  .= " default '".$field_desc['default']."'";
908
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
908
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
909 909
 		$sql  .= " ".$field_desc['extra'];
910 910
 		$sql .= " ".$field_position;
911 911
 
912
-		if(! $this -> query($sql))
912
+		if (!$this -> query($sql))
913 913
 		return -1;
914 914
 		else
915 915
 		return 1;
@@ -923,16 +923,16 @@  discard block
 block discarded – undo
923 923
 	 *	@param	string	$field_desc 		Array with description of field format
924 924
 	 *	@return	int							<0 if KO, >0 if OK
925 925
 	 */
926
-	function DDLUpdateField($table,$field_name,$field_desc)
926
+	function DDLUpdateField($table, $field_name, $field_desc)
927 927
 	{
928 928
 		$sql = "ALTER TABLE ".$table;
929 929
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
930 930
 		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
931
-			$sql.="(".$field_desc['value'].")";
931
+			$sql .= "(".$field_desc['value'].")";
932 932
 		}
933 933
 
934
-		dol_syslog($sql,LOG_DEBUG);
935
-		if (! $this->query($sql))
934
+		dol_syslog($sql, LOG_DEBUG);
935
+		if (!$this->query($sql))
936 936
 		return -1;
937 937
 		else
938 938
 		return 1;
@@ -945,13 +945,13 @@  discard block
 block discarded – undo
945 945
 	 *	@param	string	$field_name 	Name of field to drop
946 946
 	 *	@return	int						<0 if KO, >0 if OK
947 947
 	 */
948
-	function DDLDropField($table,$field_name)
948
+	function DDLDropField($table, $field_name)
949 949
 	{
950
-		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
951
-		dol_syslog($sql,LOG_DEBUG);
952
-		if (! $this->query($sql))
950
+		$sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
951
+		dol_syslog($sql, LOG_DEBUG);
952
+		if (!$this->query($sql))
953 953
 		{
954
-			$this->error=$this->lasterror();
954
+			$this->error = $this->lasterror();
955 955
 			return -1;
956 956
 		}
957 957
 		else return 1;
@@ -966,12 +966,12 @@  discard block
 block discarded – undo
966 966
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
967 967
 	 *	@return	int									<0 if KO, >=0 if OK
968 968
 	 */
969
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
969
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
970 970
 	{
971 971
 	    $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
972
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
973
-        $resql=$this->query($sql);
974
-        if (! $resql)
972
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
973
+        $resql = $this->query($sql);
974
+        if (!$resql)
975 975
         {
976 976
             if ($this->lasterrno != '15025')
977 977
             {
@@ -983,9 +983,9 @@  discard block
 block discarded – undo
983 983
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
984 984
             }
985 985
         }
986
-        $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
987
-        $ressql=$this->query($sql);
988
-        if (! $ressql)
986
+        $sql = "SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
987
+        $ressql = $this->query($sql);
988
+        if (!$ressql)
989 989
         {
990 990
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
991 991
             return -1;
@@ -995,9 +995,9 @@  discard block
 block discarded – undo
995 995
             if ($num)
996 996
             {
997 997
                 $this->select_db($dolibarr_main_db_name);
998
-                $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
998
+                $sql = "CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
999 999
                 $this->query($sql);
1000
-                $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1000
+                $sql = "ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1001 1001
                 $this->query($sql);
1002 1002
             }
1003 1003
         }
@@ -1037,12 +1037,12 @@  discard block
 block discarded – undo
1037 1037
 	 */
1038 1038
 	function getDefaultCollationDatabase()
1039 1039
 	{
1040
-		$resql=$this->query("SELECT SERVERPROPERTY('collation')");
1040
+		$resql = $this->query("SELECT SERVERPROPERTY('collation')");
1041 1041
 		if (!$resql)
1042 1042
 		{
1043 1043
 			return $this->forcecollate;
1044 1044
 		}
1045
-		$liste=$this->fetch_array($resql);
1045
+		$liste = $this->fetch_array($resql);
1046 1046
 		return $liste['computed'];
1047 1047
 	}
1048 1048
 
@@ -1091,13 +1091,13 @@  discard block
 block discarded – undo
1091 1091
 	 * @param	string	$filter		Filter list on a particular value
1092 1092
 	 * @return	array				Array of key-values (key=>value)
1093 1093
 	 */
1094
-	function getServerParametersValues($filter='')
1094
+	function getServerParametersValues($filter = '')
1095 1095
 	{
1096 1096
 		// FIXME: Dummy method
1097 1097
 		// TODO: Implement
1098 1098
 		// May help: SELECT SERVERPROPERTY
1099 1099
 
1100
-		$result=array();
1100
+		$result = array();
1101 1101
 		return $result;
1102 1102
 	}
1103 1103
 
@@ -1107,7 +1107,7 @@  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 1112
 		// FIXME: Dummy method
1113 1113
 		// TODO: Implement
@@ -1134,23 +1134,23 @@  discard block
 block discarded – undo
1134 1134
 	 * @param      mixed   $fields     String for one field or array of string for multiple field
1135 1135
 	 * @return false|object
1136 1136
 	 */
1137
-	function GetFieldInformation($table,$fields) {
1138
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1137
+	function GetFieldInformation($table, $fields) {
1138
+	    $sql = "SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1139 1139
 	    if (is_array($fields))
1140 1140
 	    {
1141
-	        $where=" IN ('".implode("','",$fields)."')";
1141
+	        $where = " IN ('".implode("','", $fields)."')";
1142 1142
 	    }
1143 1143
 	    else
1144 1144
 	    {
1145
-	        $where="='".$this->escape($fields)."'";
1145
+	        $where = "='".$this->escape($fields)."'";
1146 1146
 	    }
1147
-	    $result=array();
1148
-	    $ret=mssql_query($sql.$where,$this->db);
1147
+	    $result = array();
1148
+	    $ret = mssql_query($sql.$where, $this->db);
1149 1149
 	    if ($ret)
1150 1150
 	    {
1151
-	        while($obj=mssql_fetch_object($ret))
1151
+	        while ($obj = mssql_fetch_object($ret))
1152 1152
 	        {
1153
-	            $result[]=$obj;
1153
+	            $result[] = $obj;
1154 1154
 	        }
1155 1155
 	    }
1156 1156
 	    else
Please login to merge, or discard this patch.
Braces   +102 added lines, -89 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;
@@ -165,7 +162,9 @@  discard block
 block discarded – undo
165 162
 	{
166 163
 		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
167 164
 		$newhost=$host;
168
-		if ($port) $newhost.=':'.$port;
165
+		if ($port) {
166
+			$newhost.=':'.$port;
167
+		}
169 168
 		$this->db  = @mssql_connect($newhost, $login, $passwd);
170 169
 		//force les enregistrement en latin1 si la base est en utf8 par defaut
171 170
 		// Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
@@ -196,8 +195,9 @@  discard block
 block discarded – undo
196 195
 		{
197 196
             $version=$this->fetch_array($resql);
198 197
             return $version['computed'];
198
+		} else {
199
+			return '';
199 200
 		}
200
-		else return '';
201 201
 	}
202 202
 
203 203
 	/**
@@ -220,7 +220,9 @@  discard block
 block discarded – undo
220 220
     {
221 221
         if ($this->db)
222 222
         {
223
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
223
+          if ($this->transaction_opened > 0) {
224
+          	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
225
+          }
224 226
           $this->connected=false;
225 227
           return mssql_close($this->db);
226 228
         }
@@ -248,8 +250,7 @@  discard block
 block discarded – undo
248 250
 				dol_syslog("BEGIN Transaction",LOG_DEBUG);
249 251
 			}
250 252
 			return $ret;
251
-		}
252
-		else
253
+		} else
253 254
 		{
254 255
 			return true;
255 256
 		}
@@ -274,13 +275,11 @@  discard block
 block discarded – undo
274 275
 			{
275 276
 				dol_syslog("COMMIT Transaction",LOG_DEBUG);
276 277
 				return true;
277
-			}
278
-			else
278
+			} else
279 279
 			{
280 280
 				return false;
281 281
 			}
282
-		}
283
-		elseif ($this->transaction_opened > 1)
282
+		} elseif ($this->transaction_opened > 1)
284 283
 		{
285 284
 			return true;
286 285
 		}
@@ -304,8 +303,7 @@  discard block
 block discarded – undo
304 303
 			$ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
305 304
 			dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
306 305
 			return $ret;
307
-		}
308
-		elseif ($this->transaction_opened > 1)
306
+		} elseif ($this->transaction_opened > 1)
309 307
 		{
310 308
 			return true;
311 309
 		}
@@ -326,7 +324,9 @@  discard block
 block discarded – undo
326 324
 	{
327 325
 		$query = trim($query);
328 326
 
329
-		if (preg_match('/^--/',$query)) return true;
327
+		if (preg_match('/^--/',$query)) {
328
+			return true;
329
+		}
330 330
 
331 331
 		// Conversion syntaxe MySql vers MSDE.
332 332
 		$query = str_ireplace("now()", "getdate()", $query);
@@ -360,11 +360,11 @@  discard block
 block discarded – undo
360 360
                             $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
361 361
                         }
362 362
                     }
363
-                    if (! empty($query_comp))
364
-                        $query.=" WHERE ".implode(" AND ",$query_comp);
363
+                    if (! empty($query_comp)) {
364
+                                            $query.=" WHERE ".implode(" AND ",$query_comp);
365
+                    }
365 366
                 }
366
-    		}
367
-    		else
367
+    		} else
368 368
     		{
369 369
     		    if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
370 370
     		    {
@@ -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;
@@ -543,7 +546,9 @@  discard block
 block discarded – undo
543 546
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
544 547
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
545 548
 		// Si resultset en est un, on libere la memoire
546
-		if (is_resource($resultset)) mssql_free_result($resultset);
549
+		if (is_resource($resultset)) {
550
+			mssql_free_result($resultset);
551
+		}
547 552
 	}
548 553
 
549 554
 	/**
@@ -581,8 +586,7 @@  discard block
 block discarded – undo
581 586
 		{
582 587
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
583 588
 			return 'DB_ERROR_FAILED_TO_CONNECT';
584
-		}
585
-		else
589
+		} else
586 590
 		{
587 591
 			// Constants to convert a MSSql error code to a generic Dolibarr error code
588 592
 			$errorcode_map = array(
@@ -633,8 +637,7 @@  discard block
 block discarded – undo
633 637
 		if (! $this->connected) {
634 638
 			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
635 639
 			return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
636
-		}
637
-		else {
640
+		} else {
638 641
 			return mssql_get_last_message();
639 642
 		}
640 643
 	}
@@ -652,8 +655,7 @@  discard block
 block discarded – undo
652 655
 		if ($res && $data = $this->fetch_array($res))
653 656
 		{
654 657
 			return $data["id"];
655
-		}
656
-		else
658
+		} else
657 659
 		{
658 660
 			return -1;
659 661
 		}
@@ -714,8 +716,9 @@  discard block
 block discarded – undo
714 716
 		{
715 717
             $row=$this->fetch_row($resql);
716 718
             return $row[0];
719
+		} else {
720
+			return '?';
717 721
 		}
718
-		else return '?';
719 722
 	}
720 723
 
721 724
 	/**
@@ -808,26 +811,27 @@  discard block
 block discarded – undo
808 811
 		{
809 812
 			$sqlfields[$i] = $field_name." ";
810 813
 			$sqlfields[$i]  .= $field_desc['type'];
811
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
812
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
813
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
814
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
815
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
814
+			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
815
+						$sqlfields[$i]  .= "(".$field_desc['value'].")";
816
+			} else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
817
+						$sqlfields[$i]  .= " ".$field_desc['attribute'];
818
+			} else if( preg_match("/^[^\s]/i",$field_desc['default']))
816 819
 			{
817
-				if(preg_match("/null/i",$field_desc['default']))
818
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
819
-				else
820
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
820
+				if(preg_match("/null/i",$field_desc['default'])) {
821
+								$sqlfields[$i]  .= " default ".$field_desc['default'];
822
+				} else {
823
+								$sqlfields[$i]  .= " default '".$field_desc['default']."'";
824
+				}
825
+			} else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
826
+						$sqlfields[$i]  .= " ".$field_desc['null'];
827
+			} else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
828
+						$sqlfields[$i]  .= " ".$field_desc['extra'];
821 829
 			}
822
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
823
-			$sqlfields[$i]  .= " ".$field_desc['null'];
824
-
825
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
826
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
827 830
 			$i++;
828 831
 		}
829
-		if($primary_key != "")
830
-		$pk = "primary key(".$primary_key.")";
832
+		if($primary_key != "") {
833
+				$pk = "primary key(".$primary_key.")";
834
+		}
831 835
 
832 836
 		if(is_array($unique_keys))
833 837
 		{
@@ -848,19 +852,23 @@  discard block
 block discarded – undo
848 852
 			}
849 853
 		}
850 854
 		$sql .= implode(',',$sqlfields);
851
-		if($primary_key != "")
852
-		$sql .= ",".$pk;
853
-		if(is_array($unique_keys))
854
-		$sql .= ",".implode(',',$sqluq);
855
-		if(is_array($keys))
856
-		$sql .= ",".implode(',',$sqlk);
855
+		if($primary_key != "") {
856
+				$sql .= ",".$pk;
857
+		}
858
+		if(is_array($unique_keys)) {
859
+				$sql .= ",".implode(',',$sqluq);
860
+		}
861
+		if(is_array($keys)) {
862
+				$sql .= ",".implode(',',$sqlk);
863
+		}
857 864
 		$sql .=") type=".$type;
858 865
 
859 866
 		dol_syslog($sql);
860
-		if(! $this -> query($sql))
861
-		return -1;
862
-		else
863
-		return 1;
867
+		if(! $this -> query($sql)) {
868
+				return -1;
869
+		} else {
870
+				return 1;
871
+		}
864 872
 	}
865 873
 
866 874
 	/**
@@ -894,25 +902,31 @@  discard block
 block discarded – undo
894 902
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
895 903
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
896 904
 		$sql .= $field_desc['type'];
897
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
898
-		$sql  .= "(".$field_desc['value'].")";
899
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
900
-		$sql  .= " ".$field_desc['attribute'];
901
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
902
-		$sql  .= " ".$field_desc['null'];
903
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
904
-		if(preg_match("/null/i",$field_desc['default']))
905
+		if( preg_match("/^[^\s]/i",$field_desc['value'])) {
906
+				$sql  .= "(".$field_desc['value'].")";
907
+		}
908
+		if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
909
+				$sql  .= " ".$field_desc['attribute'];
910
+		}
911
+		if( preg_match("/^[^\s]/i",$field_desc['null'])) {
912
+				$sql  .= " ".$field_desc['null'];
913
+		}
914
+		if( preg_match("/^[^\s]/i",$field_desc['default'])) {
915
+				if(preg_match("/null/i",$field_desc['default']))
905 916
 		$sql  .= " default ".$field_desc['default'];
906
-		else
907
-		$sql  .= " default '".$field_desc['default']."'";
908
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
909
-		$sql  .= " ".$field_desc['extra'];
917
+		} else {
918
+				$sql  .= " default '".$field_desc['default']."'";
919
+		}
920
+		if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
921
+				$sql  .= " ".$field_desc['extra'];
922
+		}
910 923
 		$sql .= " ".$field_position;
911 924
 
912
-		if(! $this -> query($sql))
913
-		return -1;
914
-		else
915
-		return 1;
925
+		if(! $this -> query($sql)) {
926
+				return -1;
927
+		} else {
928
+				return 1;
929
+		}
916 930
 	}
917 931
 
918 932
 	/**
@@ -932,10 +946,11 @@  discard block
 block discarded – undo
932 946
 		}
933 947
 
934 948
 		dol_syslog($sql,LOG_DEBUG);
935
-		if (! $this->query($sql))
936
-		return -1;
937
-		else
938
-		return 1;
949
+		if (! $this->query($sql)) {
950
+				return -1;
951
+		} else {
952
+				return 1;
953
+		}
939 954
 	}
940 955
 
941 956
 	/**
@@ -953,8 +968,9 @@  discard block
 block discarded – undo
953 968
 		{
954 969
 			$this->error=$this->lasterror();
955 970
 			return -1;
971
+		} else {
972
+			return 1;
956 973
 		}
957
-		else return 1;
958 974
 	}
959 975
 
960 976
 	/**
@@ -976,8 +992,7 @@  discard block
 block discarded – undo
976 992
             if ($this->lasterrno != '15025')
977 993
             {
978 994
 	            return -1;
979
-            }
980
-            else
995
+            } else
981 996
 			{
982 997
             	// If user already exists, we continue to set permissions
983 998
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -989,8 +1004,7 @@  discard block
 block discarded – undo
989 1004
         {
990 1005
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
991 1006
             return -1;
992
-        }
993
-        else
1007
+        } else
994 1008
         {
995 1009
             if ($num)
996 1010
             {
@@ -1139,8 +1153,7 @@  discard block
 block discarded – undo
1139 1153
 	    if (is_array($fields))
1140 1154
 	    {
1141 1155
 	        $where=" IN ('".implode("','",$fields)."')";
1142
-	    }
1143
-	    else
1156
+	    } else
1144 1157
 	    {
1145 1158
 	        $where="='".$this->escape($fields)."'";
1146 1159
 	    }
@@ -1152,9 +1165,9 @@  discard block
 block discarded – undo
1152 1165
 	        {
1153 1166
 	            $result[]=$obj;
1154 1167
 	        }
1168
+	    } else {
1169
+	    	        return false;
1155 1170
 	    }
1156
-	    else
1157
-	        return false;
1158 1171
 
1159 1172
 	    return $result;
1160 1173
 	}
Please login to merge, or discard this patch.
htdocs/core/db/mysqli.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -233,7 +233,7 @@
 block discarded – undo
233 233
      * 	@param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
234 234
      * 									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.
235 235
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
236
-     *	@return	bool|mysqli_result		Resultset of answer
236
+     *	@return	mysqli_result|null		Resultset of answer
237 237
      */
238 238
     function query($query,$usesavepoint=0,$type='auto')
239 239
     {
Please login to merge, or discard this patch.
Indentation   +831 added lines, -831 removed lines patch added patch discarded remove patch
@@ -34,16 +34,16 @@  discard block
 block discarded – undo
34 34
 {
35 35
 	/** @var mysqli Database object */
36 36
 	public $db;
37
-    //! Database type
38
-    public $type='mysqli';
39
-    //! Database label
40
-    const LABEL='MySQL or MariaDB';
41
-    //! Version min database
42
-    const VERSIONMIN='5.0.3';
37
+	//! Database type
38
+	public $type='mysqli';
39
+	//! Database label
40
+	const LABEL='MySQL or MariaDB';
41
+	//! Version min database
42
+	const VERSIONMIN='5.0.3';
43 43
 	/** @var mysqli_result Resultset of last query */
44 44
 	private $_results;
45 45
 
46
-    /**
46
+	/**
47 47
 	 *	Constructor.
48 48
 	 *	This create an opened connexion to a database server and eventually to a database
49 49
 	 *
@@ -53,38 +53,38 @@  discard block
 block discarded – undo
53 53
 	 *	@param	    string	$pass		Mot de passe
54 54
 	 *	@param	    string	$name		Nom de la database
55 55
 	 *	@param	    int		$port		Port of database server
56
-     */
57
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
58
-    {
59
-        global $conf,$langs;
60
-
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;
64
-
65
-        $this->database_user=$user;
66
-        $this->database_host=$host;
67
-        $this->database_port=$port;
68
-
69
-        $this->transaction_opened=0;
70
-
71
-        //print "Name DB: $host,$user,$pass,$name<br>";
72
-
73
-        if (! class_exists('mysqli'))
74
-        {
75
-            $this->connected = false;
76
-            $this->ok = false;
77
-            $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
78
-            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);
79
-        }
80
-
81
-        if (! $host)
82
-        {
83
-            $this->connected = false;
84
-            $this->ok = false;
85
-            $this->error=$langs->trans("ErrorWrongHostParameter");
86
-            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
87
-        }
56
+	 */
57
+	function __construct($type, $host, $user, $pass, $name='', $port=0)
58
+	{
59
+		global $conf,$langs;
60
+
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;
64
+
65
+		$this->database_user=$user;
66
+		$this->database_host=$host;
67
+		$this->database_port=$port;
68
+
69
+		$this->transaction_opened=0;
70
+
71
+		//print "Name DB: $host,$user,$pass,$name<br>";
72
+
73
+		if (! class_exists('mysqli'))
74
+		{
75
+			$this->connected = false;
76
+			$this->ok = false;
77
+			$this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
78
+			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);
79
+		}
80
+
81
+		if (! $host)
82
+		{
83
+			$this->connected = false;
84
+			$this->ok = false;
85
+			$this->error=$langs->trans("ErrorWrongHostParameter");
86
+			dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
87
+		}
88 88
 
89 89
 		// Try server connection
90 90
 		// We do not try to connect to database, only to server. Connect to database is done later in constrcutor
@@ -101,61 +101,61 @@  discard block
 block discarded – undo
101 101
 		}
102 102
 
103 103
 		// If server connection is ok, we try to connect to the database
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
-                // If client connected with different charset than Dolibarr HTML output
113
-                $clientmustbe='';
114
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
115
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
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
+				// If client connected with different charset than Dolibarr HTML output
113
+				$clientmustbe='';
114
+				if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
115
+				if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
116 116
 				if ($this->db->character_set_name() != $clientmustbe) {
117 117
 					$this->db->set_charset($clientmustbe);
118 118
 				}
119
-            }
120
-            else
121
-            {
122
-                $this->database_selected = false;
123
-                $this->database_name = '';
124
-                $this->ok = false;
125
-                $this->error=$this->error();
126
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
127
-            }
128
-        }
129
-        else
130
-        {
131
-            // Pas de selection de base demandee, ok ou ko
132
-            $this->database_selected = false;
133
-
134
-            if ($this->connected)
135
-            {
136
-                // If client connected with different charset than Dolibarr HTML output
137
-                $clientmustbe='';
138
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
139
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
119
+			}
120
+			else
121
+			{
122
+				$this->database_selected = false;
123
+				$this->database_name = '';
124
+				$this->ok = false;
125
+				$this->error=$this->error();
126
+				dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
127
+			}
128
+		}
129
+		else
130
+		{
131
+			// Pas de selection de base demandee, ok ou ko
132
+			$this->database_selected = false;
133
+
134
+			if ($this->connected)
135
+			{
136
+				// If client connected with different charset than Dolibarr HTML output
137
+				$clientmustbe='';
138
+				if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
139
+				if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
140 140
 				if ($this->db->character_set_name() != $clientmustbe) {
141 141
 					$this->db->set_charset($clientmustbe);
142 142
 				}
143
-            }
144
-        }
145
-    }
146
-
147
-
148
-    /**
149
-     *  Convert a SQL request in Mysql syntax to native syntax
150
-     *
151
-     *  @param     string	$line   SQL request line to convert
152
-     *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
153
-     *  @return    string   		SQL request line converted
154
-     */
155
-    static function convertSQLFromMysql($line,$type='ddl')
156
-    {
157
-        return $line;
158
-    }
143
+			}
144
+		}
145
+	}
146
+
147
+
148
+	/**
149
+	 *  Convert a SQL request in Mysql syntax to native syntax
150
+	 *
151
+	 *  @param     string	$line   SQL request line to convert
152
+	 *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
153
+	 *  @return    string   		SQL request line converted
154
+	 */
155
+	static function convertSQLFromMysql($line,$type='ddl')
156
+	{
157
+		return $line;
158
+	}
159 159
 
160 160
 	/**
161 161
 	 *	Select a database
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
 	 *	@param	    string	$database	Name of database
164 164
 	 *	@return	    boolean  		    true if OK, false if KO
165 165
 	 */
166
-    function select_db($database)
167
-    {
168
-        dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
169
-	    return $this->db->select_db($database);
170
-    }
166
+	function select_db($database)
167
+	{
168
+		dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
169
+		return $this->db->select_db($database);
170
+	}
171 171
 
172 172
 
173 173
 	/**
@@ -188,360 +188,360 @@  discard block
 block discarded – undo
188 188
 		return new mysqli($host, $login, $passwd, $name, $port);
189 189
 	}
190 190
 
191
-    /**
191
+	/**
192 192
 	 *	Return version of database server
193 193
 	 *
194 194
 	 *	@return	        string      Version string
195
-     */
196
-    function getVersion()
197
-    {
198
-        return $this->db->server_info;
199
-    }
200
-
201
-    /**
202
-     *	Return version of database client driver
203
-     *
204
-     *	@return	        string      Version string
205
-     */
195
+	 */
196
+	function getVersion()
197
+	{
198
+		return $this->db->server_info;
199
+	}
200
+
201
+	/**
202
+	 *	Return version of database client driver
203
+	 *
204
+	 *	@return	        string      Version string
205
+	 */
206 206
 	function getDriverInfo()
207 207
 	{
208 208
 		return $this->db->client_info;
209 209
 	}
210 210
 
211 211
 
212
-    /**
213
-     *  Close database connexion
214
-     *
215
-     *  @return     bool     True if disconnect successfull, false otherwise
216
-     *  @see        connect
217
-     */
218
-    function close()
219
-    {
220
-        if ($this->db)
221
-        {
222
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
223
-            $this->connected=false;
224
-            return $this->db->close();
225
-        }
226
-        return false;
227
-    }
228
-
229
-    /**
230
-     * 	Execute a SQL request and return the resultset
231
-     *
232
-     * 	@param	string	$query			SQL query string
233
-     * 	@param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
234
-     * 									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.
235
-     *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
236
-     *	@return	bool|mysqli_result		Resultset of answer
237
-     */
238
-    function query($query,$usesavepoint=0,$type='auto')
239
-    {
240
-    	global $conf;
241
-
242
-        $query = trim($query);
243
-
244
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
245
-
246
-        if (! $this->database_name)
247
-        {
248
-            // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
249
-            $ret = $this->db->query($query);
250
-        }
251
-        else
252
-        {
253
-            $ret = $this->db->query($query);
254
-        }
255
-
256
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
257
-        {
258
-            // Si requete utilisateur, on la sauvegarde ainsi que son resultset
259
-            if (! $ret)
260
-            {
261
-                $this->lastqueryerror = $query;
262
-                $this->lasterror = $this->error();
263
-                $this->lasterrno = $this->errno();
212
+	/**
213
+	 *  Close database connexion
214
+	 *
215
+	 *  @return     bool     True if disconnect successfull, false otherwise
216
+	 *  @see        connect
217
+	 */
218
+	function close()
219
+	{
220
+		if ($this->db)
221
+		{
222
+			if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
223
+			$this->connected=false;
224
+			return $this->db->close();
225
+		}
226
+		return false;
227
+	}
228
+
229
+	/**
230
+	 * 	Execute a SQL request and return the resultset
231
+	 *
232
+	 * 	@param	string	$query			SQL query string
233
+	 * 	@param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
234
+	 * 									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.
235
+	 *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
236
+	 *	@return	bool|mysqli_result		Resultset of answer
237
+	 */
238
+	function query($query,$usesavepoint=0,$type='auto')
239
+	{
240
+		global $conf;
241
+
242
+		$query = trim($query);
243
+
244
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
245
+
246
+		if (! $this->database_name)
247
+		{
248
+			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
249
+			$ret = $this->db->query($query);
250
+		}
251
+		else
252
+		{
253
+			$ret = $this->db->query($query);
254
+		}
255
+
256
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
257
+		{
258
+			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
259
+			if (! $ret)
260
+			{
261
+				$this->lastqueryerror = $query;
262
+				$this->lasterror = $this->error();
263
+				$this->lasterrno = $this->errno();
264 264
 
265 265
 				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
266
-                dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
267
-            }
268
-            $this->lastquery=$query;
269
-            $this->_results = $ret;
270
-        }
271
-
272
-        return $ret;
273
-    }
274
-
275
-    /**
276
-     *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
277
-     *
278
-     *	@param	mysqli_result	$resultset	Curseur de la requete voulue
279
-     *	@return	object|null					Object result line or null if KO or end of cursor
280
-     */
281
-    function fetch_object($resultset)
282
-    {
283
-        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
284
-        if (! is_object($resultset)) { $resultset=$this->_results; }
266
+				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
267
+			}
268
+			$this->lastquery=$query;
269
+			$this->_results = $ret;
270
+		}
271
+
272
+		return $ret;
273
+	}
274
+
275
+	/**
276
+	 *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
277
+	 *
278
+	 *	@param	mysqli_result	$resultset	Curseur de la requete voulue
279
+	 *	@return	object|null					Object result line or null if KO or end of cursor
280
+	 */
281
+	function fetch_object($resultset)
282
+	{
283
+		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
284
+		if (! is_object($resultset)) { $resultset=$this->_results; }
285 285
 		return $resultset->fetch_object();
286
-    }
287
-
288
-
289
-    /**
290
-     *	Return datas as an array
291
-     *
292
-     *	@param	mysqli_result	$resultset	Resultset of request
293
-     *	@return	array|null					Array or null if KO or end of cursor
294
-     */
295
-    function fetch_array($resultset)
296
-    {
297
-        // If resultset not provided, we take the last used by connexion
298
-        if (! is_object($resultset)) { $resultset=$this->_results; }
299
-        return $resultset->fetch_array();
300
-    }
301
-
302
-    /**
303
-     *	Return datas as an array
304
-     *
305
-     *	@param	mysqli_result	$resultset	Resultset of request
306
-     *	@return	array|null|0				Array or null if KO or end of cursor or 0 if resultset is bool
307
-     */
308
-    function fetch_row($resultset)
309
-    {
310
-        // If resultset not provided, we take the last used by connexion
311
-        if (! is_bool($resultset))
312
-        {
313
-            if (! is_object($resultset)) { $resultset=$this->_results; }
314
-            return $resultset->fetch_row();
315
-        }
316
-        else
317
-        {
318
-            // si le curseur est un booleen on retourne la valeur 0
319
-            return 0;
320
-        }
321
-    }
322
-
323
-    /**
324
-     *	Return number of lines for result of a SELECT
325
-     *
326
-     *	@param	mysqli_result	$resultset  Resulset of requests
327
-     *	@return	int				Nb of lines
328
-     *	@see    affected_rows
329
-     */
330
-    function num_rows($resultset)
331
-    {
332
-        // If resultset not provided, we take the last used by connexion
333
-        if (! is_object($resultset)) { $resultset=$this->_results; }
334
-        return $resultset->num_rows;
335
-    }
336
-
337
-    /**
338
-     *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
339
-     *
340
-     *	@param	mysqli_result	$resultset	Curseur de la requete voulue
341
-     *	@return int							Nombre de lignes
342
-     *	@see    num_rows
343
-     */
344
-    function affected_rows($resultset)
345
-    {
346
-        // If resultset not provided, we take the last used by connexion
347
-        if (! is_object($resultset)) { $resultset=$this->_results; }
348
-        // mysql necessite un link de base pour cette fonction contrairement
349
-        // a pqsql qui prend un resultset
350
-        return $this->db->affected_rows;
351
-    }
352
-
353
-
354
-    /**
355
-     *	Libere le dernier resultset utilise sur cette connexion
356
-     *
357
-     *	@param  mysqli_result	$resultset	Curseur de la requete voulue
358
-     *	@return	void
359
-     */
360
-    function free($resultset=null)
361
-    {
362
-        // If resultset not provided, we take the last used by connexion
363
-        if (! is_object($resultset)) { $resultset=$this->_results; }
364
-        // Si resultset en est un, on libere la memoire
365
-        if (is_object($resultset)) $resultset->free_result();
366
-    }
367
-
368
-    /**
369
-     *	Escape a string to insert data
370
-     *
371
-     *	@param	string	$stringtoencode		String to escape
372
-     *	@return	string						String escaped
373
-     */
374
-    function escape($stringtoencode)
375
-    {
376
-        return $this->db->real_escape_string($stringtoencode);
377
-    }
378
-
379
-    /**
380
-     *	Return generic error code of last operation.
381
-     *
382
-     *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
383
-     */
384
-    function errno()
385
-    {
386
-        if (! $this->connected) {
387
-            // Si il y a eu echec de connexion, $this->db n'est pas valide.
388
-            return 'DB_ERROR_FAILED_TO_CONNECT';
389
-        } else {
390
-            // Constants to convert a MySql error code to a generic Dolibarr error code
391
-            $errorcode_map = array(
392
-            1004 => 'DB_ERROR_CANNOT_CREATE',
393
-            1005 => 'DB_ERROR_CANNOT_CREATE',
394
-            1006 => 'DB_ERROR_CANNOT_CREATE',
395
-            1007 => 'DB_ERROR_ALREADY_EXISTS',
396
-            1008 => 'DB_ERROR_CANNOT_DROP',
397
-            1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
398
-            1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
399
-            1044 => 'DB_ERROR_ACCESSDENIED',
400
-            1046 => 'DB_ERROR_NODBSELECTED',
401
-            1048 => 'DB_ERROR_CONSTRAINT',
402
-            1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
403
-            1051 => 'DB_ERROR_NOSUCHTABLE',
404
-            1054 => 'DB_ERROR_NOSUCHFIELD',
405
-            1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
406
-            1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
407
-            1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
408
-            1064 => 'DB_ERROR_SYNTAX',
409
-            1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
410
-            1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
411
-            1091 => 'DB_ERROR_NOSUCHFIELD',
412
-            1100 => 'DB_ERROR_NOT_LOCKED',
413
-            1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
414
-            1146 => 'DB_ERROR_NOSUCHTABLE',
415
-            1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
416
-            1216 => 'DB_ERROR_NO_PARENT',
417
-            1217 => 'DB_ERROR_CHILD_EXISTS',
418
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
419
-            1451 => 'DB_ERROR_CHILD_EXISTS'
420
-            );
421
-
422
-            if (isset($errorcode_map[$this->db->errno])) {
423
-                return $errorcode_map[$this->db->errno];
424
-            }
425
-            $errno=$this->db->errno;
426
-            return ($errno?'DB_ERROR_'.$errno:'0');
427
-        }
428
-    }
429
-
430
-    /**
286
+	}
287
+
288
+
289
+	/**
290
+	 *	Return datas as an array
291
+	 *
292
+	 *	@param	mysqli_result	$resultset	Resultset of request
293
+	 *	@return	array|null					Array or null if KO or end of cursor
294
+	 */
295
+	function fetch_array($resultset)
296
+	{
297
+		// If resultset not provided, we take the last used by connexion
298
+		if (! is_object($resultset)) { $resultset=$this->_results; }
299
+		return $resultset->fetch_array();
300
+	}
301
+
302
+	/**
303
+	 *	Return datas as an array
304
+	 *
305
+	 *	@param	mysqli_result	$resultset	Resultset of request
306
+	 *	@return	array|null|0				Array or null if KO or end of cursor or 0 if resultset is bool
307
+	 */
308
+	function fetch_row($resultset)
309
+	{
310
+		// If resultset not provided, we take the last used by connexion
311
+		if (! is_bool($resultset))
312
+		{
313
+			if (! is_object($resultset)) { $resultset=$this->_results; }
314
+			return $resultset->fetch_row();
315
+		}
316
+		else
317
+		{
318
+			// si le curseur est un booleen on retourne la valeur 0
319
+			return 0;
320
+		}
321
+	}
322
+
323
+	/**
324
+	 *	Return number of lines for result of a SELECT
325
+	 *
326
+	 *	@param	mysqli_result	$resultset  Resulset of requests
327
+	 *	@return	int				Nb of lines
328
+	 *	@see    affected_rows
329
+	 */
330
+	function num_rows($resultset)
331
+	{
332
+		// If resultset not provided, we take the last used by connexion
333
+		if (! is_object($resultset)) { $resultset=$this->_results; }
334
+		return $resultset->num_rows;
335
+	}
336
+
337
+	/**
338
+	 *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
339
+	 *
340
+	 *	@param	mysqli_result	$resultset	Curseur de la requete voulue
341
+	 *	@return int							Nombre de lignes
342
+	 *	@see    num_rows
343
+	 */
344
+	function affected_rows($resultset)
345
+	{
346
+		// If resultset not provided, we take the last used by connexion
347
+		if (! is_object($resultset)) { $resultset=$this->_results; }
348
+		// mysql necessite un link de base pour cette fonction contrairement
349
+		// a pqsql qui prend un resultset
350
+		return $this->db->affected_rows;
351
+	}
352
+
353
+
354
+	/**
355
+	 *	Libere le dernier resultset utilise sur cette connexion
356
+	 *
357
+	 *	@param  mysqli_result	$resultset	Curseur de la requete voulue
358
+	 *	@return	void
359
+	 */
360
+	function free($resultset=null)
361
+	{
362
+		// If resultset not provided, we take the last used by connexion
363
+		if (! is_object($resultset)) { $resultset=$this->_results; }
364
+		// Si resultset en est un, on libere la memoire
365
+		if (is_object($resultset)) $resultset->free_result();
366
+	}
367
+
368
+	/**
369
+	 *	Escape a string to insert data
370
+	 *
371
+	 *	@param	string	$stringtoencode		String to escape
372
+	 *	@return	string						String escaped
373
+	 */
374
+	function escape($stringtoencode)
375
+	{
376
+		return $this->db->real_escape_string($stringtoencode);
377
+	}
378
+
379
+	/**
380
+	 *	Return generic error code of last operation.
381
+	 *
382
+	 *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
383
+	 */
384
+	function errno()
385
+	{
386
+		if (! $this->connected) {
387
+			// Si il y a eu echec de connexion, $this->db n'est pas valide.
388
+			return 'DB_ERROR_FAILED_TO_CONNECT';
389
+		} else {
390
+			// Constants to convert a MySql error code to a generic Dolibarr error code
391
+			$errorcode_map = array(
392
+			1004 => 'DB_ERROR_CANNOT_CREATE',
393
+			1005 => 'DB_ERROR_CANNOT_CREATE',
394
+			1006 => 'DB_ERROR_CANNOT_CREATE',
395
+			1007 => 'DB_ERROR_ALREADY_EXISTS',
396
+			1008 => 'DB_ERROR_CANNOT_DROP',
397
+			1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
398
+			1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
399
+			1044 => 'DB_ERROR_ACCESSDENIED',
400
+			1046 => 'DB_ERROR_NODBSELECTED',
401
+			1048 => 'DB_ERROR_CONSTRAINT',
402
+			1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
403
+			1051 => 'DB_ERROR_NOSUCHTABLE',
404
+			1054 => 'DB_ERROR_NOSUCHFIELD',
405
+			1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
406
+			1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
407
+			1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
408
+			1064 => 'DB_ERROR_SYNTAX',
409
+			1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
410
+			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
411
+			1091 => 'DB_ERROR_NOSUCHFIELD',
412
+			1100 => 'DB_ERROR_NOT_LOCKED',
413
+			1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
414
+			1146 => 'DB_ERROR_NOSUCHTABLE',
415
+			1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
416
+			1216 => 'DB_ERROR_NO_PARENT',
417
+			1217 => 'DB_ERROR_CHILD_EXISTS',
418
+			1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
419
+			1451 => 'DB_ERROR_CHILD_EXISTS'
420
+			);
421
+
422
+			if (isset($errorcode_map[$this->db->errno])) {
423
+				return $errorcode_map[$this->db->errno];
424
+			}
425
+			$errno=$this->db->errno;
426
+			return ($errno?'DB_ERROR_'.$errno:'0');
427
+		}
428
+	}
429
+
430
+	/**
431 431
 	 *	Return description of last error
432 432
 	 *
433 433
 	 *	@return	string		Error text
434
-     */
435
-    function error()
436
-    {
437
-        if (! $this->connected) {
438
-            // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
439
-            return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
440
-        }
441
-        else {
442
-            return $this->db->error;
443
-        }
444
-    }
445
-
446
-    /**
434
+	 */
435
+	function error()
436
+	{
437
+		if (! $this->connected) {
438
+			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
439
+			return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
440
+		}
441
+		else {
442
+			return $this->db->error;
443
+		}
444
+	}
445
+
446
+	/**
447 447
 	 * Get last ID after an insert INSERT
448 448
 	 *
449 449
 	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
450 450
 	 * @param	string	$fieldid	Field name
451 451
 	 * @return  int|string			Id of row
452
-     */
453
-    function last_insert_id($tab,$fieldid='rowid')
454
-    {
455
-        return $this->db->insert_id;
456
-    }
457
-
458
-    /**
459
-     *	Encrypt sensitive data in database
460
-     *  Warning: This function includes the escape, so it must use direct value
461
-     *
462
-     *	@param	string	$fieldorvalue	Field name or value to encrypt
463
-     * 	@param	int		$withQuotes		Return string with quotes
464
-     * 	@return	string					XXX(field) or XXX('value') or field or 'value'
465
-     *
466
-     */
467
-    function encrypt($fieldorvalue, $withQuotes=0)
468
-    {
469
-        global $conf;
470
-
471
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
472
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
473
-
474
-        //Encryption key
475
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
476
-
477
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
478
-
479
-        if ($cryptType && !empty($cryptKey))
480
-        {
481
-            if ($cryptType == 2)
482
-            {
483
-                $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
484
-            }
485
-            else if ($cryptType == 1)
486
-            {
487
-                $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
488
-            }
489
-        }
490
-
491
-        return $return;
492
-    }
493
-
494
-    /**
495
-     *	Decrypt sensitive data in database
496
-     *
497
-     *	@param	string	$value			Value to decrypt
498
-     * 	@return	string					Decrypted value if used
499
-     */
500
-    function decrypt($value)
501
-    {
502
-        global $conf;
503
-
504
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
505
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
506
-
507
-        //Encryption key
508
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
509
-
510
-        $return = $value;
511
-
512
-        if ($cryptType && !empty($cryptKey))
513
-        {
514
-            if ($cryptType == 2)
515
-            {
516
-                $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
517
-            }
518
-            else if ($cryptType == 1)
519
-            {
520
-                $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
521
-            }
522
-        }
523
-
524
-        return $return;
525
-    }
526
-
527
-
528
-    /**
452
+	 */
453
+	function last_insert_id($tab,$fieldid='rowid')
454
+	{
455
+		return $this->db->insert_id;
456
+	}
457
+
458
+	/**
459
+	 *	Encrypt sensitive data in database
460
+	 *  Warning: This function includes the escape, so it must use direct value
461
+	 *
462
+	 *	@param	string	$fieldorvalue	Field name or value to encrypt
463
+	 * 	@param	int		$withQuotes		Return string with quotes
464
+	 * 	@return	string					XXX(field) or XXX('value') or field or 'value'
465
+	 *
466
+	 */
467
+	function encrypt($fieldorvalue, $withQuotes=0)
468
+	{
469
+		global $conf;
470
+
471
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
472
+		$cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
473
+
474
+		//Encryption key
475
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
476
+
477
+		$return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
478
+
479
+		if ($cryptType && !empty($cryptKey))
480
+		{
481
+			if ($cryptType == 2)
482
+			{
483
+				$return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
484
+			}
485
+			else if ($cryptType == 1)
486
+			{
487
+				$return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
488
+			}
489
+		}
490
+
491
+		return $return;
492
+	}
493
+
494
+	/**
495
+	 *	Decrypt sensitive data in database
496
+	 *
497
+	 *	@param	string	$value			Value to decrypt
498
+	 * 	@return	string					Decrypted value if used
499
+	 */
500
+	function decrypt($value)
501
+	{
502
+		global $conf;
503
+
504
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
505
+		$cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
506
+
507
+		//Encryption key
508
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
509
+
510
+		$return = $value;
511
+
512
+		if ($cryptType && !empty($cryptKey))
513
+		{
514
+			if ($cryptType == 2)
515
+			{
516
+				$return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
517
+			}
518
+			else if ($cryptType == 1)
519
+			{
520
+				$return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
521
+			}
522
+		}
523
+
524
+		return $return;
525
+	}
526
+
527
+
528
+	/**
529 529
 	 * Return connexion ID
530 530
 	 *
531 531
 	 * @return	        string      Id connexion
532
-     */
533
-    function DDLGetConnectId()
534
-    {
535
-        $resql=$this->query('SELECT CONNECTION_ID()');
536
-        if ($resql)
537
-        {
538
-            $row=$this->fetch_row($resql);
539
-            return $row[0];
540
-        }
541
-        else return '?';
542
-    }
543
-
544
-    /**
532
+	 */
533
+	function DDLGetConnectId()
534
+	{
535
+		$resql=$this->query('SELECT CONNECTION_ID()');
536
+		if ($resql)
537
+		{
538
+			$row=$this->fetch_row($resql);
539
+			return $row[0];
540
+		}
541
+		else return '?';
542
+	}
543
+
544
+	/**
545 545
 	 *	Create a new database
546 546
 	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
547 547
 	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
@@ -551,79 +551,79 @@  discard block
 block discarded – undo
551 551
 	 * 	@param	string	$collation		Charset used to sort data
552 552
 	 * 	@param	string	$owner			Username of database owner
553 553
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
554
-     */
555
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
556
-    {
557
-        if (empty($charset))   $charset=$this->forcecharset;
558
-        if (empty($collation)) $collation=$this->forcecollate;
554
+	 */
555
+	function DDLCreateDb($database,$charset='',$collation='',$owner='')
556
+	{
557
+		if (empty($charset))   $charset=$this->forcecharset;
558
+		if (empty($collation)) $collation=$this->forcecollate;
559 559
 
560
-        // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
560
+		// ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
561 561
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
562 562
 		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
563 563
 
564
-        dol_syslog($sql,LOG_DEBUG);
565
-        $ret=$this->query($sql);
566
-        if (! $ret)
567
-        {
568
-            // We try again for compatibility with Mysql < 4.1.1
569
-            $sql = "CREATE DATABASE `".$this->escape($database)."`";
570
-            dol_syslog($sql,LOG_DEBUG);
571
-            $ret=$this->query($sql);
572
-        }
573
-        return $ret;
574
-    }
575
-
576
-    /**
564
+		dol_syslog($sql,LOG_DEBUG);
565
+		$ret=$this->query($sql);
566
+		if (! $ret)
567
+		{
568
+			// We try again for compatibility with Mysql < 4.1.1
569
+			$sql = "CREATE DATABASE `".$this->escape($database)."`";
570
+			dol_syslog($sql,LOG_DEBUG);
571
+			$ret=$this->query($sql);
572
+		}
573
+		return $ret;
574
+	}
575
+
576
+	/**
577 577
 	 *  List tables into a database
578 578
 	 *
579 579
 	 *  @param	string		$database	Name of database
580 580
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
581 581
 	 *  @return	array					List of tables in an array
582
-     */
583
-    function DDLListTables($database, $table='')
584
-    {
585
-        $listtables=array();
586
-
587
-        $like = '';
588
-        if ($table) $like = "LIKE '".$table."'";
589
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
590
-        //print $sql;
591
-        $result = $this->query($sql);
592
-        if ($result)
593
-        {
594
-            while($row = $this->fetch_row($result))
595
-            {
596
-                $listtables[] = $row[0];
597
-            }
598
-        }
599
-        return $listtables;
600
-    }
601
-
602
-    /**
582
+	 */
583
+	function DDLListTables($database, $table='')
584
+	{
585
+		$listtables=array();
586
+
587
+		$like = '';
588
+		if ($table) $like = "LIKE '".$table."'";
589
+		$sql="SHOW TABLES FROM ".$database." ".$like.";";
590
+		//print $sql;
591
+		$result = $this->query($sql);
592
+		if ($result)
593
+		{
594
+			while($row = $this->fetch_row($result))
595
+			{
596
+				$listtables[] = $row[0];
597
+			}
598
+		}
599
+		return $listtables;
600
+	}
601
+
602
+	/**
603 603
 	 *	List information of columns into a table.
604 604
 	 *
605 605
 	 *	@param	string	$table		Name of table
606 606
 	 *	@return	array				Tableau des informations des champs de la table
607
-     */
608
-    function DDLInfoTable($table)
609
-    {
610
-        $infotables=array();
611
-
612
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
613
-
614
-        dol_syslog($sql,LOG_DEBUG);
615
-        $result = $this->query($sql);
616
-        if ($result)
617
-        {
618
-            while($row = $this->fetch_row($result))
619
-            {
620
-                $infotables[] = $row;
621
-            }
622
-        }
623
-        return $infotables;
624
-    }
625
-
626
-    /**
607
+	 */
608
+	function DDLInfoTable($table)
609
+	{
610
+		$infotables=array();
611
+
612
+		$sql="SHOW FULL COLUMNS FROM ".$table.";";
613
+
614
+		dol_syslog($sql,LOG_DEBUG);
615
+		$result = $this->query($sql);
616
+		if ($result)
617
+		{
618
+			while($row = $this->fetch_row($result))
619
+			{
620
+				$infotables[] = $row;
621
+			}
622
+		}
623
+		return $infotables;
624
+	}
625
+
626
+	/**
627 627
 	 *	Create a table into database
628 628
 	 *
629 629
 	 *	@param	    string	$table 			Nom de la table
@@ -634,18 +634,18 @@  discard block
 block discarded – undo
634 634
 	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
635 635
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
636 636
 	 *	@return	    int						<0 if KO, >=0 if OK
637
-     */
638
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
639
-    {
640
-	    // FIXME: $fulltext_keys parameter is unused
641
-
642
-        // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
643
-        // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
644
-        $sql = "CREATE TABLE ".$table."(";
645
-        $i=0;
646
-        foreach($fields as $field_name => $field_desc)
647
-        {
648
-        	$sqlfields[$i] = $field_name." ";
637
+	 */
638
+	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
639
+	{
640
+		// FIXME: $fulltext_keys parameter is unused
641
+
642
+		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
643
+		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
644
+		$sql = "CREATE TABLE ".$table."(";
645
+		$i=0;
646
+		foreach($fields as $field_name => $field_desc)
647
+		{
648
+			$sqlfields[$i] = $field_name." ";
649 649
 			$sqlfields[$i]  .= $field_desc['type'];
650 650
 			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
651 651
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
@@ -668,61 +668,61 @@  discard block
 block discarded – undo
668 668
 			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
669 669
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
670 670
 			}
671
-            $i++;
672
-        }
673
-        if($primary_key != "")
674
-        $pk = "primary key(".$primary_key.")";
675
-
676
-        if(is_array($unique_keys)) {
677
-            $i = 0;
678
-            foreach($unique_keys as $key => $value)
679
-            {
680
-                $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
681
-                $i++;
682
-            }
683
-        }
684
-        if(is_array($keys))
685
-        {
686
-            $i = 0;
687
-            foreach($keys as $key => $value)
688
-            {
689
-                $sqlk[$i] = "KEY ".$key." (".$value.")";
690
-                $i++;
691
-            }
692
-        }
693
-        $sql .= implode(',',$sqlfields);
694
-        if($primary_key != "")
695
-        $sql .= ",".$pk;
696
-        if($unique_keys != "")
697
-        $sql .= ",".implode(',',$sqluq);
698
-        if(is_array($keys))
699
-        $sql .= ",".implode(',',$sqlk);
700
-        $sql .=") engine=".$type;
701
-
702
-        dol_syslog($sql,LOG_DEBUG);
703
-        if(! $this -> query($sql))
704
-        return -1;
705
-        else
706
-        return 1;
707
-    }
708
-
709
-    /**
671
+			$i++;
672
+		}
673
+		if($primary_key != "")
674
+		$pk = "primary key(".$primary_key.")";
675
+
676
+		if(is_array($unique_keys)) {
677
+			$i = 0;
678
+			foreach($unique_keys as $key => $value)
679
+			{
680
+				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
681
+				$i++;
682
+			}
683
+		}
684
+		if(is_array($keys))
685
+		{
686
+			$i = 0;
687
+			foreach($keys as $key => $value)
688
+			{
689
+				$sqlk[$i] = "KEY ".$key." (".$value.")";
690
+				$i++;
691
+			}
692
+		}
693
+		$sql .= implode(',',$sqlfields);
694
+		if($primary_key != "")
695
+		$sql .= ",".$pk;
696
+		if($unique_keys != "")
697
+		$sql .= ",".implode(',',$sqluq);
698
+		if(is_array($keys))
699
+		$sql .= ",".implode(',',$sqlk);
700
+		$sql .=") engine=".$type;
701
+
702
+		dol_syslog($sql,LOG_DEBUG);
703
+		if(! $this -> query($sql))
704
+		return -1;
705
+		else
706
+		return 1;
707
+	}
708
+
709
+	/**
710 710
 	 *	Return a pointer of line with description of a table or field
711 711
 	 *
712 712
 	 *	@param	string		$table	Name of table
713 713
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
714 714
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
715
-     */
716
-    function DDLDescTable($table,$field="")
717
-    {
718
-        $sql="DESC ".$table." ".$field;
715
+	 */
716
+	function DDLDescTable($table,$field="")
717
+	{
718
+		$sql="DESC ".$table." ".$field;
719 719
 
720
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
721
-        $this->_results = $this->query($sql);
722
-        return $this->_results;
723
-    }
720
+		dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
721
+		$this->_results = $this->query($sql);
722
+		return $this->_results;
723
+	}
724 724
 
725
-    /**
725
+	/**
726 726
 	 *	Create a new field into table
727 727
 	 *
728 728
 	 *	@param	string	$table 				Name of table
@@ -730,105 +730,105 @@  discard block
 block discarded – undo
730 730
 	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
731 731
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
732 732
 	 *	@return	int							<0 if KO, >0 if OK
733
-     */
734
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
735
-    {
736
-        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
737
-        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
738
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
739
-        $sql.= $field_desc['type'];
740
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
741
-            if (! in_array($field_desc['type'],array('date','datetime')))
742
-            {
743
-                $sql.= "(".$field_desc['value'].")";
744
-            }
745
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
746
-        $sql.= " ".$field_desc['attribute'];
747
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
748
-        $sql.= " ".$field_desc['null'];
749
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
750
-        {
751
-            if(preg_match("/null/i",$field_desc['default']))
752
-            $sql.= " default ".$field_desc['default'];
753
-            else
754
-            $sql.= " default '".$field_desc['default']."'";
755
-        }
756
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
757
-        $sql.= " ".$field_desc['extra'];
758
-        $sql.= " ".$field_position;
759
-
760
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
761
-        if($this->query($sql)) {
762
-            return 1;
763
-        }
764
-        return -1;
765
-    }
766
-
767
-    /**
733
+	 */
734
+	function DDLAddField($table,$field_name,$field_desc,$field_position="")
735
+	{
736
+		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
737
+		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
738
+		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
739
+		$sql.= $field_desc['type'];
740
+		if(preg_match("/^[^\s]/i",$field_desc['value']))
741
+			if (! in_array($field_desc['type'],array('date','datetime')))
742
+			{
743
+				$sql.= "(".$field_desc['value'].")";
744
+			}
745
+		if(preg_match("/^[^\s]/i",$field_desc['attribute']))
746
+		$sql.= " ".$field_desc['attribute'];
747
+		if(preg_match("/^[^\s]/i",$field_desc['null']))
748
+		$sql.= " ".$field_desc['null'];
749
+		if(preg_match("/^[^\s]/i",$field_desc['default']))
750
+		{
751
+			if(preg_match("/null/i",$field_desc['default']))
752
+			$sql.= " default ".$field_desc['default'];
753
+			else
754
+			$sql.= " default '".$field_desc['default']."'";
755
+		}
756
+		if(preg_match("/^[^\s]/i",$field_desc['extra']))
757
+		$sql.= " ".$field_desc['extra'];
758
+		$sql.= " ".$field_position;
759
+
760
+		dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
761
+		if($this->query($sql)) {
762
+			return 1;
763
+		}
764
+		return -1;
765
+	}
766
+
767
+	/**
768 768
 	 *	Update format of a field into a table
769 769
 	 *
770 770
 	 *	@param	string	$table 				Name of table
771 771
 	 *	@param	string	$field_name 		Name of field to modify
772 772
 	 *	@param	string	$field_desc 		Array with description of field format
773 773
 	 *	@return	int							<0 if KO, >0 if OK
774
-     */
775
-    function DDLUpdateField($table,$field_name,$field_desc)
776
-    {
777
-        $sql = "ALTER TABLE ".$table;
778
-        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
779
-        if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
780
-        	$sql.="(".$field_desc['value'].")";
781
-        }
782
-        if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
783
-        {
784
-        	// 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
785
-        	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
786
-        	{
787
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
788
-        		$this->query($sqlbis);
789
-        	}
790
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
791
-        	{
792
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
793
-        		$this->query($sqlbis);
794
-        	}
795
-
796
-        	$sql.=" NOT NULL";
797
-        }
798
-
799
-        if ($field_desc['default'] != '')
800
-        {
774
+	 */
775
+	function DDLUpdateField($table,$field_name,$field_desc)
776
+	{
777
+		$sql = "ALTER TABLE ".$table;
778
+		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
779
+		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
780
+			$sql.="(".$field_desc['value'].")";
781
+		}
782
+		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
783
+		{
784
+			// 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
785
+			if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
786
+			{
787
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
788
+				$this->query($sqlbis);
789
+			}
790
+			elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
791
+			{
792
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
793
+				$this->query($sqlbis);
794
+			}
795
+
796
+			$sql.=" NOT NULL";
797
+		}
798
+
799
+		if ($field_desc['default'] != '')
800
+		{
801 801
 			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
802
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
803
-        }
802
+			elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
803
+		}
804 804
 
805
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
806
-        if (! $this->query($sql))
807
-        return -1;
808
-        else
809
-        return 1;
810
-    }
805
+		dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
806
+		if (! $this->query($sql))
807
+		return -1;
808
+		else
809
+		return 1;
810
+	}
811 811
 
812
-    /**
812
+	/**
813 813
 	 *	Drop a field from table
814 814
 	 *
815 815
 	 *	@param	string	$table 			Name of table
816 816
 	 *	@param	string	$field_name 	Name of field to drop
817 817
 	 *	@return	int						<0 if KO, >0 if OK
818
-     */
819
-    function DDLDropField($table,$field_name)
820
-    {
821
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
822
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
823
-        if ($this->query($sql)) {
824
-            return 1;
825
-        }
826
-	    $this->error=$this->lasterror();
827
-	    return -1;
828
-    }
829
-
830
-
831
-    /**
818
+	 */
819
+	function DDLDropField($table,$field_name)
820
+	{
821
+		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
822
+		dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
823
+		if ($this->query($sql)) {
824
+			return 1;
825
+		}
826
+		$this->error=$this->lasterror();
827
+		return -1;
828
+	}
829
+
830
+
831
+	/**
832 832
 	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
833 833
 	 *
834 834
 	 *	@param	string	$dolibarr_main_db_host 		Ip server or '%'
@@ -836,213 +836,213 @@  discard block
 block discarded – undo
836 836
 	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
837 837
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
838 838
 	 *	@return	int									<0 if KO, >=0 if OK
839
-     */
840
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
841
-    {
842
-        $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
843
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
844
-        $resql=$this->query($sql);
845
-        if (! $resql)
846
-        {
847
-            if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
848
-            {
849
-            	return -1;
850
-            }
851
-            else
839
+	 */
840
+	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
841
+	{
842
+		$sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
843
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
844
+		$resql=$this->query($sql);
845
+		if (! $resql)
846
+		{
847
+			if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
848
+			{
849
+				return -1;
850
+			}
851
+			else
852
+			{
853
+				// If user already exists, we continue to set permissions
854
+				dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
855
+			}
856
+		}
857
+		$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)."'";
858
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
859
+		$resql=$this->query($sql);
860
+		if (! $resql)
861
+		{
862
+			return -1;
863
+		}
864
+
865
+		$sql="FLUSH Privileges";
866
+
867
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
868
+		$resql=$this->query($sql);
869
+		if (! $resql)
870
+		{
871
+			return -1;
872
+		}
873
+
874
+		return 1;
875
+	}
876
+
877
+	/**
878
+	 *	Return charset used to store data in current database (same result than using SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = "databasename";)
879
+	 *
880
+	 *	@return		string		Charset
881
+	 *  @see getDefaultCollationDatabase
882
+	 */
883
+	function getDefaultCharacterSetDatabase()
884
+	{
885
+		$resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
886
+		if (!$resql)
887
+		{
888
+			// version Mysql < 4.1.1
889
+			return $this->forcecharset;
890
+		}
891
+		$liste=$this->fetch_array($resql);
892
+		$tmpval = $liste['Value'];
893
+
894
+		return $tmpval;
895
+	}
896
+
897
+	/**
898
+	 *	Return list of available charset that can be used to store data in database
899
+	 *
900
+	 *	@return		array|null		List of Charset
901
+	 */
902
+	function getListOfCharacterSet()
903
+	{
904
+		$resql=$this->query('SHOW CHARSET');
905
+		$liste = array();
906
+		if ($resql)
907
+		{
908
+			$i = 0;
909
+			while ($obj = $this->fetch_object($resql) )
910
+			{
911
+				$liste[$i]['charset'] = $obj->Charset;
912
+				$liste[$i]['description'] = $obj->Description;
913
+				$i++;
914
+			}
915
+			$this->free($resql);
916
+		} else {
917
+			// version Mysql < 4.1.1
918
+			return null;
919
+		}
920
+		return $liste;
921
+	}
922
+
923
+	/**
924
+	 *	Return collation used in current database
925
+	 *
926
+	 *	@return		string		Collation value
927
+	 *  @see getDefaultCharacterSetDatabase
928
+	 */
929
+	function getDefaultCollationDatabase()
930
+	{
931
+		$resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
932
+		if (!$resql)
933
+		{
934
+			// version Mysql < 4.1.1
935
+			return $this->forcecollate;
936
+		}
937
+		$liste=$this->fetch_array($resql);
938
+		$tmpval = $liste['Value'];
939
+
940
+		return $tmpval;
941
+	}
942
+
943
+	/**
944
+	 *	Return list of available collation that can be used for database
945
+	 *
946
+	 *	@return		array|null		Liste of Collation
947
+	 */
948
+	function getListOfCollation()
949
+	{
950
+		$resql=$this->query('SHOW COLLATION');
951
+		$liste = array();
952
+		if ($resql)
953
+		{
954
+			$i = 0;
955
+			while ($obj = $this->fetch_object($resql) )
852 956
 			{
853
-            	// If user already exists, we continue to set permissions
854
-            	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
855
-            }
856
-        }
857
-        $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)."'";
858
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
859
-        $resql=$this->query($sql);
860
-        if (! $resql)
861
-        {
862
-            return -1;
863
-        }
864
-
865
-        $sql="FLUSH Privileges";
866
-
867
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
868
-        $resql=$this->query($sql);
869
-        if (! $resql)
870
-        {
871
-            return -1;
872
-        }
873
-
874
-        return 1;
875
-    }
876
-
877
-    /**
878
-     *	Return charset used to store data in current database (same result than using SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = "databasename";)
879
-     *
880
-     *	@return		string		Charset
881
-     *  @see getDefaultCollationDatabase
882
-     */
883
-    function getDefaultCharacterSetDatabase()
884
-    {
885
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
886
-        if (!$resql)
887
-        {
888
-            // version Mysql < 4.1.1
889
-            return $this->forcecharset;
890
-        }
891
-        $liste=$this->fetch_array($resql);
892
-        $tmpval = $liste['Value'];
893
-
894
-        return $tmpval;
895
-    }
896
-
897
-    /**
898
-     *	Return list of available charset that can be used to store data in database
899
-     *
900
-     *	@return		array|null		List of Charset
901
-     */
902
-    function getListOfCharacterSet()
903
-    {
904
-        $resql=$this->query('SHOW CHARSET');
905
-        $liste = array();
906
-        if ($resql)
907
-        {
908
-            $i = 0;
909
-            while ($obj = $this->fetch_object($resql) )
910
-            {
911
-                $liste[$i]['charset'] = $obj->Charset;
912
-                $liste[$i]['description'] = $obj->Description;
913
-                $i++;
914
-            }
915
-            $this->free($resql);
916
-        } else {
917
-            // version Mysql < 4.1.1
918
-            return null;
919
-        }
920
-        return $liste;
921
-    }
922
-
923
-    /**
924
-     *	Return collation used in current database
925
-     *
926
-     *	@return		string		Collation value
927
-     *  @see getDefaultCharacterSetDatabase
928
-     */
929
-    function getDefaultCollationDatabase()
930
-    {
931
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
932
-        if (!$resql)
933
-        {
934
-            // version Mysql < 4.1.1
935
-            return $this->forcecollate;
936
-        }
937
-        $liste=$this->fetch_array($resql);
938
-        $tmpval = $liste['Value'];
939
-
940
-        return $tmpval;
941
-    }
942
-
943
-    /**
944
-     *	Return list of available collation that can be used for database
945
-     *
946
-     *	@return		array|null		Liste of Collation
947
-     */
948
-    function getListOfCollation()
949
-    {
950
-        $resql=$this->query('SHOW COLLATION');
951
-        $liste = array();
952
-        if ($resql)
953
-        {
954
-            $i = 0;
955
-            while ($obj = $this->fetch_object($resql) )
956
-            {
957
-                $liste[$i]['collation'] = $obj->Collation;
958
-                $i++;
959
-            }
960
-            $this->free($resql);
961
-        } else {
962
-            // version Mysql < 4.1.1
963
-            return null;
964
-        }
965
-        return $liste;
966
-    }
967
-
968
-    /**
957
+				$liste[$i]['collation'] = $obj->Collation;
958
+				$i++;
959
+			}
960
+			$this->free($resql);
961
+		} else {
962
+			// version Mysql < 4.1.1
963
+			return null;
964
+		}
965
+		return $liste;
966
+	}
967
+
968
+	/**
969 969
 	 *	Return full path of dump program
970 970
 	 *
971 971
 	 *	@return		string		Full path of dump program
972
-     */
973
-    function getPathOfDump()
974
-    {
975
-        $fullpathofdump='/pathtomysqldump/mysqldump';
976
-
977
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
978
-        if ($resql)
979
-        {
980
-            $liste=$this->fetch_array($resql);
981
-            $basedir=$liste['Value'];
982
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
983
-        }
984
-        return $fullpathofdump;
985
-    }
986
-
987
-    /**
988
-     *	Return full path of restore program
989
-     *
990
-     *	@return		string		Full path of restore program
991
-     */
992
-    function getPathOfRestore()
993
-    {
994
-        $fullpathofimport='/pathtomysql/mysql';
995
-
996
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
997
-        if ($resql)
998
-        {
999
-            $liste=$this->fetch_array($resql);
1000
-            $basedir=$liste['Value'];
1001
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1002
-        }
1003
-        return $fullpathofimport;
1004
-    }
1005
-
1006
-    /**
1007
-     * Return value of server parameters
1008
-     *
1009
-     * @param	string	$filter		Filter list on a particular value
972
+	 */
973
+	function getPathOfDump()
974
+	{
975
+		$fullpathofdump='/pathtomysqldump/mysqldump';
976
+
977
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
978
+		if ($resql)
979
+		{
980
+			$liste=$this->fetch_array($resql);
981
+			$basedir=$liste['Value'];
982
+			$fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
983
+		}
984
+		return $fullpathofdump;
985
+	}
986
+
987
+	/**
988
+	 *	Return full path of restore program
989
+	 *
990
+	 *	@return		string		Full path of restore program
991
+	 */
992
+	function getPathOfRestore()
993
+	{
994
+		$fullpathofimport='/pathtomysql/mysql';
995
+
996
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
997
+		if ($resql)
998
+		{
999
+			$liste=$this->fetch_array($resql);
1000
+			$basedir=$liste['Value'];
1001
+			$fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1002
+		}
1003
+		return $fullpathofimport;
1004
+	}
1005
+
1006
+	/**
1007
+	 * Return value of server parameters
1008
+	 *
1009
+	 * @param	string	$filter		Filter list on a particular value
1010 1010
 	 * @return	array				Array of key-values (key=>value)
1011
-     */
1012
-    function getServerParametersValues($filter='')
1013
-    {
1014
-        $result=array();
1015
-
1016
-        $sql='SHOW VARIABLES';
1017
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1018
-        $resql=$this->query($sql);
1019
-        if ($resql)
1020
-        {
1021
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1022
-        }
1023
-
1024
-        return $result;
1025
-    }
1026
-
1027
-    /**
1028
-     * Return value of server status (current indicators on memory, cache...)
1029
-     *
1030
-     * @param	string	$filter		Filter list on a particular value
1011
+	 */
1012
+	function getServerParametersValues($filter='')
1013
+	{
1014
+		$result=array();
1015
+
1016
+		$sql='SHOW VARIABLES';
1017
+		if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1018
+		$resql=$this->query($sql);
1019
+		if ($resql)
1020
+		{
1021
+			while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1022
+		}
1023
+
1024
+		return $result;
1025
+	}
1026
+
1027
+	/**
1028
+	 * Return value of server status (current indicators on memory, cache...)
1029
+	 *
1030
+	 * @param	string	$filter		Filter list on a particular value
1031 1031
 	 * @return  array				Array of key-values (key=>value)
1032
-     */
1033
-    function getServerStatusValues($filter='')
1034
-    {
1035
-        $result=array();
1036
-
1037
-        $sql='SHOW STATUS';
1038
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1039
-        $resql=$this->query($sql);
1040
-        if ($resql)
1041
-        {
1042
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1043
-        }
1044
-
1045
-        return $result;
1046
-    }
1032
+	 */
1033
+	function getServerStatusValues($filter='')
1034
+	{
1035
+		$result=array();
1036
+
1037
+		$sql='SHOW STATUS';
1038
+		if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1039
+		$resql=$this->query($sql);
1040
+		if ($resql)
1041
+		{
1042
+			while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1043
+		}
1044
+
1045
+		return $result;
1046
+	}
1047 1047
 }
1048 1048
 
Please login to merge, or discard this patch.
Braces   +109 added lines, -68 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,13 +115,16 @@  discard block
 block discarded – undo
111 115
 
112 116
                 // If client connected with different charset than Dolibarr HTML output
113 117
                 $clientmustbe='';
114
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
115
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
118
+                if (preg_match('/UTF-8/i',$conf->file->character_set_client)) {
119
+                	$clientmustbe='utf8';
120
+                }
121
+                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) {
122
+                	$clientmustbe='latin1';
123
+                }
116 124
 				if ($this->db->character_set_name() != $clientmustbe) {
117 125
 					$this->db->set_charset($clientmustbe);
118 126
 				}
119
-            }
120
-            else
127
+            } else
121 128
             {
122 129
                 $this->database_selected = false;
123 130
                 $this->database_name = '';
@@ -125,8 +132,7 @@  discard block
 block discarded – undo
125 132
                 $this->error=$this->error();
126 133
                 dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
127 134
             }
128
-        }
129
-        else
135
+        } else
130 136
         {
131 137
             // Pas de selection de base demandee, ok ou ko
132 138
             $this->database_selected = false;
@@ -135,8 +141,12 @@  discard block
 block discarded – undo
135 141
             {
136 142
                 // If client connected with different charset than Dolibarr HTML output
137 143
                 $clientmustbe='';
138
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
139
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
144
+                if (preg_match('/UTF-8/i',$conf->file->character_set_client)) {
145
+                	$clientmustbe='utf8';
146
+                }
147
+                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) {
148
+                	$clientmustbe='latin1';
149
+                }
140 150
 				if ($this->db->character_set_name() != $clientmustbe) {
141 151
 					$this->db->set_charset($clientmustbe);
142 152
 				}
@@ -219,7 +229,9 @@  discard block
 block discarded – undo
219 229
     {
220 230
         if ($this->db)
221 231
         {
222
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
232
+	        if ($this->transaction_opened > 0) {
233
+	        	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
234
+	        }
223 235
             $this->connected=false;
224 236
             return $this->db->close();
225 237
         }
@@ -241,14 +253,15 @@  discard block
 block discarded – undo
241 253
 
242 254
         $query = trim($query);
243 255
 
244
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
256
+	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
257
+	    	dol_syslog('sql='.$query, LOG_DEBUG);
258
+	    }
245 259
 
246 260
         if (! $this->database_name)
247 261
         {
248 262
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
249 263
             $ret = $this->db->query($query);
250
-        }
251
-        else
264
+        } else
252 265
         {
253 266
             $ret = $this->db->query($query);
254 267
         }
@@ -262,7 +275,10 @@  discard block
 block discarded – undo
262 275
                 $this->lasterror = $this->error();
263 276
                 $this->lasterrno = $this->errno();
264 277
 
265
-				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
278
+				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
279
+					dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
280
+				}
281
+				// Log of request was not yet done previously
266 282
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
267 283
             }
268 284
             $this->lastquery=$query;
@@ -312,8 +328,7 @@  discard block
 block discarded – undo
312 328
         {
313 329
             if (! is_object($resultset)) { $resultset=$this->_results; }
314 330
             return $resultset->fetch_row();
315
-        }
316
-        else
331
+        } else
317 332
         {
318 333
             // si le curseur est un booleen on retourne la valeur 0
319 334
             return 0;
@@ -362,7 +377,9 @@  discard block
 block discarded – undo
362 377
         // If resultset not provided, we take the last used by connexion
363 378
         if (! is_object($resultset)) { $resultset=$this->_results; }
364 379
         // Si resultset en est un, on libere la memoire
365
-        if (is_object($resultset)) $resultset->free_result();
380
+        if (is_object($resultset)) {
381
+        	$resultset->free_result();
382
+        }
366 383
     }
367 384
 
368 385
     /**
@@ -437,8 +454,7 @@  discard block
 block discarded – undo
437 454
         if (! $this->connected) {
438 455
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
439 456
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
440
-        }
441
-        else {
457
+        } else {
442 458
             return $this->db->error;
443 459
         }
444 460
     }
@@ -481,8 +497,7 @@  discard block
 block discarded – undo
481 497
             if ($cryptType == 2)
482 498
             {
483 499
                 $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
484
-            }
485
-            else if ($cryptType == 1)
500
+            } else if ($cryptType == 1)
486 501
             {
487 502
                 $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
488 503
             }
@@ -514,8 +529,7 @@  discard block
 block discarded – undo
514 529
             if ($cryptType == 2)
515 530
             {
516 531
                 $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
517
-            }
518
-            else if ($cryptType == 1)
532
+            } else if ($cryptType == 1)
519 533
             {
520 534
                 $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
521 535
             }
@@ -537,8 +551,9 @@  discard block
 block discarded – undo
537 551
         {
538 552
             $row=$this->fetch_row($resql);
539 553
             return $row[0];
554
+        } else {
555
+        	return '?';
540 556
         }
541
-        else return '?';
542 557
     }
543 558
 
544 559
     /**
@@ -554,8 +569,12 @@  discard block
 block discarded – undo
554 569
      */
555 570
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
556 571
     {
557
-        if (empty($charset))   $charset=$this->forcecharset;
558
-        if (empty($collation)) $collation=$this->forcecollate;
572
+        if (empty($charset)) {
573
+        	$charset=$this->forcecharset;
574
+        }
575
+        if (empty($collation)) {
576
+        	$collation=$this->forcecollate;
577
+        }
559 578
 
560 579
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
561 580
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
@@ -585,7 +604,9 @@  discard block
 block discarded – undo
585 604
         $listtables=array();
586 605
 
587 606
         $like = '';
588
-        if ($table) $like = "LIKE '".$table."'";
607
+        if ($table) {
608
+        	$like = "LIKE '".$table."'";
609
+        }
589 610
         $sql="SHOW TABLES FROM ".$database." ".$like.";";
590 611
         //print $sql;
591 612
         $result = $this->query($sql);
@@ -657,8 +678,7 @@  discard block
 block discarded – undo
657 678
 			{
658 679
 				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
659 680
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
660
-				}
661
-				else {
681
+				} else {
662 682
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
663 683
 				}
664 684
 			}
@@ -670,8 +690,9 @@  discard block
 block discarded – undo
670 690
 			}
671 691
             $i++;
672 692
         }
673
-        if($primary_key != "")
674
-        $pk = "primary key(".$primary_key.")";
693
+        if($primary_key != "") {
694
+                $pk = "primary key(".$primary_key.")";
695
+        }
675 696
 
676 697
         if(is_array($unique_keys)) {
677 698
             $i = 0;
@@ -691,19 +712,23 @@  discard block
 block discarded – undo
691 712
             }
692 713
         }
693 714
         $sql .= implode(',',$sqlfields);
694
-        if($primary_key != "")
695
-        $sql .= ",".$pk;
696
-        if($unique_keys != "")
697
-        $sql .= ",".implode(',',$sqluq);
698
-        if(is_array($keys))
699
-        $sql .= ",".implode(',',$sqlk);
715
+        if($primary_key != "") {
716
+                $sql .= ",".$pk;
717
+        }
718
+        if($unique_keys != "") {
719
+                $sql .= ",".implode(',',$sqluq);
720
+        }
721
+        if(is_array($keys)) {
722
+                $sql .= ",".implode(',',$sqlk);
723
+        }
700 724
         $sql .=") engine=".$type;
701 725
 
702 726
         dol_syslog($sql,LOG_DEBUG);
703
-        if(! $this -> query($sql))
704
-        return -1;
705
-        else
706
-        return 1;
727
+        if(! $this -> query($sql)) {
728
+                return -1;
729
+        } else {
730
+                return 1;
731
+        }
707 732
     }
708 733
 
709 734
     /**
@@ -737,24 +762,29 @@  discard block
 block discarded – undo
737 762
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
738 763
         $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
739 764
         $sql.= $field_desc['type'];
740
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
741
-            if (! in_array($field_desc['type'],array('date','datetime')))
765
+        if(preg_match("/^[^\s]/i",$field_desc['value'])) {
766
+                    if (! in_array($field_desc['type'],array('date','datetime')))
742 767
             {
743 768
                 $sql.= "(".$field_desc['value'].")";
769
+        }
744 770
             }
745
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
746
-        $sql.= " ".$field_desc['attribute'];
747
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
748
-        $sql.= " ".$field_desc['null'];
771
+        if(preg_match("/^[^\s]/i",$field_desc['attribute'])) {
772
+                $sql.= " ".$field_desc['attribute'];
773
+        }
774
+        if(preg_match("/^[^\s]/i",$field_desc['null'])) {
775
+                $sql.= " ".$field_desc['null'];
776
+        }
749 777
         if(preg_match("/^[^\s]/i",$field_desc['default']))
750 778
         {
751
-            if(preg_match("/null/i",$field_desc['default']))
752
-            $sql.= " default ".$field_desc['default'];
753
-            else
754
-            $sql.= " default '".$field_desc['default']."'";
779
+            if(preg_match("/null/i",$field_desc['default'])) {
780
+                        $sql.= " default ".$field_desc['default'];
781
+            } else {
782
+                        $sql.= " default '".$field_desc['default']."'";
783
+            }
784
+        }
785
+        if(preg_match("/^[^\s]/i",$field_desc['extra'])) {
786
+                $sql.= " ".$field_desc['extra'];
755 787
         }
756
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
757
-        $sql.= " ".$field_desc['extra'];
758 788
         $sql.= " ".$field_position;
759 789
 
760 790
         dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
@@ -786,8 +816,7 @@  discard block
 block discarded – undo
786 816
         	{
787 817
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
788 818
         		$this->query($sqlbis);
789
-        	}
790
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
819
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
791 820
         	{
792 821
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
793 822
         		$this->query($sqlbis);
@@ -798,15 +827,20 @@  discard block
 block discarded – undo
798 827
 
799 828
         if ($field_desc['default'] != '')
800 829
         {
801
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
802
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
830
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
831
+				$sql.=" DEFAULT ".$this->escape($field_desc['default']);
832
+			} elseif ($field_desc['type'] == 'text') {
833
+        		$sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
834
+        	}
835
+        	// Default not supported on text fields
803 836
         }
804 837
 
805 838
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
806
-        if (! $this->query($sql))
807
-        return -1;
808
-        else
809
-        return 1;
839
+        if (! $this->query($sql)) {
840
+                return -1;
841
+        } else {
842
+                return 1;
843
+        }
810 844
     }
811 845
 
812 846
     /**
@@ -847,8 +881,7 @@  discard block
 block discarded – undo
847 881
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
848 882
             {
849 883
             	return -1;
850
-            }
851
-            else
884
+            } else
852 885
 			{
853 886
             	// If user already exists, we continue to set permissions
854 887
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -1014,11 +1047,15 @@  discard block
 block discarded – undo
1014 1047
         $result=array();
1015 1048
 
1016 1049
         $sql='SHOW VARIABLES';
1017
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1050
+        if ($filter) {
1051
+        	$sql.=" LIKE '".$this->escape($filter)."'";
1052
+        }
1018 1053
         $resql=$this->query($sql);
1019 1054
         if ($resql)
1020 1055
         {
1021
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1056
+        	while($obj=$this->fetch_object($resql)) {
1057
+        		$result[$obj->Variable_name]=$obj->Value;
1058
+        	}
1022 1059
         }
1023 1060
 
1024 1061
         return $result;
@@ -1035,11 +1072,15 @@  discard block
 block discarded – undo
1035 1072
         $result=array();
1036 1073
 
1037 1074
         $sql='SHOW STATUS';
1038
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1075
+        if ($filter) {
1076
+        	$sql.=" LIKE '".$this->escape($filter)."'";
1077
+        }
1039 1078
         $resql=$this->query($sql);
1040 1079
         if ($resql)
1041 1080
         {
1042
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1081
+            while($obj=$this->fetch_object($resql)) {
1082
+            	$result[$obj->Variable_name]=$obj->Value;
1083
+            }
1043 1084
         }
1044 1085
 
1045 1086
         return $result;
Please login to merge, or discard this patch.
Spacing   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
  *	\brief      Class file to manage Dolibarr database access for a MySQL database
26 26
  */
27 27
 
28
-require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
28
+require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
29 29
 
30 30
 /**
31 31
  *	Class to manage Dolibarr database access for a MySQL database using the MySQLi extension
@@ -35,11 +35,11 @@  discard block
 block discarded – undo
35 35
 	/** @var mysqli Database object */
36 36
 	public $db;
37 37
     //! Database type
38
-    public $type='mysqli';
38
+    public $type = 'mysqli';
39 39
     //! Database label
40
-    const LABEL='MySQL or MariaDB';
40
+    const LABEL = 'MySQL or MariaDB';
41 41
     //! Version min database
42
-    const VERSIONMIN='5.0.3';
42
+    const VERSIONMIN = '5.0.3';
43 43
 	/** @var mysqli_result Resultset of last query */
44 44
 	private $_results;
45 45
 
@@ -54,36 +54,36 @@  discard block
 block discarded – undo
54 54
 	 *	@param	    string	$name		Nom de la database
55 55
 	 *	@param	    int		$port		Port of database server
56 56
      */
57
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
57
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
58 58
     {
59
-        global $conf,$langs;
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)) $this->forcecharset = $conf->db->character_set;
63
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
64 64
 
65
-        $this->database_user=$user;
66
-        $this->database_host=$host;
67
-        $this->database_port=$port;
65
+        $this->database_user = $user;
66
+        $this->database_host = $host;
67
+        $this->database_port = $port;
68 68
 
69
-        $this->transaction_opened=0;
69
+        $this->transaction_opened = 0;
70 70
 
71 71
         //print "Name DB: $host,$user,$pass,$name<br>";
72 72
 
73
-        if (! class_exists('mysqli'))
73
+        if (!class_exists('mysqli'))
74 74
         {
75 75
             $this->connected = false;
76 76
             $this->ok = false;
77
-            $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
78
-            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);
77
+            $this->error = "Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
78
+            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);
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)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
85
+            $this->error = $langs->trans("ErrorWrongHostParameter");
86
+            dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters", LOG_ERR);
87 87
         }
88 88
 
89 89
 		// Try server connection
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 			$this->connected = false;
95 95
 			$this->ok = false;
96 96
 			$this->error = $this->db->connect_error;
97
-			dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
97
+			dol_syslog(get_class($this)."::DoliDBMysqli Connect error: ".$this->error, LOG_ERR);
98 98
 		} else {
99 99
 			$this->connected = true;
100 100
 			$this->ok = true;
@@ -110,9 +110,9 @@  discard block
 block discarded – undo
110 110
                 $this->ok = true;
111 111
 
112 112
                 // If client connected with different charset than Dolibarr HTML output
113
-                $clientmustbe='';
114
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
115
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
113
+                $clientmustbe = '';
114
+                if (preg_match('/UTF-8/i', $conf->file->character_set_client))      $clientmustbe = 'utf8';
115
+                if (preg_match('/ISO-8859-1/i', $conf->file->character_set_client)) $clientmustbe = 'latin1';
116 116
 				if ($this->db->character_set_name() != $clientmustbe) {
117 117
 					$this->db->set_charset($clientmustbe);
118 118
 				}
@@ -122,8 +122,8 @@  discard block
 block discarded – undo
122 122
                 $this->database_selected = false;
123 123
                 $this->database_name = '';
124 124
                 $this->ok = false;
125
-                $this->error=$this->error();
126
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
125
+                $this->error = $this->error();
126
+                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error, LOG_ERR);
127 127
             }
128 128
         }
129 129
         else
@@ -134,9 +134,9 @@  discard block
 block discarded – undo
134 134
             if ($this->connected)
135 135
             {
136 136
                 // If client connected with different charset than Dolibarr HTML output
137
-                $clientmustbe='';
138
-                if (preg_match('/UTF-8/i',$conf->file->character_set_client))      $clientmustbe='utf8';
139
-                if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
137
+                $clientmustbe = '';
138
+                if (preg_match('/UTF-8/i', $conf->file->character_set_client))      $clientmustbe = 'utf8';
139
+                if (preg_match('/ISO-8859-1/i', $conf->file->character_set_client)) $clientmustbe = 'latin1';
140 140
 				if ($this->db->character_set_name() != $clientmustbe) {
141 141
 					$this->db->set_charset($clientmustbe);
142 142
 				}
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
153 153
      *  @return    string   		SQL request line converted
154 154
      */
155
-    static function convertSQLFromMysql($line,$type='ddl')
155
+    static function convertSQLFromMysql($line, $type = 'ddl')
156 156
     {
157 157
         return $line;
158 158
     }
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	 */
184 184
 	function connect($host, $login, $passwd, $name, $port = 0)
185 185
 	{
186
-		dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
186
+		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
187 187
 
188 188
 		// Can also be
189 189
 		// mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
@@ -222,8 +222,8 @@  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;
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 227
             return $this->db->close();
228 228
         }
229 229
         return false;
@@ -238,15 +238,15 @@  discard block
 block discarded – undo
238 238
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
239 239
      *	@return	bool|mysqli_result		Resultset of answer
240 240
      */
241
-    function query($query,$usesavepoint=0,$type='auto')
241
+    function query($query, $usesavepoint = 0, $type = 'auto')
242 242
     {
243 243
     	global $conf;
244 244
 
245 245
         $query = trim($query);
246 246
 
247
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
247
+	    if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
248 248
 
249
-        if (! $this->database_name)
249
+        if (!$this->database_name)
250 250
         {
251 251
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
252 252
             $ret = $this->db->query($query);
@@ -256,19 +256,19 @@  discard block
 block discarded – undo
256 256
             $ret = $this->db->query($query);
257 257
         }
258 258
 
259
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
259
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
260 260
         {
261 261
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
262
-            if (! $ret)
262
+            if (!$ret)
263 263
             {
264 264
                 $this->lastqueryerror = $query;
265 265
                 $this->lasterror = $this->error();
266 266
                 $this->lasterrno = $this->errno();
267 267
 
268
-				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
268
+				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
269 269
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
270 270
             }
271
-            $this->lastquery=$query;
271
+            $this->lastquery = $query;
272 272
             $this->_results = $ret;
273 273
         }
274 274
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
     function fetch_object($resultset)
285 285
     {
286 286
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
287
-        if (! is_object($resultset)) { $resultset=$this->_results; }
287
+        if (!is_object($resultset)) { $resultset = $this->_results; }
288 288
 		return $resultset->fetch_object();
289 289
     }
290 290
 
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
     function fetch_array($resultset)
299 299
     {
300 300
         // If resultset not provided, we take the last used by connexion
301
-        if (! is_object($resultset)) { $resultset=$this->_results; }
301
+        if (!is_object($resultset)) { $resultset = $this->_results; }
302 302
         return $resultset->fetch_array();
303 303
     }
304 304
 
@@ -311,9 +311,9 @@  discard block
 block discarded – undo
311 311
     function fetch_row($resultset)
312 312
     {
313 313
         // If resultset not provided, we take the last used by connexion
314
-        if (! is_bool($resultset))
314
+        if (!is_bool($resultset))
315 315
         {
316
-            if (! is_object($resultset)) { $resultset=$this->_results; }
316
+            if (!is_object($resultset)) { $resultset = $this->_results; }
317 317
             return $resultset->fetch_row();
318 318
         }
319 319
         else
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
     function num_rows($resultset)
334 334
     {
335 335
         // If resultset not provided, we take the last used by connexion
336
-        if (! is_object($resultset)) { $resultset=$this->_results; }
336
+        if (!is_object($resultset)) { $resultset = $this->_results; }
337 337
         return $resultset->num_rows;
338 338
     }
339 339
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
     function affected_rows($resultset)
348 348
     {
349 349
         // If resultset not provided, we take the last used by connexion
350
-        if (! is_object($resultset)) { $resultset=$this->_results; }
350
+        if (!is_object($resultset)) { $resultset = $this->_results; }
351 351
         // mysql necessite un link de base pour cette fonction contrairement
352 352
         // a pqsql qui prend un resultset
353 353
         return $this->db->affected_rows;
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
      *	@param  mysqli_result	$resultset	Curseur de la requete voulue
361 361
      *	@return	void
362 362
      */
363
-    function free($resultset=null)
363
+    function free($resultset = null)
364 364
     {
365 365
         // If resultset not provided, we take the last used by connexion
366
-        if (! is_object($resultset)) { $resultset=$this->_results; }
366
+        if (!is_object($resultset)) { $resultset = $this->_results; }
367 367
         // Si resultset en est un, on libere la memoire
368 368
         if (is_object($resultset)) $resultset->free_result();
369 369
     }
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
      */
387 387
     function errno()
388 388
     {
389
-        if (! $this->connected) {
389
+        if (!$this->connected) {
390 390
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
391 391
             return 'DB_ERROR_FAILED_TO_CONNECT';
392 392
         } else {
@@ -418,15 +418,15 @@  discard block
 block discarded – undo
418 418
             1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
419 419
             1216 => 'DB_ERROR_NO_PARENT',
420 420
             1217 => 'DB_ERROR_CHILD_EXISTS',
421
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
421
+            1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
422 422
             1451 => 'DB_ERROR_CHILD_EXISTS'
423 423
             );
424 424
 
425 425
             if (isset($errorcode_map[$this->db->errno])) {
426 426
                 return $errorcode_map[$this->db->errno];
427 427
             }
428
-            $errno=$this->db->errno;
429
-            return ($errno?'DB_ERROR_'.$errno:'0');
428
+            $errno = $this->db->errno;
429
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
430 430
         }
431 431
     }
432 432
 
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
      */
438 438
     function error()
439 439
     {
440
-        if (! $this->connected) {
440
+        if (!$this->connected) {
441 441
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
442 442
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
443 443
         }
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 	 * @param	string	$fieldid	Field name
454 454
 	 * @return  int|string			Id of row
455 455
      */
456
-    function last_insert_id($tab,$fieldid='rowid')
456
+    function last_insert_id($tab, $fieldid = 'rowid')
457 457
     {
458 458
         return $this->db->insert_id;
459 459
     }
@@ -467,17 +467,17 @@  discard block
 block discarded – undo
467 467
      * 	@return	string					XXX(field) or XXX('value') or field or 'value'
468 468
      *
469 469
      */
470
-    function encrypt($fieldorvalue, $withQuotes=0)
470
+    function encrypt($fieldorvalue, $withQuotes = 0)
471 471
     {
472 472
         global $conf;
473 473
 
474 474
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
475
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
475
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
476 476
 
477 477
         //Encryption key
478
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
478
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
479 479
 
480
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
480
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
481 481
 
482 482
         if ($cryptType && !empty($cryptKey))
483 483
         {
@@ -505,10 +505,10 @@  discard block
 block discarded – undo
505 505
         global $conf;
506 506
 
507 507
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
508
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
508
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
509 509
 
510 510
         //Encryption key
511
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
511
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
512 512
 
513 513
         $return = $value;
514 514
 
@@ -535,10 +535,10 @@  discard block
 block discarded – undo
535 535
      */
536 536
     function DDLGetConnectId()
537 537
     {
538
-        $resql=$this->query('SELECT CONNECTION_ID()');
538
+        $resql = $this->query('SELECT CONNECTION_ID()');
539 539
         if ($resql)
540 540
         {
541
-            $row=$this->fetch_row($resql);
541
+            $row = $this->fetch_row($resql);
542 542
             return $row[0];
543 543
         }
544 544
         else return '?';
@@ -555,23 +555,23 @@  discard block
 block discarded – undo
555 555
 	 * 	@param	string	$owner			Username of database owner
556 556
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
557 557
      */
558
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
558
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
559 559
     {
560
-        if (empty($charset))   $charset=$this->forcecharset;
561
-        if (empty($collation)) $collation=$this->forcecollate;
560
+        if (empty($charset))   $charset = $this->forcecharset;
561
+        if (empty($collation)) $collation = $this->forcecollate;
562 562
 
563 563
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
564 564
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
565
-		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
565
+		$sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
566 566
 
567
-        dol_syslog($sql,LOG_DEBUG);
568
-        $ret=$this->query($sql);
569
-        if (! $ret)
567
+        dol_syslog($sql, LOG_DEBUG);
568
+        $ret = $this->query($sql);
569
+        if (!$ret)
570 570
         {
571 571
             // We try again for compatibility with Mysql < 4.1.1
572 572
             $sql = "CREATE DATABASE `".$this->escape($database)."`";
573
-            dol_syslog($sql,LOG_DEBUG);
574
-            $ret=$this->query($sql);
573
+            dol_syslog($sql, LOG_DEBUG);
574
+            $ret = $this->query($sql);
575 575
         }
576 576
         return $ret;
577 577
     }
@@ -583,18 +583,18 @@  discard block
 block discarded – undo
583 583
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
584 584
 	 *  @return	array					List of tables in an array
585 585
      */
586
-    function DDLListTables($database, $table='')
586
+    function DDLListTables($database, $table = '')
587 587
     {
588
-        $listtables=array();
588
+        $listtables = array();
589 589
 
590 590
         $like = '';
591 591
         if ($table) $like = "LIKE '".$table."'";
592
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
592
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
593 593
         //print $sql;
594 594
         $result = $this->query($sql);
595 595
         if ($result)
596 596
         {
597
-            while($row = $this->fetch_row($result))
597
+            while ($row = $this->fetch_row($result))
598 598
             {
599 599
                 $listtables[] = $row[0];
600 600
             }
@@ -610,15 +610,15 @@  discard block
 block discarded – undo
610 610
      */
611 611
     function DDLInfoTable($table)
612 612
     {
613
-        $infotables=array();
613
+        $infotables = array();
614 614
 
615
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
615
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
616 616
 
617
-        dol_syslog($sql,LOG_DEBUG);
617
+        dol_syslog($sql, LOG_DEBUG);
618 618
         $result = $this->query($sql);
619 619
         if ($result)
620 620
         {
621
-            while($row = $this->fetch_row($result))
621
+            while ($row = $this->fetch_row($result))
622 622
             {
623 623
                 $infotables[] = $row;
624 624
             }
@@ -638,72 +638,72 @@  discard block
 block discarded – undo
638 638
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
639 639
 	 *	@return	    int						<0 if KO, >=0 if OK
640 640
      */
641
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
641
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
642 642
     {
643 643
 	    // FIXME: $fulltext_keys parameter is unused
644 644
 
645 645
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
646 646
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
647 647
         $sql = "CREATE TABLE ".$table."(";
648
-        $i=0;
649
-        foreach($fields as $field_name => $field_desc)
648
+        $i = 0;
649
+        foreach ($fields as $field_name => $field_desc)
650 650
         {
651 651
         	$sqlfields[$i] = $field_name." ";
652
-			$sqlfields[$i]  .= $field_desc['type'];
653
-			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
652
+			$sqlfields[$i] .= $field_desc['type'];
653
+			if (preg_match("/^[^\s]/i", $field_desc['value'])) {
654 654
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
655 655
 			}
656
-			if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
656
+			if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
657 657
 				$sqlfields[$i]  .= " ".$field_desc['attribute'];
658 658
 			}
659
-			if( preg_match("/^[^\s]/i",$field_desc['default']))
659
+			if (preg_match("/^[^\s]/i", $field_desc['default']))
660 660
 			{
661
-				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
661
+				if ((preg_match("/null/i", $field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i", $field_desc['default']))) {
662 662
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
663 663
 				}
664 664
 				else {
665 665
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
666 666
 				}
667 667
 			}
668
-			if( preg_match("/^[^\s]/i",$field_desc['null'])) {
668
+			if (preg_match("/^[^\s]/i", $field_desc['null'])) {
669 669
 				$sqlfields[$i]  .= " ".$field_desc['null'];
670 670
 			}
671
-			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
671
+			if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
672 672
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
673 673
 			}
674 674
             $i++;
675 675
         }
676
-        if($primary_key != "")
676
+        if ($primary_key != "")
677 677
         $pk = "primary key(".$primary_key.")";
678 678
 
679
-        if(is_array($unique_keys)) {
679
+        if (is_array($unique_keys)) {
680 680
             $i = 0;
681
-            foreach($unique_keys as $key => $value)
681
+            foreach ($unique_keys as $key => $value)
682 682
             {
683 683
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
684 684
                 $i++;
685 685
             }
686 686
         }
687
-        if(is_array($keys))
687
+        if (is_array($keys))
688 688
         {
689 689
             $i = 0;
690
-            foreach($keys as $key => $value)
690
+            foreach ($keys as $key => $value)
691 691
             {
692 692
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
693 693
                 $i++;
694 694
             }
695 695
         }
696
-        $sql .= implode(',',$sqlfields);
697
-        if($primary_key != "")
696
+        $sql .= implode(',', $sqlfields);
697
+        if ($primary_key != "")
698 698
         $sql .= ",".$pk;
699
-        if($unique_keys != "")
700
-        $sql .= ",".implode(',',$sqluq);
701
-        if(is_array($keys))
702
-        $sql .= ",".implode(',',$sqlk);
703
-        $sql .=") engine=".$type;
704
-
705
-        dol_syslog($sql,LOG_DEBUG);
706
-        if(! $this -> query($sql))
699
+        if ($unique_keys != "")
700
+        $sql .= ",".implode(',', $sqluq);
701
+        if (is_array($keys))
702
+        $sql .= ",".implode(',', $sqlk);
703
+        $sql .= ") engine=".$type;
704
+
705
+        dol_syslog($sql, LOG_DEBUG);
706
+        if (!$this -> query($sql))
707 707
         return -1;
708 708
         else
709 709
         return 1;
@@ -716,11 +716,11 @@  discard block
 block discarded – undo
716 716
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
717 717
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
718 718
      */
719
-    function DDLDescTable($table,$field="")
719
+    function DDLDescTable($table, $field = "")
720 720
     {
721
-        $sql="DESC ".$table." ".$field;
721
+        $sql = "DESC ".$table." ".$field;
722 722
 
723
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
723
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
724 724
         $this->_results = $this->query($sql);
725 725
         return $this->_results;
726 726
     }
@@ -734,34 +734,34 @@  discard block
 block discarded – undo
734 734
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
735 735
 	 *	@return	int							<0 if KO, >0 if OK
736 736
      */
737
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
737
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
738 738
     {
739 739
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
740 740
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
741
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
742
-        $sql.= $field_desc['type'];
743
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
744
-            if (! in_array($field_desc['type'],array('date','datetime')))
741
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
742
+        $sql .= $field_desc['type'];
743
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
744
+            if (!in_array($field_desc['type'], array('date', 'datetime')))
745 745
             {
746
-                $sql.= "(".$field_desc['value'].")";
746
+                $sql .= "(".$field_desc['value'].")";
747 747
             }
748
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
749
-        $sql.= " ".$field_desc['attribute'];
750
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
751
-        $sql.= " ".$field_desc['null'];
752
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
748
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
749
+        $sql .= " ".$field_desc['attribute'];
750
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
751
+        $sql .= " ".$field_desc['null'];
752
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
753 753
         {
754
-            if(preg_match("/null/i",$field_desc['default']))
755
-            $sql.= " default ".$field_desc['default'];
754
+            if (preg_match("/null/i", $field_desc['default']))
755
+            $sql .= " default ".$field_desc['default'];
756 756
             else
757
-            $sql.= " default '".$field_desc['default']."'";
757
+            $sql .= " default '".$field_desc['default']."'";
758 758
         }
759
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
760
-        $sql.= " ".$field_desc['extra'];
761
-        $sql.= " ".$field_position;
759
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
760
+        $sql .= " ".$field_desc['extra'];
761
+        $sql .= " ".$field_position;
762 762
 
763
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
764
-        if($this->query($sql)) {
763
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
764
+        if ($this->query($sql)) {
765 765
             return 1;
766 766
         }
767 767
         return -1;
@@ -775,38 +775,38 @@  discard block
 block discarded – undo
775 775
 	 *	@param	string	$field_desc 		Array with description of field format
776 776
 	 *	@return	int							<0 if KO, >0 if OK
777 777
      */
778
-    function DDLUpdateField($table,$field_name,$field_desc)
778
+    function DDLUpdateField($table, $field_name, $field_desc)
779 779
     {
780 780
         $sql = "ALTER TABLE ".$table;
781 781
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
782 782
         if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
783
-        	$sql.="(".$field_desc['value'].")";
783
+        	$sql .= "(".$field_desc['value'].")";
784 784
         }
785 785
         if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
786 786
         {
787 787
         	// 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
788 788
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
789 789
         	{
790
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
790
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
791 791
         		$this->query($sqlbis);
792 792
         	}
793 793
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
794 794
         	{
795
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
795
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
796 796
         		$this->query($sqlbis);
797 797
         	}
798 798
 
799
-        	$sql.=" NOT NULL";
799
+        	$sql .= " NOT NULL";
800 800
         }
801 801
 
802 802
         if ($field_desc['default'] != '')
803 803
         {
804
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
805
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
804
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
805
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
806 806
         }
807 807
 
808
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
809
-        if (! $this->query($sql))
808
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
809
+        if (!$this->query($sql))
810 810
         return -1;
811 811
         else
812 812
         return 1;
@@ -819,14 +819,14 @@  discard block
 block discarded – undo
819 819
 	 *	@param	string	$field_name 	Name of field to drop
820 820
 	 *	@return	int						<0 if KO, >0 if OK
821 821
      */
822
-    function DDLDropField($table,$field_name)
822
+    function DDLDropField($table, $field_name)
823 823
     {
824
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
825
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
824
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
825
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
826 826
         if ($this->query($sql)) {
827 827
             return 1;
828 828
         }
829
-	    $this->error=$this->lasterror();
829
+	    $this->error = $this->lasterror();
830 830
 	    return -1;
831 831
     }
832 832
 
@@ -840,12 +840,12 @@  discard block
 block discarded – undo
840 840
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
841 841
 	 *	@return	int									<0 if KO, >=0 if OK
842 842
      */
843
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
843
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
844 844
     {
845 845
         $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
846
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
847
-        $resql=$this->query($sql);
848
-        if (! $resql)
846
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
847
+        $resql = $this->query($sql);
848
+        if (!$resql)
849 849
         {
850 850
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
851 851
             {
@@ -858,18 +858,18 @@  discard block
 block discarded – undo
858 858
             }
859 859
         }
860 860
         $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)."'";
861
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
862
-        $resql=$this->query($sql);
863
-        if (! $resql)
861
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
862
+        $resql = $this->query($sql);
863
+        if (!$resql)
864 864
         {
865 865
             return -1;
866 866
         }
867 867
 
868
-        $sql="FLUSH Privileges";
868
+        $sql = "FLUSH Privileges";
869 869
 
870 870
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
871
-        $resql=$this->query($sql);
872
-        if (! $resql)
871
+        $resql = $this->query($sql);
872
+        if (!$resql)
873 873
         {
874 874
             return -1;
875 875
         }
@@ -885,13 +885,13 @@  discard block
 block discarded – undo
885 885
      */
886 886
     function getDefaultCharacterSetDatabase()
887 887
     {
888
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
888
+        $resql = $this->query('SHOW VARIABLES LIKE \'character_set_database\'');
889 889
         if (!$resql)
890 890
         {
891 891
             // version Mysql < 4.1.1
892 892
             return $this->forcecharset;
893 893
         }
894
-        $liste=$this->fetch_array($resql);
894
+        $liste = $this->fetch_array($resql);
895 895
         $tmpval = $liste['Value'];
896 896
 
897 897
         return $tmpval;
@@ -904,12 +904,12 @@  discard block
 block discarded – undo
904 904
      */
905 905
     function getListOfCharacterSet()
906 906
     {
907
-        $resql=$this->query('SHOW CHARSET');
907
+        $resql = $this->query('SHOW CHARSET');
908 908
         $liste = array();
909 909
         if ($resql)
910 910
         {
911 911
             $i = 0;
912
-            while ($obj = $this->fetch_object($resql) )
912
+            while ($obj = $this->fetch_object($resql))
913 913
             {
914 914
                 $liste[$i]['charset'] = $obj->Charset;
915 915
                 $liste[$i]['description'] = $obj->Description;
@@ -931,13 +931,13 @@  discard block
 block discarded – undo
931 931
      */
932 932
     function getDefaultCollationDatabase()
933 933
     {
934
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
934
+        $resql = $this->query('SHOW VARIABLES LIKE \'collation_database\'');
935 935
         if (!$resql)
936 936
         {
937 937
             // version Mysql < 4.1.1
938 938
             return $this->forcecollate;
939 939
         }
940
-        $liste=$this->fetch_array($resql);
940
+        $liste = $this->fetch_array($resql);
941 941
         $tmpval = $liste['Value'];
942 942
 
943 943
         return $tmpval;
@@ -950,12 +950,12 @@  discard block
 block discarded – undo
950 950
      */
951 951
     function getListOfCollation()
952 952
     {
953
-        $resql=$this->query('SHOW COLLATION');
953
+        $resql = $this->query('SHOW COLLATION');
954 954
         $liste = array();
955 955
         if ($resql)
956 956
         {
957 957
             $i = 0;
958
-            while ($obj = $this->fetch_object($resql) )
958
+            while ($obj = $this->fetch_object($resql))
959 959
             {
960 960
                 $liste[$i]['collation'] = $obj->Collation;
961 961
                 $i++;
@@ -975,14 +975,14 @@  discard block
 block discarded – undo
975 975
      */
976 976
     function getPathOfDump()
977 977
     {
978
-        $fullpathofdump='/pathtomysqldump/mysqldump';
978
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
979 979
 
980
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
980
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
981 981
         if ($resql)
982 982
         {
983
-            $liste=$this->fetch_array($resql);
984
-            $basedir=$liste['Value'];
985
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
983
+            $liste = $this->fetch_array($resql);
984
+            $basedir = $liste['Value'];
985
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
986 986
         }
987 987
         return $fullpathofdump;
988 988
     }
@@ -994,14 +994,14 @@  discard block
 block discarded – undo
994 994
      */
995 995
     function getPathOfRestore()
996 996
     {
997
-        $fullpathofimport='/pathtomysql/mysql';
997
+        $fullpathofimport = '/pathtomysql/mysql';
998 998
 
999
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
999
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1000 1000
         if ($resql)
1001 1001
         {
1002
-            $liste=$this->fetch_array($resql);
1003
-            $basedir=$liste['Value'];
1004
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1002
+            $liste = $this->fetch_array($resql);
1003
+            $basedir = $liste['Value'];
1004
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1005 1005
         }
1006 1006
         return $fullpathofimport;
1007 1007
     }
@@ -1012,16 +1012,16 @@  discard block
 block discarded – undo
1012 1012
      * @param	string	$filter		Filter list on a particular value
1013 1013
 	 * @return	array				Array of key-values (key=>value)
1014 1014
      */
1015
-    function getServerParametersValues($filter='')
1015
+    function getServerParametersValues($filter = '')
1016 1016
     {
1017
-        $result=array();
1017
+        $result = array();
1018 1018
 
1019
-        $sql='SHOW VARIABLES';
1020
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1021
-        $resql=$this->query($sql);
1019
+        $sql = 'SHOW VARIABLES';
1020
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1021
+        $resql = $this->query($sql);
1022 1022
         if ($resql)
1023 1023
         {
1024
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1024
+        	while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1025 1025
         }
1026 1026
 
1027 1027
         return $result;
@@ -1033,16 +1033,16 @@  discard block
 block discarded – undo
1033 1033
      * @param	string	$filter		Filter list on a particular value
1034 1034
 	 * @return  array				Array of key-values (key=>value)
1035 1035
      */
1036
-    function getServerStatusValues($filter='')
1036
+    function getServerStatusValues($filter = '')
1037 1037
     {
1038
-        $result=array();
1038
+        $result = array();
1039 1039
 
1040
-        $sql='SHOW STATUS';
1041
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1042
-        $resql=$this->query($sql);
1040
+        $sql = 'SHOW STATUS';
1041
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1042
+        $resql = $this->query($sql);
1043 1043
         if ($resql)
1044 1044
         {
1045
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1045
+            while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1046 1046
         }
1047 1047
 
1048 1048
         return $result;
Please login to merge, or discard this patch.
htdocs/core/db/pgsql.class.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
 	 * @param	string	$query			SQL query string
465 465
 	 * @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).
466 466
      * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
467
-	 * @return	false|resource			Resultset of answer
467
+	 * @return	resource|null			Resultset of answer
468 468
 	 */
469 469
 	function query($query,$usesavepoint=0,$type='auto')
470 470
 	{
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
 	 *	Decrypt sensitive data in database
791 791
 	 *
792 792
 	 *	@param	int		$value			Value to decrypt
793
-	 * 	@return	string					Decrypted value if used
793
+	 * 	@return	integer					Decrypted value if used
794 794
 	 */
795 795
 	function decrypt($value)
796 796
 	{
Please login to merge, or discard this patch.
Braces   +155 added lines, -89 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);
@@ -313,10 +318,12 @@  discard block
 block discarded – undo
313 318
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
314 319
 			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
315 320
 			{
316
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
321
+				if ($reg[1] == $reg[2]) {
322
+					// If same table, we remove second one
317 323
 				{
318 324
 					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
319 325
 				}
326
+				}
320 327
 			}
321 328
 
322 329
 			// Remove () in the tables in FROM if 1 table
@@ -343,7 +350,9 @@  discard block
 block discarded – undo
343 350
 			// By default we do not (should be already done by db->escape function if required
344 351
 			// except for sql insert in data file that are mysql escaped so we removed them to
345 352
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
346
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
353
+			if ($unescapeslashquot) {
354
+				$line=preg_replace("/\\\'/","''",$line);
355
+			}
347 356
 
348 357
 			//print "type=".$type." newline=".$line."<br>\n";
349 358
 		}
@@ -361,8 +370,11 @@  discard block
 block discarded – undo
361 370
 	 */
362 371
 	function select_db($database)
363 372
 	{
364
-		if ($database == $this->database_name) return true;
365
-		else return false;
373
+		if ($database == $this->database_name) {
374
+			return true;
375
+		} else {
376
+			return false;
377
+		}
366 378
 	}
367 379
 
368 380
 	/**
@@ -389,7 +401,10 @@  discard block
 block discarded – undo
389 401
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
390 402
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
391 403
 
392
-		if (! $name) $name="postgres";    // When try to connect using admin user
404
+		if (! $name) {
405
+			$name="postgres";
406
+		}
407
+		// When try to connect using admin user
393 408
 
394 409
 		// try first Unix domain socket (local)
395 410
 		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
@@ -401,8 +416,12 @@  discard block
 block discarded – undo
401 416
 		// if local connection failed or not requested, use TCP/IP
402 417
 		if (! $this->db)
403 418
 		{
404
-		    if (! $host) $host = "localhost";
405
-			if (! $port) $port = 5432;
419
+		    if (! $host) {
420
+		    	$host = "localhost";
421
+		    }
422
+			if (! $port) {
423
+				$port = 5432;
424
+			}
406 425
 
407 426
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
408 427
 			$this->db = @pg_connect($con_string);
@@ -455,7 +474,9 @@  discard block
 block discarded – undo
455 474
     {
456 475
         if ($this->db)
457 476
         {
458
-          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
+          if ($this->transaction_opened > 0) {
478
+          	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
479
+          }
459 480
           $this->connected=false;
460 481
           return pg_close($this->db);
461 482
         }
@@ -490,8 +511,9 @@  discard block
 block discarded – undo
490 511
 				{
491 512
 					$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);
492 513
 					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
514
+				} else {
515
+					$loop=false;
493 516
 				}
494
-				else $loop=false;
495 517
 			}
496 518
 		}
497 519
 
@@ -500,30 +522,39 @@  discard block
 block discarded – undo
500 522
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
501 523
 		}
502 524
 
503
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
525
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
526
+			dol_syslog('sql='.$query, LOG_DEBUG);
527
+		}
504 528
 
505 529
 		$ret = @pg_query($this->db, $query);
506 530
 
507 531
 		//print $query;
508
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
532
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) {
533
+			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
509 534
 		{
510 535
 			if (! $ret)
511 536
 			{
512 537
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
513 538
 			    {
514 539
     				$this->lastqueryerror = $query;
540
+		}
515 541
     				$this->lasterror = $this->error();
516 542
     				$this->lasterrno = $this->errno();
517 543
 
518
-    				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
544
+    				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
545
+    					dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
546
+    				}
547
+    				// Log of request was not yet done previously
519 548
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
520 549
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
521 550
 			    }
522 551
 
523
-				if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
552
+				if ($usesavepoint && $this->transaction_opened) {
553
+					// Warning, after that errno will be erased
524 554
 				{
525 555
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
526 556
 				}
557
+				}
527 558
 			}
528 559
 			$this->lastquery=$query;
529 560
 			$this->_results = $ret;
@@ -613,7 +644,9 @@  discard block
 block discarded – undo
613 644
         // If resultset not provided, we take the last used by connexion
614 645
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
615 646
 		// Si resultset en est un, on libere la memoire
616
-		if (is_resource($resultset)) pg_free_result($resultset);
647
+		if (is_resource($resultset)) {
648
+			pg_free_result($resultset);
649
+		}
617 650
 	}
618 651
 
619 652
 
@@ -627,10 +660,17 @@  discard block
 block discarded – undo
627 660
 	function plimit($limit=0,$offset=0)
628 661
 	{
629 662
 		global $conf;
630
-        if (empty($limit)) return "";
631
-		if ($limit < 0) $limit=$conf->liste_limit;
632
-		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
633
-		else return " LIMIT $limit ";
663
+        if (empty($limit)) {
664
+        	return "";
665
+        }
666
+		if ($limit < 0) {
667
+			$limit=$conf->liste_limit;
668
+		}
669
+		if ($offset > 0) {
670
+			return " LIMIT ".$limit." OFFSET ".$offset." ";
671
+		} else {
672
+			return " LIMIT $limit ";
673
+		}
634 674
 	}
635 675
 
636 676
 
@@ -680,8 +720,7 @@  discard block
 block discarded – undo
680 720
 		if (! $this->connected) {
681 721
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
682 722
 			return 'DB_ERROR_FAILED_TO_CONNECT';
683
-		}
684
-		else {
723
+		} else {
685 724
 			// Constants to convert error code to a generic Dolibarr error code
686 725
 			$errorcode_map = array(
687 726
 			1004 => 'DB_ERROR_CANNOT_CREATE',
@@ -836,8 +875,12 @@  discard block
 block discarded – undo
836 875
 	 */
837 876
 	function DDLCreateDb($database,$charset='',$collation='',$owner='')
838 877
 	{
839
-	    if (empty($charset))   $charset=$this->forcecharset;
840
-		if (empty($collation)) $collation=$this->forcecollate;
878
+	    if (empty($charset)) {
879
+	    	$charset=$this->forcecharset;
880
+	    }
881
+		if (empty($collation)) {
882
+			$collation=$this->forcecollate;
883
+		}
841 884
 
842 885
 		// Test charset match LC_TYPE (pgsql error otherwise)
843 886
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
@@ -860,7 +903,9 @@  discard block
 block discarded – undo
860 903
 		$listtables=array();
861 904
 
862 905
 		$like = '';
863
-		if ($table) $like = " AND table_name LIKE '".$table."'";
906
+		if ($table) {
907
+			$like = " AND table_name LIKE '".$table."'";
908
+		}
864 909
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
865 910
         if ($result)
866 911
         {
@@ -936,26 +981,27 @@  discard block
 block discarded – undo
936 981
 		{
937 982
 			$sqlfields[$i] = $field_name." ";
938 983
 			$sqlfields[$i]  .= $field_desc['type'];
939
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
940
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
941
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
942
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
943
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
984
+			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
985
+						$sqlfields[$i]  .= "(".$field_desc['value'].")";
986
+			} else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
987
+						$sqlfields[$i]  .= " ".$field_desc['attribute'];
988
+			} else if( preg_match("/^[^\s]/i",$field_desc['default']))
944 989
 			{
945
-				if(preg_match("/null/i",$field_desc['default']))
946
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
947
-				else
948
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
990
+				if(preg_match("/null/i",$field_desc['default'])) {
991
+								$sqlfields[$i]  .= " default ".$field_desc['default'];
992
+				} else {
993
+								$sqlfields[$i]  .= " default '".$field_desc['default']."'";
994
+				}
995
+			} else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
996
+						$sqlfields[$i]  .= " ".$field_desc['null'];
997
+			} else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
998
+						$sqlfields[$i]  .= " ".$field_desc['extra'];
949 999
 			}
950
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
951
-			$sqlfields[$i]  .= " ".$field_desc['null'];
952
-
953
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
954
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
955 1000
 			$i++;
956 1001
 		}
957
-		if($primary_key != "")
958
-		$pk = "primary key(".$primary_key.")";
1002
+		if($primary_key != "") {
1003
+				$pk = "primary key(".$primary_key.")";
1004
+		}
959 1005
 
960 1006
 		if(is_array($unique_keys))
961 1007
 		{
@@ -976,19 +1022,23 @@  discard block
 block discarded – undo
976 1022
 			}
977 1023
 		}
978 1024
 		$sql .= implode(',',$sqlfields);
979
-		if($primary_key != "")
980
-		$sql .= ",".$pk;
981
-		if(is_array($unique_keys))
982
-		$sql .= ",".implode(',',$sqluq);
983
-		if(is_array($keys))
984
-		$sql .= ",".implode(',',$sqlk);
1025
+		if($primary_key != "") {
1026
+				$sql .= ",".$pk;
1027
+		}
1028
+		if(is_array($unique_keys)) {
1029
+				$sql .= ",".implode(',',$sqluq);
1030
+		}
1031
+		if(is_array($keys)) {
1032
+				$sql .= ",".implode(',',$sqlk);
1033
+		}
985 1034
 		$sql .=") type=".$type;
986 1035
 
987 1036
 		dol_syslog($sql,LOG_DEBUG);
988
-		if(! $this->query($sql))
989
-		return -1;
990
-		else
991
-		return 1;
1037
+		if(! $this->query($sql)) {
1038
+				return -1;
1039
+		} else {
1040
+				return 1;
1041
+		}
992 1042
 	}
993 1043
 
994 1044
 	/**
@@ -1026,7 +1076,9 @@  discard block
 block discarded – undo
1026 1076
 	{
1027 1077
 		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1028 1078
 		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1029
-		if ($field) $sql.= " AND attname = '".$field."'";
1079
+		if ($field) {
1080
+			$sql.= " AND attname = '".$field."'";
1081
+		}
1030 1082
 
1031 1083
 		dol_syslog($sql,LOG_DEBUG);
1032 1084
 		$this->_results = $this->query($sql);
@@ -1048,27 +1100,33 @@  discard block
 block discarded – undo
1048 1100
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1049 1101
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1050 1102
 		$sql .= $field_desc['type'];
1051
-		if(preg_match("/^[^\s]/i",$field_desc['value']))
1052
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1103
+		if(preg_match("/^[^\s]/i",$field_desc['value'])) {
1104
+				    if (! in_array($field_desc['type'],array('int','date','datetime')))
1053 1105
 		    {
1054 1106
 		        $sql.= "(".$field_desc['value'].")";
1107
+		}
1055 1108
 		    }
1056
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1057
-		$sql .= " ".$field_desc['attribute'];
1058
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1059
-		$sql .= " ".$field_desc['null'];
1060
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1061
-		if (preg_match("/null/i",$field_desc['default']))
1109
+		if (preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1110
+				$sql .= " ".$field_desc['attribute'];
1111
+		}
1112
+		if (preg_match("/^[^\s]/i",$field_desc['null'])) {
1113
+				$sql .= " ".$field_desc['null'];
1114
+		}
1115
+		if (preg_match("/^[^\s]/i",$field_desc['default'])) {
1116
+				if (preg_match("/null/i",$field_desc['default']))
1062 1117
 		$sql .= " default ".$field_desc['default'];
1063
-		else
1064
-		$sql .= " default '".$field_desc['default']."'";
1065
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1066
-		$sql .= " ".$field_desc['extra'];
1118
+		} else {
1119
+				$sql .= " default '".$field_desc['default']."'";
1120
+		}
1121
+		if (preg_match("/^[^\s]/i",$field_desc['extra'])) {
1122
+				$sql .= " ".$field_desc['extra'];
1123
+		}
1067 1124
 		$sql .= " ".$field_position;
1068 1125
 
1069 1126
 		dol_syslog($sql,LOG_DEBUG);
1070
-		if(! $this -> query($sql))
1071
-			return -1;
1127
+		if(! $this -> query($sql)) {
1128
+					return -1;
1129
+		}
1072 1130
 		return 1;
1073 1131
 	}
1074 1132
 
@@ -1095,8 +1153,7 @@  discard block
 block discarded – undo
1095 1153
         	{
1096 1154
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1097 1155
         		$this->query($sqlbis);
1098
-        	}
1099
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1156
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1100 1157
         	{
1101 1158
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1102 1159
         		$this->query($sqlbis);
@@ -1105,13 +1162,18 @@  discard block
 block discarded – undo
1105 1162
 
1106 1163
 		if ($field_desc['default'] != '')
1107 1164
 		{
1108
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1109
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1165
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
1166
+				$sql.=" DEFAULT ".$this->escape($field_desc['default']);
1167
+			} elseif ($field_desc['type'] == 'text') {
1168
+        		$sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
1169
+        	}
1170
+        	// Default not supported on text fields
1110 1171
 		}
1111 1172
 
1112 1173
 		dol_syslog($sql,LOG_DEBUG);
1113
-		if (! $this->query($sql))
1114
-			return -1;
1174
+		if (! $this->query($sql)) {
1175
+					return -1;
1176
+		}
1115 1177
 		return 1;
1116 1178
 	}
1117 1179
 
@@ -1146,8 +1208,9 @@  discard block
 block discarded – undo
1146 1208
 		{
1147 1209
             $liste=$this->fetch_array($resql);
1148 1210
 		    return $liste['server_encoding'];
1211
+		} else {
1212
+			return '';
1149 1213
 		}
1150
-		else return '';
1151 1214
 	}
1152 1215
 
1153 1216
 	/**
@@ -1187,8 +1250,9 @@  discard block
 block discarded – undo
1187 1250
 		{
1188 1251
 		    $liste=$this->fetch_array($resql);
1189 1252
 			return $liste['lc_collate'];
1253
+		} else {
1254
+			return '';
1190 1255
 		}
1191
-		else return '';
1192 1256
 	}
1193 1257
 
1194 1258
 	/**
@@ -1227,8 +1291,7 @@  discard block
 block discarded – undo
1227 1291
 		if (file_exists('/usr/bin/pg_dump'))
1228 1292
 		{
1229 1293
 		    $fullpathofdump='/usr/bin/pg_dump';
1230
-		}
1231
-		else
1294
+		} else
1232 1295
 		{
1233 1296
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1234 1297
 		    $resql=$this->query('SHOW data_directory');
@@ -1258,8 +1321,7 @@  discard block
 block discarded – undo
1258 1321
         if (file_exists('/usr/bin/'.$tool))
1259 1322
         {
1260 1323
             $fullpathofdump='/usr/bin/'.$tool;
1261
-        }
1262
-        else
1324
+        } else
1263 1325
         {
1264 1326
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1265 1327
             $resql=$this->query('SHOW data_directory');
@@ -1285,11 +1347,15 @@  discard block
 block discarded – undo
1285 1347
 		$result=array();
1286 1348
 
1287 1349
 		$resql='select name,setting from pg_settings';
1288
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1350
+		if ($filter) {
1351
+			$resql.=" WHERE name = '".$this->escape($filter)."'";
1352
+		}
1289 1353
 		$resql=$this->query($resql);
1290 1354
 		if ($resql)
1291 1355
 		{
1292
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1356
+			while ($obj=$this->fetch_object($resql)) {
1357
+				$result[$obj->name]=$obj->setting;
1358
+			}
1293 1359
 		}
1294 1360
 
1295 1361
 		return $result;
Please login to merge, or discard this patch.
Indentation   +283 added lines, -283 removed lines patch added patch discarded remove patch
@@ -35,14 +35,14 @@  discard block
 block discarded – undo
35 35
  */
36 36
 class DoliDBPgsql extends DoliDB
37 37
 {
38
-    //! Database type
38
+	//! Database type
39 39
 	public $type='pgsql';            // Name of manager
40
-    //! Database label
40
+	//! Database label
41 41
 	const LABEL='PostgreSQL';      // Label of manager
42 42
 	//! Charset
43 43
 	var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
44
-    //! Collate used to force collate when creating database
45
-    var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
44
+	//! Collate used to force collate when creating database
45
+	var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
46 46
 	//! Version min database
47 47
 	const VERSIONMIN='9.0.0';	// Version min database
48 48
 	/** @var resource Resultset of last query */
@@ -66,13 +66,13 @@  discard block
 block discarded – undo
66 66
 	{
67 67
 		global $conf,$langs;
68 68
 
69
-        // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
69
+		// Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
70 70
 		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
71 71
 		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
72 72
 
73 73
 		$this->database_user=$user;
74
-        $this->database_host=$host;
75
-        $this->database_port=$port;
74
+		$this->database_host=$host;
75
+		$this->database_port=$port;
76 76
 
77 77
 		$this->transaction_opened=0;
78 78
 
@@ -142,14 +142,14 @@  discard block
 block discarded – undo
142 142
 	}
143 143
 
144 144
 
145
-    /**
146
-     *  Convert a SQL request in Mysql syntax to native syntax
147
-     *
148
-     *  @param  string	$line   			SQL request line to convert
149
-     *  @param  string	$type				Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
150
-     *  @param	bool	$unescapeslashquot	Unescape slash quote with quote quote
151
-     *  @return string   					SQL request line converted
152
-     */
145
+	/**
146
+	 *  Convert a SQL request in Mysql syntax to native syntax
147
+	 *
148
+	 *  @param  string	$line   			SQL request line to convert
149
+	 *  @param  string	$type				Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
150
+	 *  @param	bool	$unescapeslashquot	Unescape slash quote with quote quote
151
+	 *  @return string   					SQL request line converted
152
+	 */
153 153
 	static function convertSQLFromMysql($line,$type='auto',$unescapeslashquot=false)
154 154
 	{
155 155
 		// Removed empty line if this is a comment line for SVN tagging
@@ -165,157 +165,157 @@  discard block
 block discarded – undo
165 165
 		{
166 166
 			// group_concat support (PgSQL >= 9.0)
167 167
 			// Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
168
-		    $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
168
+			$line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
169 169
 			$line = preg_replace('/ SEPARATOR/i', ',', $line);
170 170
 			$line = preg_replace('/STRING_AGG\(([^,\)]+)\)/i', 'STRING_AGG(\\1, \',\')', $line);
171 171
 			//print $line."\n";
172 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
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
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
-    			}
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);
196
-                    //$line = "-- ".$line." replaced by --\n".$newline;
197
-                    $line=$newline;
198
-    			}
199
-
200
-    			// tinyint type conversion
201
-    			$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
202
-    			$line=preg_replace('/tinyint/i','smallint',$line);
203
-
204
-    			// nuke unsigned
205
-    			$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
206
-
207
-    			// blob -> text
208
-    			$line=preg_replace('/\w*blob/i','text',$line);
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);
214
-
215
-    			$line=preg_replace('/text\([0-9]+\)/i','text',$line);
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);
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);
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);
232
-
233
-    			// nuke ON UPDATE CURRENT_TIMESTAMP
234
-    			$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
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
-    			}
241
-
242
-    			// We remove end of requests "AFTER fieldxxx"
243
-    			$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
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);
247
-
248
-                // Translate order to rename fields
249
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
250
-                {
251
-                	$line = "-- ".$line." replaced by --\n";
252
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
253
-                }
254
-
255
-                // Translate order to modify field format
256
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
257
-                {
258
-                    $line = "-- ".$line." replaced by --\n";
259
-                    $newreg3=$reg[3];
260
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
261
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
262
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
263
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
264
-                    $newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
265
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
266
-                    // TODO Add alter to set default value or null/not null if there is this in $reg[3]
267
-                }
268
-
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
-    			}
276
-
277
-                // Translate order to drop primary keys
278
-                // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
279
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg))
280
-                {
281
-                    $line = "-- ".$line." replaced by --\n";
282
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
283
-                }
284
-
285
-		        // Translate order to drop foreign keys
286
-                // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
287
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
288
-                {
289
-                    $line = "-- ".$line." replaced by --\n";
290
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
291
-                }
292
-
293
-                // Translate order to add foreign keys
294
-                // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
295
-                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
296
-                {
297
-                    $line=preg_replace('/;$/','',$line);
298
-                    $line.=" DEFERRABLE INITIALLY IMMEDIATE;";
299
-                }
300
-
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
-    			}
311
-            }
312
-
313
-            // To have postgresql case sensitive
314
-            $line=str_replace(' LIKE \'',' ILIKE \'',$line);
315
-            $line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
316
-
317
-            // Replace INSERT IGNORE into INSERT
318
-            $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
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
+				$line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
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
+				}
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);
196
+					//$line = "-- ".$line." replaced by --\n".$newline;
197
+					$line=$newline;
198
+				}
199
+
200
+				// tinyint type conversion
201
+				$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
202
+				$line=preg_replace('/tinyint/i','smallint',$line);
203
+
204
+				// nuke unsigned
205
+				$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
206
+
207
+				// blob -> text
208
+				$line=preg_replace('/\w*blob/i','text',$line);
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);
214
+
215
+				$line=preg_replace('/text\([0-9]+\)/i','text',$line);
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);
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);
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);
232
+
233
+				// nuke ON UPDATE CURRENT_TIMESTAMP
234
+				$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
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
+				}
241
+
242
+				// We remove end of requests "AFTER fieldxxx"
243
+				$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
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);
247
+
248
+				// Translate order to rename fields
249
+				if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
250
+				{
251
+					$line = "-- ".$line." replaced by --\n";
252
+					$line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
253
+				}
254
+
255
+				// Translate order to modify field format
256
+				if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
257
+				{
258
+					$line = "-- ".$line." replaced by --\n";
259
+					$newreg3=$reg[3];
260
+					$newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
261
+					$newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
262
+					$newreg3=preg_replace('/ NULL/i','',$newreg3);
263
+					$newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
264
+					$newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
265
+					$line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
266
+					// TODO Add alter to set default value or null/not null if there is this in $reg[3]
267
+				}
268
+
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
+				}
276
+
277
+				// Translate order to drop primary keys
278
+				// ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
279
+				if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg))
280
+				{
281
+					$line = "-- ".$line." replaced by --\n";
282
+					$line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
283
+				}
284
+
285
+				// Translate order to drop foreign keys
286
+				// ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
287
+				if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
288
+				{
289
+					$line = "-- ".$line." replaced by --\n";
290
+					$line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
291
+				}
292
+
293
+				// Translate order to add foreign keys
294
+				// ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
295
+				if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
296
+				{
297
+					$line=preg_replace('/;$/','',$line);
298
+					$line.=" DEFERRABLE INITIALLY IMMEDIATE;";
299
+				}
300
+
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
+				}
311
+			}
312
+
313
+			// To have postgresql case sensitive
314
+			$line=str_replace(' LIKE \'',' ILIKE \'',$line);
315
+			$line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
316
+
317
+			// Replace INSERT IGNORE into INSERT
318
+			$line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
319 319
 
320 320
 			// Delete using criteria on other table must not declare twice the deleted table
321 321
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
@@ -361,8 +361,8 @@  discard block
 block discarded – undo
361 361
 
362 362
 	/**
363 363
 	 *	Select a database
364
-     *  Ici postgresql n'a aucune fonction equivalente de mysql_select_db
365
-     *  On compare juste manuellement si la database choisie est bien celle activee par la connexion
364
+	 *  Ici postgresql n'a aucune fonction equivalente de mysql_select_db
365
+	 *  On compare juste manuellement si la database choisie est bien celle activee par la connexion
366 366
 	 *
367 367
 	 *	@param	    string	$database	Name of database
368 368
 	 *	@return	    bool				true if OK, false if KO
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		// if local connection failed or not requested, use TCP/IP
410 410
 		if (! $this->db)
411 411
 		{
412
-		    if (! $host) $host = "localhost";
412
+			if (! $host) $host = "localhost";
413 413
 			if (! $port) $port = 5432;
414 414
 
415 415
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
@@ -453,29 +453,29 @@  discard block
 block discarded – undo
453 453
 		return 'pgsql php driver';
454 454
 	}
455 455
 
456
-    /**
457
-     *  Close database connexion
458
-     *
459
-     *  @return     boolean     True if disconnect successfull, false otherwise
460
-     *  @see        connect
461
-     */
462
-    function close()
463
-    {
464
-        if ($this->db)
465
-        {
466
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
467
-          $this->connected=false;
468
-          return pg_close($this->db);
469
-        }
470
-        return false;
471
-    }
456
+	/**
457
+	 *  Close database connexion
458
+	 *
459
+	 *  @return     boolean     True if disconnect successfull, false otherwise
460
+	 *  @see        connect
461
+	 */
462
+	function close()
463
+	{
464
+		if ($this->db)
465
+		{
466
+		  if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
467
+		  $this->connected=false;
468
+		  return pg_close($this->db);
469
+		}
470
+		return false;
471
+	}
472 472
 
473 473
 	/**
474 474
 	 * Convert request to PostgreSQL syntax, execute it and return the resultset
475 475
 	 *
476 476
 	 * @param	string	$query			SQL query string
477 477
 	 * @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
-     * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
478
+	 * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
479 479
 	 * @return	false|resource			Resultset of answer
480 480
 	 */
481 481
 	function query($query,$usesavepoint=0,$type='auto')
@@ -517,16 +517,16 @@  discard block
 block discarded – undo
517 517
 		{
518 518
 			if (! $ret)
519 519
 			{
520
-			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
521
-			    {
522
-    				$this->lastqueryerror = $query;
523
-    				$this->lasterror = $this->error();
524
-    				$this->lasterrno = $this->errno();
520
+				if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
521
+				{
522
+					$this->lastqueryerror = $query;
523
+					$this->lasterror = $this->error();
524
+					$this->lasterrno = $this->errno();
525 525
 
526
-    				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
526
+					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
527 527
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
528 528
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
529
-			    }
529
+				}
530 530
 
531 531
 				if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
532 532
 				{
@@ -548,29 +548,29 @@  discard block
 block discarded – undo
548 548
 	 */
549 549
 	function fetch_object($resultset)
550 550
 	{
551
-        // If resultset not provided, we take the last used by connexion
551
+		// If resultset not provided, we take the last used by connexion
552 552
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
553 553
 		return pg_fetch_object($resultset);
554 554
 	}
555 555
 
556 556
 	/**
557
-     *	Return datas as an array
558
-     *
559
-     *	@param	resource	$resultset  Resultset of request
560
-     *	@return	false|array				Array
557
+	 *	Return datas as an array
558
+	 *
559
+	 *	@param	resource	$resultset  Resultset of request
560
+	 *	@return	false|array				Array
561 561
 	 */
562 562
 	function fetch_array($resultset)
563 563
 	{
564
-        // If resultset not provided, we take the last used by connexion
564
+		// If resultset not provided, we take the last used by connexion
565 565
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
566 566
 		return pg_fetch_array($resultset);
567 567
 	}
568 568
 
569 569
 	/**
570
-     *	Return datas as an array
571
-     *
572
-     *	@param	resource	$resultset  Resultset of request
573
-     *	@return	false|array				Array
570
+	 *	Return datas as an array
571
+	 *
572
+	 *	@param	resource	$resultset  Resultset of request
573
+	 *	@return	false|array				Array
574 574
 	 */
575 575
 	function fetch_row($resultset)
576 576
 	{
@@ -580,15 +580,15 @@  discard block
 block discarded – undo
580 580
 	}
581 581
 
582 582
 	/**
583
-     *	Return number of lines for result of a SELECT
584
-     *
585
-     *	@param	resourse	$resultset  Resulset of requests
586
-     *	@return int		    			Nb of lines, -1 on error
587
-     *	@see    affected_rows
583
+	 *	Return number of lines for result of a SELECT
584
+	 *
585
+	 *	@param	resourse	$resultset  Resulset of requests
586
+	 *	@return int		    			Nb of lines, -1 on error
587
+	 *	@see    affected_rows
588 588
 	 */
589 589
 	function num_rows($resultset)
590 590
 	{
591
-        // If resultset not provided, we take the last used by connexion
591
+		// If resultset not provided, we take the last used by connexion
592 592
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
593 593
 		return pg_num_rows($resultset);
594 594
 	}
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
 	 */
603 603
 	function affected_rows($resultset)
604 604
 	{
605
-        // If resultset not provided, we take the last used by connexion
605
+		// If resultset not provided, we take the last used by connexion
606 606
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
607 607
 		// pgsql necessite un resultset pour cette fonction contrairement
608 608
 		// a mysql qui prend un link de base
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	 */
619 619
 	function free($resultset=null)
620 620
 	{
621
-        // If resultset not provided, we take the last used by connexion
621
+		// If resultset not provided, we take the last used by connexion
622 622
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
623 623
 		// Si resultset en est un, on libere la memoire
624 624
 		if (is_resource($resultset)) pg_free_result($resultset);
@@ -626,16 +626,16 @@  discard block
 block discarded – undo
626 626
 
627 627
 
628 628
 	/**
629
-     *	Define limits and offset of request
630
-     *
631
-     *	@param	int		$limit      Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
632
-     *	@param	int		$offset     Numero of line from where starting fetch
633
-     *	@return	string      		String with SQL syntax to add a limit and offset
629
+	 *	Define limits and offset of request
630
+	 *
631
+	 *	@param	int		$limit      Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
632
+	 *	@param	int		$offset     Numero of line from where starting fetch
633
+	 *	@return	string      		String with SQL syntax to add a limit and offset
634 634
 	 */
635 635
 	function plimit($limit=0,$offset=0)
636 636
 	{
637 637
 		global $conf;
638
-        if (empty($limit)) return "";
638
+		if (empty($limit)) return "";
639 639
 		if ($limit < 0) $limit=$conf->liste_limit;
640 640
 		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
641 641
 		else return " LIMIT $limit ";
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
 		return pg_escape_string($stringtoencode);
654 654
 	}
655 655
 
656
-    /**
656
+	/**
657 657
 	 *   Convert (by PHP) a GM Timestamp date into a GM string date to insert into a date field.
658 658
 	 *   Function to use to build INSERT, UPDATE or WHERE predica
659 659
 	 *
@@ -666,8 +666,8 @@  discard block
 block discarded – undo
666 666
 	}
667 667
 
668 668
 	/**
669
-     *  Format a SQL IF
670
-     *
669
+	 *  Format a SQL IF
670
+	 *
671 671
 	 *  @param	string	$test           Test string (example: 'cd.statut=0', 'field IS NULL')
672 672
 	 *  @param	string	$resok          resultat si test egal
673 673
 	 *  @param	string	$resko          resultat si test non egal
@@ -776,12 +776,12 @@  discard block
 block discarded – undo
776 776
 	}
777 777
 
778 778
 	/**
779
-     *  Encrypt sensitive data in database
780
-     *  Warning: This function includes the escape, so it must use direct value
781
-     *
782
-     *  @param  string  $fieldorvalue   Field name or value to encrypt
783
-     *  @param	int		$withQuotes     Return string with quotes
784
-     *  @return string          		XXX(field) or XXX('value') or field or 'value'
779
+	 *  Encrypt sensitive data in database
780
+	 *  Warning: This function includes the escape, so it must use direct value
781
+	 *
782
+	 *  @param  string  $fieldorvalue   Field name or value to encrypt
783
+	 *  @param	int		$withQuotes     Return string with quotes
784
+	 *  @return string          		XXX(field) or XXX('value') or field or 'value'
785 785
 	 */
786 786
 	function encrypt($fieldorvalue, $withQuotes=0)
787 787
 	{
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 	 */
845 845
 	function DDLCreateDb($database,$charset='',$collation='',$owner='')
846 846
 	{
847
-	    if (empty($charset))   $charset=$this->forcecharset;
847
+		if (empty($charset))   $charset=$this->forcecharset;
848 848
 		if (empty($collation)) $collation=$this->forcecollate;
849 849
 
850 850
 		// Test charset match LC_TYPE (pgsql error otherwise)
@@ -870,13 +870,13 @@  discard block
 block discarded – undo
870 870
 		$like = '';
871 871
 		if ($table) $like = " AND table_name LIKE '".$table."'";
872 872
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
873
-        if ($result)
874
-        {
875
-    		while($row = $this->fetch_row($result))
876
-    		{
877
-    			$listtables[] = $row[0];
878
-    		}
879
-        }
873
+		if ($result)
874
+		{
875
+			while($row = $this->fetch_row($result))
876
+			{
877
+				$listtables[] = $row[0];
878
+			}
879
+		}
880 880
 		return $listtables;
881 881
 	}
882 882
 
@@ -911,12 +911,12 @@  discard block
 block discarded – undo
911 911
 		$result = $this->query($sql);
912 912
 		if ($result)
913 913
 		{
914
-    		 while($row = $this->fetch_row($result))
915
-    		 {
916
-    			$infotables[] = $row;
917
-    		 }
914
+			 while($row = $this->fetch_row($result))
915
+			 {
916
+				$infotables[] = $row;
917
+			 }
918 918
 		}
919
-        return $infotables;
919
+		return $infotables;
920 920
 	}
921 921
 
922 922
 
@@ -1057,10 +1057,10 @@  discard block
 block discarded – undo
1057 1057
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1058 1058
 		$sql .= $field_desc['type'];
1059 1059
 		if(preg_match("/^[^\s]/i",$field_desc['value']))
1060
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1061
-		    {
1062
-		        $sql.= "(".$field_desc['value'].")";
1063
-		    }
1060
+			if (! in_array($field_desc['type'],array('int','date','datetime')))
1061
+			{
1062
+				$sql.= "(".$field_desc['value'].")";
1063
+			}
1064 1064
 		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1065 1065
 		$sql .= " ".$field_desc['attribute'];
1066 1066
 		if (preg_match("/^[^\s]/i",$field_desc['null']))
@@ -1098,23 +1098,23 @@  discard block
 block discarded – undo
1098 1098
 
1099 1099
 		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
1100 1100
 		{
1101
-        	// 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
1102
-        	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1103
-        	{
1104
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1105
-        		$this->query($sqlbis);
1106
-        	}
1107
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1108
-        	{
1109
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1110
-        		$this->query($sqlbis);
1111
-        	}
1101
+			// 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
1102
+			if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1103
+			{
1104
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1105
+				$this->query($sqlbis);
1106
+			}
1107
+			elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1108
+			{
1109
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1110
+				$this->query($sqlbis);
1111
+			}
1112 1112
 		}
1113 1113
 
1114 1114
 		if ($field_desc['default'] != '')
1115 1115
 		{
1116 1116
 			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1117
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1117
+			elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1118 1118
 		}
1119 1119
 
1120 1120
 		dol_syslog($sql,LOG_DEBUG);
@@ -1152,8 +1152,8 @@  discard block
 block discarded – undo
1152 1152
 		$resql=$this->query('SHOW SERVER_ENCODING');
1153 1153
 		if ($resql)
1154 1154
 		{
1155
-            $liste=$this->fetch_array($resql);
1156
-		    return $liste['server_encoding'];
1155
+			$liste=$this->fetch_array($resql);
1156
+			return $liste['server_encoding'];
1157 1157
 		}
1158 1158
 		else return '';
1159 1159
 	}
@@ -1193,7 +1193,7 @@  discard block
 block discarded – undo
1193 1193
 		$resql=$this->query('SHOW LC_COLLATE');
1194 1194
 		if ($resql)
1195 1195
 		{
1196
-		    $liste=$this->fetch_array($resql);
1196
+			$liste=$this->fetch_array($resql);
1197 1197
 			return $liste['lc_collate'];
1198 1198
 		}
1199 1199
 		else return '';
@@ -1234,28 +1234,28 @@  discard block
 block discarded – undo
1234 1234
 
1235 1235
 		if (file_exists('/usr/bin/pg_dump'))
1236 1236
 		{
1237
-		    $fullpathofdump='/usr/bin/pg_dump';
1237
+			$fullpathofdump='/usr/bin/pg_dump';
1238 1238
 		}
1239 1239
 		else
1240 1240
 		{
1241
-            // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1242
-		    $resql=$this->query('SHOW data_directory');
1243
-    		if ($resql)
1244
-    		{
1245
-    			$liste=$this->fetch_array($resql);
1246
-    			$basedir=$liste['data_directory'];
1247
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1248
-    		}
1241
+			// TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1242
+			$resql=$this->query('SHOW data_directory');
1243
+			if ($resql)
1244
+			{
1245
+				$liste=$this->fetch_array($resql);
1246
+				$basedir=$liste['data_directory'];
1247
+				$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1248
+			}
1249 1249
 		}
1250 1250
 
1251 1251
 		return $fullpathofdump;
1252 1252
 	}
1253 1253
 
1254
-    /**
1255
-     *	Return full path of restore program
1256
-     *
1257
-     *	@return		string		Full path of restore program
1258
-     */
1254
+	/**
1255
+	 *	Return full path of restore program
1256
+	 *
1257
+	 *	@return		string		Full path of restore program
1258
+	 */
1259 1259
 	function getPathOfRestore()
1260 1260
 	{
1261 1261
 		//$tool='pg_restore';
@@ -1263,21 +1263,21 @@  discard block
 block discarded – undo
1263 1263
 
1264 1264
 		$fullpathofdump='/pathtopgrestore/'.$tool;
1265 1265
 
1266
-        if (file_exists('/usr/bin/'.$tool))
1267
-        {
1268
-            $fullpathofdump='/usr/bin/'.$tool;
1269
-        }
1270
-        else
1271
-        {
1272
-            // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1273
-            $resql=$this->query('SHOW data_directory');
1274
-            if ($resql)
1275
-            {
1276
-                $liste=$this->fetch_array($resql);
1277
-                $basedir=$liste['data_directory'];
1278
-                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1279
-            }
1280
-        }
1266
+		if (file_exists('/usr/bin/'.$tool))
1267
+		{
1268
+			$fullpathofdump='/usr/bin/'.$tool;
1269
+		}
1270
+		else
1271
+		{
1272
+			// TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1273
+			$resql=$this->query('SHOW data_directory');
1274
+			if ($resql)
1275
+			{
1276
+				$liste=$this->fetch_array($resql);
1277
+				$basedir=$liste['data_directory'];
1278
+				$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1279
+			}
1280
+		}
1281 1281
 
1282 1282
 		return $fullpathofdump;
1283 1283
 	}
Please login to merge, or discard this patch.
Spacing   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
  *	\brief      Fichier de la classe permettant de gerer une base pgsql
29 29
  */
30 30
 
31
-require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
31
+require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
32 32
 
33 33
 /**
34 34
  *	Class to drive a Postgresql database for Dolibarr
@@ -36,15 +36,15 @@  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
41
+	const LABEL = 'PostgreSQL'; // Label of manager
42 42
 	//! Charset
43
-	var $forcecharset='UTF8';       // Can't be static as it may be forced with a dynamic value
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
-    var $forcecollate='';			// Can't be static as it may be forced with a dynamic value
45
+    var $forcecollate = ''; // Can't be static as it may be forced with a dynamic value
46 46
 	//! Version min database
47
-	const VERSIONMIN='9.0.0';	// Version min database
47
+	const VERSIONMIN = '9.0.0'; // Version min database
48 48
 	/** @var resource Resultset of last query */
49 49
 	private $_results;
50 50
 
@@ -62,37 +62,37 @@  discard block
 block discarded – undo
62 62
 	 *	@param	    string	$name		Nom de la database
63 63
 	 *	@param	    int		$port		Port of database server
64 64
 	 */
65
-	function __construct($type, $host, $user, $pass, $name='', $port=0)
65
+	function __construct($type, $host, $user, $pass, $name = '', $port = 0)
66 66
 	{
67
-		global $conf,$langs;
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;
74
-        $this->database_host=$host;
75
-        $this->database_port=$port;
73
+		$this->database_user = $user;
74
+        $this->database_host = $host;
75
+        $this->database_port = $port;
76 76
 
77
-		$this->transaction_opened=0;
77
+		$this->transaction_opened = 0;
78 78
 
79 79
 		//print "Name DB: $host,$user,$pass,$name<br>";
80 80
 
81
-		if (! function_exists("pg_connect"))
81
+		if (!function_exists("pg_connect"))
82 82
 		{
83 83
 			$this->connected = false;
84 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);
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 87
 			return $this->ok;
88 88
 		}
89 89
 
90
-		if (! $host)
90
+		if (!$host)
91 91
 		{
92 92
 			$this->connected = false;
93 93
 			$this->ok = false;
94
-			$this->error=$langs->trans("ErrorWrongHostParameter");
95
-			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters",LOG_ERR);
94
+			$this->error = $langs->trans("ErrorWrongHostParameter");
95
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
96 96
 			return $this->ok;
97 97
 		}
98 98
 
@@ -110,8 +110,8 @@  discard block
 block discarded – undo
110 110
 			// host, login ou password incorrect
111 111
 			$this->connected = false;
112 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);
113
+			$this->error = 'Host, login or password incorrect';
114
+			dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error, LOG_ERR);
115 115
 		}
116 116
 
117 117
 		// Si connexion serveur ok et si connexion base demandee, on essaie connexion base
@@ -128,8 +128,8 @@  discard block
 block discarded – undo
128 128
 				$this->database_selected = false;
129 129
 				$this->database_name = '';
130 130
 				$this->ok = false;
131
-				$this->error=$this->error();
132
-				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
131
+				$this->error = $this->error();
132
+				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error, LOG_ERR);
133 133
 			}
134 134
 		}
135 135
 		else
@@ -150,14 +150,14 @@  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)
153
+	static function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
154 154
 	{
155 155
 		// Removed empty line if this is a comment line for SVN tagging
156
-		if (preg_match('/^--\s\$Id/i',$line)) {
156
+		if (preg_match('/^--\s\$Id/i', $line)) {
157 157
 			return '';
158 158
 		}
159 159
 		// Return line if this is a comment
160
-		if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
160
+		if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
161 161
 		{
162 162
 			return $line;
163 163
 		}
@@ -172,186 +172,186 @@  discard block
 block discarded – undo
172 172
 
173 173
 		    if ($type == 'auto')
174 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';
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 178
 		    }
179 179
 
180
-    		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
180
+    		$line = preg_replace('/ as signed\)/i', ' as integer)', $line);
181 181
 
182 182
 		    if ($type == 'dml')
183 183
 		    {
184
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
184
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
185 185
 
186 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);
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 191
     			}
192 192
 
193 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);
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
-                    $line=$newline;
197
+                    $line = $newline;
198 198
     			}
199 199
 
200 200
     			// tinyint type conversion
201
-    			$line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
202
-    			$line=preg_replace('/tinyint/i','smallint',$line);
201
+    			$line = preg_replace('/tinyint\(?[0-9]*\)?/', 'smallint', $line);
202
+    			$line = preg_replace('/tinyint/i', 'smallint', $line);
203 203
 
204 204
     			// nuke unsigned
205
-    			$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
205
+    			$line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
206 206
 
207 207
     			// blob -> text
208
-    			$line=preg_replace('/\w*blob/i','text',$line);
208
+    			$line = preg_replace('/\w*blob/i', 'text', $line);
209 209
 
210 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);
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 217
     			// change not null datetime field to null valid ones
218 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);
219
+    			$line = preg_replace('/datetime not null/i', 'datetime', $line);
220
+    			$line = preg_replace('/datetime/i', 'timestamp', $line);
221 221
 
222 222
     			// double -> numeric
223
-    			$line=preg_replace('/^double/i','numeric',$line);
224
-    			$line=preg_replace('/(\s*)double/i','\\1numeric',$line);
223
+    			$line = preg_replace('/^double/i', 'numeric', $line);
224
+    			$line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
225 225
     			// float -> numeric
226
-    			$line=preg_replace('/^float/i','numeric',$line);
227
-    			$line=preg_replace('/(\s*)float/i','\\1numeric',$line);
226
+    			$line = preg_replace('/^float/i', 'numeric', $line);
227
+    			$line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
228 228
 
229 229
     			//Check tms timestamp field case (in Mysql this field is defautled to now and
230 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);
231
+    			$line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
232 232
 
233 233
     			// nuke ON UPDATE CURRENT_TIMESTAMP
234
-    			$line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
234
+    			$line = preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
235 235
 
236 236
     			// unique index(field1,field2)
237
-    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
237
+    			if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
238 238
     			{
239
-    				$line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
239
+    				$line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
240 240
     			}
241 241
 
242 242
     			// We remove end of requests "AFTER fieldxxx"
243
-    			$line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
243
+    			$line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
244 244
 
245 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);
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
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
249
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
250 250
                 {
251 251
                 	$line = "-- ".$line." replaced by --\n";
252
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
252
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
253 253
                 }
254 254
 
255 255
                 // Translate order to modify field format
256
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
256
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
257 257
                 {
258 258
                     $line = "-- ".$line." replaced by --\n";
259
-                    $newreg3=$reg[3];
260
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
261
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
262
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
263
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
264
-                    $newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
265
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
259
+                    $newreg3 = $reg[3];
260
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
261
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
262
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
263
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
264
+                    $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
265
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
266 266
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
267 267
                 }
268 268
 
269 269
                 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
270 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))
271
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
272 272
     			{
273 273
     				$line = "-- ".$line." replaced by --\n";
274
-    				$line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
274
+    				$line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
275 275
     			}
276 276
 
277 277
                 // Translate order to drop primary keys
278 278
                 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
279
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg))
279
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg))
280 280
                 {
281 281
                     $line = "-- ".$line." replaced by --\n";
282
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
282
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
283 283
                 }
284 284
 
285 285
 		        // Translate order to drop foreign keys
286 286
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
287
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
287
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
288 288
                 {
289 289
                     $line = "-- ".$line." replaced by --\n";
290
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
290
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
291 291
                 }
292 292
 
293 293
                 // Translate order to add foreign keys
294 294
                 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
295
-                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
295
+                if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
296 296
                 {
297
-                    $line=preg_replace('/;$/','',$line);
298
-                    $line.=" DEFERRABLE INITIALLY IMMEDIATE;";
297
+                    $line = preg_replace('/;$/', '', $line);
298
+                    $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
299 299
                 }
300 300
 
301 301
                 // alter table add [unique] [index] (field1, field2 ...)
302 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))
303
+    			if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
304 304
     			{
305
-    				$fieldlist=$reg[4];
306
-    				$idxname=$reg[3];
307
-    				$tablename=$reg[1];
305
+    				$fieldlist = $reg[4];
306
+    				$idxname = $reg[3];
307
+    				$tablename = $reg[1];
308 308
     				$line = "-- ".$line." replaced by --\n";
309
-    				$line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
309
+    				$line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
310 310
     			}
311 311
             }
312 312
 
313 313
             // To have postgresql case sensitive
314
-            $line=str_replace(' LIKE \'',' ILIKE \'',$line);
315
-            $line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
314
+            $line = str_replace(' LIKE \'', ' ILIKE \'', $line);
315
+            $line = str_replace(' LIKE BINARY \'', ' LIKE \'', $line);
316 316
 
317 317
             // Replace INSERT IGNORE into INSERT
318
-            $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
318
+            $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
319 319
 
320 320
 			// Delete using criteria on other table must not declare twice the deleted table
321 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))
322
+			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
323 323
 			{
324 324
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
325 325
 				{
326
-					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
326
+					$line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
327 327
 				}
328 328
 			}
329 329
 
330 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);
331
+			$line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
332 332
 			//print $line."\n";
333 333
 
334 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);
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 336
 			//print $line."\n";
337 337
 
338 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);
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 340
 			//print $line."\n";
341 341
 
342 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);
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 344
 			//print $line."\n";
345 345
 
346 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);
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 348
 			//print $line."\n";
349 349
 
350 350
 			// Replace espacing \' by ''.
351 351
 			// By default we do not (should be already done by db->escape function if required
352 352
 			// except for sql insert in data file that are mysql escaped so we removed them to
353 353
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
354
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
354
+			if ($unescapeslashquot) $line = preg_replace("/\\\'/", "''", $line);
355 355
 
356 356
 			//print "type=".$type." newline=".$line."<br>\n";
357 357
 		}
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 	 *	@return		false|resource			Database access handler
385 385
 	 *	@see		close
386 386
 	 */
387
-	function connect($host, $login, $passwd, $name, $port=0)
387
+	function connect($host, $login, $passwd, $name, $port = 0)
388 388
 	{
389 389
 		// use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
390 390
 
@@ -397,20 +397,20 @@  discard block
 block discarded – undo
397 397
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
398 398
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
399 399
 
400
-		if (! $name) $name="postgres";    // When try to connect using admin user
400
+		if (!$name) $name = "postgres"; // When try to connect using admin user
401 401
 
402 402
 		// try first Unix domain socket (local)
403
-		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
403
+		if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT'))
404 404
 		{
405
-			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'";    // $name may be empty
405
+			$con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
406 406
 			$this->db = @pg_connect($con_string);
407 407
 		}
408 408
 
409 409
 		// if local connection failed or not requested, use TCP/IP
410
-		if (! $this->db)
410
+		if (!$this->db)
411 411
 		{
412
-		    if (! $host) $host = "localhost";
413
-			if (! $port) $port = 5432;
412
+		    if (!$host) $host = "localhost";
413
+			if (!$port) $port = 5432;
414 414
 
415 415
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
416 416
 			$this->db = @pg_connect($con_string);
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 		if ($this->db)
421 421
 		{
422 422
 			$this->database_name = $name;
423
-			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);	// Set verbosity to max
423
+			pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
424 424
 			pg_query($this->db, "set datestyle = 'ISO, YMD';");
425 425
 		}
426 426
 
@@ -434,10 +434,10 @@  discard block
 block discarded – undo
434 434
 	 */
435 435
 	function getVersion()
436 436
 	{
437
-		$resql=$this->query('SHOW server_version');
437
+		$resql = $this->query('SHOW server_version');
438 438
 		if ($resql)
439 439
 		{
440
-		  $liste=$this->fetch_array($resql);
440
+		  $liste = $this->fetch_array($resql);
441 441
 		  return $liste['server_version'];
442 442
 		}
443 443
 		return '';
@@ -463,8 +463,8 @@  discard block
 block discarded – undo
463 463
     {
464 464
         if ($this->db)
465 465
         {
466
-          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
467
-          $this->connected=false;
466
+          if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
467
+          $this->connected = false;
468 468
           return pg_close($this->db);
469 469
         }
470 470
         return false;
@@ -478,28 +478,28 @@  discard block
 block discarded – undo
478 478
      * @param   string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
479 479
 	 * @return	false|resource			Resultset of answer
480 480
 	 */
481
-	function query($query,$usesavepoint=0,$type='auto')
481
+	function query($query, $usesavepoint = 0, $type = 'auto')
482 482
 	{
483 483
 		global $conf;
484 484
 
485 485
 		$query = trim($query);
486 486
 
487 487
 		// Convert MySQL syntax to PostgresSQL syntax
488
-		$query=$this->convertSQLFromMysql($query,$type,($this->unescapeslashquot && $this->standard_conforming_strings));
488
+		$query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
489 489
 		//print "After convertSQLFromMysql:\n".$query."<br>\n";
490 490
 
491
-		if (! empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
491
+		if (!empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST))
492 492
 		{
493 493
 			// Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
494
-			$loop=true;
494
+			$loop = true;
495 495
 			while ($loop)
496 496
 			{
497
-				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))
497
+				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))
498 498
 				{
499
-					$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);
500
-					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
499
+					$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);
500
+					dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
501 501
 				}
502
-				else $loop=false;
502
+				else $loop = false;
503 503
 			}
504 504
 		}
505 505
 
@@ -508,14 +508,14 @@  discard block
 block discarded – undo
508 508
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
509 509
 		}
510 510
 
511
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
511
+		if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
512 512
 
513 513
 		$ret = @pg_query($this->db, $query);
514 514
 
515 515
 		//print $query;
516
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
516
+		if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
517 517
 		{
518
-			if (! $ret)
518
+			if (!$ret)
519 519
 			{
520 520
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
521 521
 			    {
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
     				$this->lasterror = $this->error();
524 524
     				$this->lasterrno = $this->errno();
525 525
 
526
-    				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
526
+    				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
527 527
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
528 528
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
529 529
 			    }
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
534 534
 				}
535 535
 			}
536
-			$this->lastquery=$query;
536
+			$this->lastquery = $query;
537 537
 			$this->_results = $ret;
538 538
 		}
539 539
 
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 	function fetch_object($resultset)
550 550
 	{
551 551
         // If resultset not provided, we take the last used by connexion
552
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
552
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
553 553
 		return pg_fetch_object($resultset);
554 554
 	}
555 555
 
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
 	function fetch_array($resultset)
563 563
 	{
564 564
         // If resultset not provided, we take the last used by connexion
565
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
565
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
566 566
 		return pg_fetch_array($resultset);
567 567
 	}
568 568
 
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 	function fetch_row($resultset)
576 576
 	{
577 577
 		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
578
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
578
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
579 579
 		return pg_fetch_row($resultset);
580 580
 	}
581 581
 
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 	function num_rows($resultset)
590 590
 	{
591 591
         // If resultset not provided, we take the last used by connexion
592
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
592
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
593 593
 		return pg_num_rows($resultset);
594 594
 	}
595 595
 
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 	function affected_rows($resultset)
604 604
 	{
605 605
         // If resultset not provided, we take the last used by connexion
606
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
606
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
607 607
 		// pgsql necessite un resultset pour cette fonction contrairement
608 608
 		// a mysql qui prend un link de base
609 609
 		return pg_affected_rows($resultset);
@@ -616,10 +616,10 @@  discard block
 block discarded – undo
616 616
 	 * @param	resource	$resultset  Result set of request
617 617
 	 * @return	void
618 618
 	 */
619
-	function free($resultset=null)
619
+	function free($resultset = null)
620 620
 	{
621 621
         // If resultset not provided, we take the last used by connexion
622
-		if (! is_resource($resultset)) { $resultset=$this->_results; }
622
+		if (!is_resource($resultset)) { $resultset = $this->_results; }
623 623
 		// Si resultset en est un, on libere la memoire
624 624
 		if (is_resource($resultset)) pg_free_result($resultset);
625 625
 	}
@@ -632,11 +632,11 @@  discard block
 block discarded – undo
632 632
      *	@param	int		$offset     Numero of line from where starting fetch
633 633
      *	@return	string      		String with SQL syntax to add a limit and offset
634 634
 	 */
635
-	function plimit($limit=0,$offset=0)
635
+	function plimit($limit = 0, $offset = 0)
636 636
 	{
637 637
 		global $conf;
638 638
         if (empty($limit)) return "";
639
-		if ($limit < 0) $limit=$conf->liste_limit;
639
+		if ($limit < 0) $limit = $conf->liste_limit;
640 640
 		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
641 641
 		else return " LIMIT $limit ";
642 642
 	}
@@ -662,7 +662,7 @@  discard block
 block discarded – undo
662 662
 	 */
663 663
 	function idate($param)
664 664
 	{
665
-		return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
665
+		return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
666 666
 	}
667 667
 
668 668
 	/**
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
 	 *  @param	string	$resko          resultat si test non egal
674 674
 	 *  @return	string          		chaine formate SQL
675 675
 	 */
676
-	function ifsql($test,$resok,$resko)
676
+	function ifsql($test, $resok, $resko)
677 677
 	{
678 678
 		return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
679 679
 	}
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 	 */
686 686
 	function errno()
687 687
 	{
688
-		if (! $this->connected) {
688
+		if (!$this->connected) {
689 689
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
690 690
 			return 'DB_ERROR_FAILED_TO_CONNECT';
691 691
 		}
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 			42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
708 708
 			'42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
709 709
 			'23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
710
-			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP',		// May also be Type xxx does not exists
710
+			'42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
711 711
 			'42601' => 'DB_ERROR_SYNTAX',
712 712
 			'42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
713 713
 			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
@@ -721,18 +721,18 @@  discard block
 block discarded – undo
721 721
 			'42P04' => 'DB_DATABASE_ALREADY_EXISTS'
722 722
 			);
723 723
 
724
-			$errorlabel=pg_last_error($this->db);
725
-			$errorcode='';
726
-			if (preg_match('/: *([0-9P]+):/',$errorlabel,$reg))
724
+			$errorlabel = pg_last_error($this->db);
725
+			$errorcode = '';
726
+			if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg))
727 727
 			{
728
-				$errorcode=$reg[1];
728
+				$errorcode = $reg[1];
729 729
 				if (isset($errorcode_map[$errorcode]))
730 730
 				{
731 731
 					return $errorcode_map[$errorcode];
732 732
 				}
733 733
 			}
734
-			$errno=$errorcode?$errorcode:$errorlabel;
735
-			return ($errno?'DB_ERROR_'.$errno:'0');
734
+			$errno = $errorcode ? $errorcode : $errorlabel;
735
+			return ($errno ? 'DB_ERROR_'.$errno : '0');
736 736
 		}
737 737
 		//                '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
738 738
 		//                '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
@@ -761,17 +761,17 @@  discard block
 block discarded – undo
761 761
 	 * @param	string	$fieldid	Field name
762 762
 	 * @return  string     			Id of row
763 763
 	 */
764
-	function last_insert_id($tab,$fieldid='rowid')
764
+	function last_insert_id($tab, $fieldid = 'rowid')
765 765
 	{
766 766
 		//$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
767
-		$result = pg_query($this->db,"SELECT currval('".$tab."_".$fieldid."_seq')");
768
-		if (! $result)
767
+		$result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
768
+		if (!$result)
769 769
 		{
770 770
 			print pg_last_error($this->db);
771 771
 			exit;
772 772
 		}
773 773
 		//$nbre = pg_num_rows($result);
774
-		$row = pg_fetch_result($result,0,0);
774
+		$row = pg_fetch_result($result, 0, 0);
775 775
 		return $row;
776 776
 	}
777 777
 
@@ -783,18 +783,18 @@  discard block
 block discarded – undo
783 783
      *  @param	int		$withQuotes     Return string with quotes
784 784
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
785 785
 	 */
786
-	function encrypt($fieldorvalue, $withQuotes=0)
786
+	function encrypt($fieldorvalue, $withQuotes = 0)
787 787
 	{
788 788
 		global $conf;
789 789
 
790 790
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
791
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
791
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
792 792
 
793 793
 		//Encryption key
794
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
794
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
795 795
 
796 796
 		$return = $fieldorvalue;
797
-		return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
797
+		return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
798 798
 	}
799 799
 
800 800
 
@@ -809,10 +809,10 @@  discard block
 block discarded – undo
809 809
 		global $conf;
810 810
 
811 811
 		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
812
-		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
812
+		$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
813 813
 
814 814
 		//Encryption key
815
-		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
815
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
816 816
 
817 817
 		$return = $value;
818 818
 		return $return;
@@ -842,17 +842,17 @@  discard block
 block discarded – undo
842 842
 	 * 	@param	string	$owner			Username of database owner
843 843
 	 * 	@return	false|resource				resource defined if OK, null if KO
844 844
 	 */
845
-	function DDLCreateDb($database,$charset='',$collation='',$owner='')
845
+	function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
846 846
 	{
847
-	    if (empty($charset))   $charset=$this->forcecharset;
848
-		if (empty($collation)) $collation=$this->forcecollate;
847
+	    if (empty($charset))   $charset = $this->forcecharset;
848
+		if (empty($collation)) $collation = $this->forcecollate;
849 849
 
850 850
 		// Test charset match LC_TYPE (pgsql error otherwise)
851 851
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
852 852
 
853
-		$sql='CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
854
-		dol_syslog($sql,LOG_DEBUG);
855
-		$ret=$this->query($sql);
853
+		$sql = 'CREATE DATABASE "'.$database.'" OWNER "'.$owner.'" ENCODING \''.$charset.'\'';
854
+		dol_syslog($sql, LOG_DEBUG);
855
+		$ret = $this->query($sql);
856 856
 		return $ret;
857 857
 	}
858 858
 
@@ -863,16 +863,16 @@  discard block
 block discarded – undo
863 863
 	 *  @param	string		$table		Name of table filter ('xxx%')
864 864
 	 *  @return	array					List of tables in an array
865 865
 	 */
866
-	function DDLListTables($database, $table='')
866
+	function DDLListTables($database, $table = '')
867 867
 	{
868
-		$listtables=array();
868
+		$listtables = array();
869 869
 
870 870
 		$like = '';
871 871
 		if ($table) $like = " AND table_name LIKE '".$table."'";
872 872
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
873 873
         if ($result)
874 874
         {
875
-    		while($row = $this->fetch_row($result))
875
+    		while ($row = $this->fetch_row($result))
876 876
     		{
877 877
     			$listtables[] = $row[0];
878 878
     		}
@@ -889,29 +889,29 @@  discard block
 block discarded – undo
889 889
 	 */
890 890
 	function DDLInfoTable($table)
891 891
 	{
892
-		$infotables=array();
893
-
894
-		$sql="SELECT ";
895
-		$sql.="	infcol.column_name as \"Column\",";
896
-		$sql.="	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
897
-		$sql.="		ELSE infcol.udt_name";
898
-		$sql.="	END as \"Type\",";
899
-		$sql.="	infcol.collation_name as \"Collation\",";
900
-		$sql.="	infcol.is_nullable as \"Null\",";
901
-		$sql.="	'' as \"Key\",";
902
-		$sql.="	infcol.column_default as \"Default\",";
903
-		$sql.="	'' as \"Extra\",";
904
-		$sql.="	'' as \"Privileges\"";
905
-		$sql.="	FROM information_schema.columns infcol";
906
-		$sql.="	WHERE table_schema='public' ";
907
-		$sql.="	AND table_name='".$table."'";
908
-		$sql.="	ORDER BY ordinal_position;";
909
-
910
-		dol_syslog($sql,LOG_DEBUG);
892
+		$infotables = array();
893
+
894
+		$sql = "SELECT ";
895
+		$sql .= "	infcol.column_name as \"Column\",";
896
+		$sql .= "	CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
897
+		$sql .= "		ELSE infcol.udt_name";
898
+		$sql .= "	END as \"Type\",";
899
+		$sql .= "	infcol.collation_name as \"Collation\",";
900
+		$sql .= "	infcol.is_nullable as \"Null\",";
901
+		$sql .= "	'' as \"Key\",";
902
+		$sql .= "	infcol.column_default as \"Default\",";
903
+		$sql .= "	'' as \"Extra\",";
904
+		$sql .= "	'' as \"Privileges\"";
905
+		$sql .= "	FROM information_schema.columns infcol";
906
+		$sql .= "	WHERE table_schema='public' ";
907
+		$sql .= "	AND table_name='".$table."'";
908
+		$sql .= "	ORDER BY ordinal_position;";
909
+
910
+		dol_syslog($sql, LOG_DEBUG);
911 911
 		$result = $this->query($sql);
912 912
 		if ($result)
913 913
 		{
914
-    		 while($row = $this->fetch_row($result))
914
+    		 while ($row = $this->fetch_row($result))
915 915
     		 {
916 916
     			$infotables[] = $row;
917 917
     		 }
@@ -932,68 +932,68 @@  discard block
 block discarded – undo
932 932
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
933 933
 	 *	@return	    int						<0 if KO, >=0 if OK
934 934
 	 */
935
-	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
935
+	function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
936 936
 	{
937 937
 		// FIXME: $fulltext_keys parameter is unused
938 938
 
939 939
 		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
940 940
 		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
941 941
 		$sql = "create table ".$table."(";
942
-		$i=0;
943
-		foreach($fields as $field_name => $field_desc)
942
+		$i = 0;
943
+		foreach ($fields as $field_name => $field_desc)
944 944
 		{
945 945
 			$sqlfields[$i] = $field_name." ";
946 946
 			$sqlfields[$i]  .= $field_desc['type'];
947
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
947
+			if (preg_match("/^[^\s]/i", $field_desc['value']))
948 948
 			$sqlfields[$i]  .= "(".$field_desc['value'].")";
949
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
949
+			else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
950 950
 			$sqlfields[$i]  .= " ".$field_desc['attribute'];
951
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
951
+			else if (preg_match("/^[^\s]/i", $field_desc['default']))
952 952
 			{
953
-				if(preg_match("/null/i",$field_desc['default']))
953
+				if (preg_match("/null/i", $field_desc['default']))
954 954
 				$sqlfields[$i]  .= " default ".$field_desc['default'];
955 955
 				else
956 956
 				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
957 957
 			}
958
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
958
+			else if (preg_match("/^[^\s]/i", $field_desc['null']))
959 959
 			$sqlfields[$i]  .= " ".$field_desc['null'];
960 960
 
961
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
961
+			else if (preg_match("/^[^\s]/i", $field_desc['extra']))
962 962
 			$sqlfields[$i]  .= " ".$field_desc['extra'];
963 963
 			$i++;
964 964
 		}
965
-		if($primary_key != "")
965
+		if ($primary_key != "")
966 966
 		$pk = "primary key(".$primary_key.")";
967 967
 
968
-		if(is_array($unique_keys))
968
+		if (is_array($unique_keys))
969 969
 		{
970 970
 			$i = 0;
971
-			foreach($unique_keys as $key => $value)
971
+			foreach ($unique_keys as $key => $value)
972 972
 			{
973 973
 				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
974 974
 				$i++;
975 975
 			}
976 976
 		}
977
-		if(is_array($keys))
977
+		if (is_array($keys))
978 978
 		{
979 979
 			$i = 0;
980
-			foreach($keys as $key => $value)
980
+			foreach ($keys as $key => $value)
981 981
 			{
982 982
 				$sqlk[$i] = "KEY ".$key." (".$value.")";
983 983
 				$i++;
984 984
 			}
985 985
 		}
986
-		$sql .= implode(',',$sqlfields);
987
-		if($primary_key != "")
986
+		$sql .= implode(',', $sqlfields);
987
+		if ($primary_key != "")
988 988
 		$sql .= ",".$pk;
989
-		if(is_array($unique_keys))
990
-		$sql .= ",".implode(',',$sqluq);
991
-		if(is_array($keys))
992
-		$sql .= ",".implode(',',$sqlk);
993
-		$sql .=") type=".$type;
994
-
995
-		dol_syslog($sql,LOG_DEBUG);
996
-		if(! $this->query($sql))
989
+		if (is_array($unique_keys))
990
+		$sql .= ",".implode(',', $sqluq);
991
+		if (is_array($keys))
992
+		$sql .= ",".implode(',', $sqlk);
993
+		$sql .= ") type=".$type;
994
+
995
+		dol_syslog($sql, LOG_DEBUG);
996
+		if (!$this->query($sql))
997 997
 		return -1;
998 998
 		else
999 999
 		return 1;
@@ -1008,14 +1008,14 @@  discard block
 block discarded – undo
1008 1008
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1009 1009
 	 *	@return	int									<0 if KO, >=0 if OK
1010 1010
 	 */
1011
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1011
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1012 1012
 	{
1013 1013
 		// Note: using ' on user does not works with pgsql
1014 1014
 		$sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1015 1015
 
1016
-		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1017
-		$resql=$this->query($sql);
1018
-		if (! $resql)
1016
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1017
+		$resql = $this->query($sql);
1018
+		if (!$resql)
1019 1019
 		{
1020 1020
 			return -1;
1021 1021
 		}
@@ -1030,13 +1030,13 @@  discard block
 block discarded – undo
1030 1030
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1031 1031
 	 *	@return	false|resource		Resultset x (x->attname)
1032 1032
 	 */
1033
-	function DDLDescTable($table,$field="")
1033
+	function DDLDescTable($table, $field = "")
1034 1034
 	{
1035
-		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1036
-		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1037
-		if ($field) $sql.= " AND attname = '".$field."'";
1035
+		$sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1036
+		$sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1037
+		if ($field) $sql .= " AND attname = '".$field."'";
1038 1038
 
1039
-		dol_syslog($sql,LOG_DEBUG);
1039
+		dol_syslog($sql, LOG_DEBUG);
1040 1040
 		$this->_results = $this->query($sql);
1041 1041
 		return $this->_results;
1042 1042
 	}
@@ -1050,32 +1050,32 @@  discard block
 block discarded – undo
1050 1050
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1051 1051
 	 *	@return	int							<0 if KO, >0 if OK
1052 1052
 	 */
1053
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
1053
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1054 1054
 	{
1055 1055
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1056 1056
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1057
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1057
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1058 1058
 		$sql .= $field_desc['type'];
1059
-		if(preg_match("/^[^\s]/i",$field_desc['value']))
1060
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1059
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
1060
+		    if (!in_array($field_desc['type'], array('int', 'date', 'datetime')))
1061 1061
 		    {
1062
-		        $sql.= "(".$field_desc['value'].")";
1062
+		        $sql .= "(".$field_desc['value'].")";
1063 1063
 		    }
1064
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1064
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1065 1065
 		$sql .= " ".$field_desc['attribute'];
1066
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1066
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
1067 1067
 		$sql .= " ".$field_desc['null'];
1068
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1069
-		if (preg_match("/null/i",$field_desc['default']))
1068
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
1069
+		if (preg_match("/null/i", $field_desc['default']))
1070 1070
 		$sql .= " default ".$field_desc['default'];
1071 1071
 		else
1072 1072
 		$sql .= " default '".$field_desc['default']."'";
1073
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1073
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
1074 1074
 		$sql .= " ".$field_desc['extra'];
1075 1075
 		$sql .= " ".$field_position;
1076 1076
 
1077
-		dol_syslog($sql,LOG_DEBUG);
1078
-		if(! $this -> query($sql))
1077
+		dol_syslog($sql, LOG_DEBUG);
1078
+		if (!$this -> query($sql))
1079 1079
 			return -1;
1080 1080
 		return 1;
1081 1081
 	}
@@ -1088,12 +1088,12 @@  discard block
 block discarded – undo
1088 1088
 	 *	@param	string	$field_desc 		Array with description of field format
1089 1089
 	 *	@return	int							<0 if KO, >0 if OK
1090 1090
 	 */
1091
-	function DDLUpdateField($table,$field_name,$field_desc)
1091
+	function DDLUpdateField($table, $field_name, $field_desc)
1092 1092
 	{
1093 1093
 		$sql = "ALTER TABLE ".$table;
1094 1094
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1095 1095
 		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1096
-			$sql.="(".$field_desc['value'].")";
1096
+			$sql .= "(".$field_desc['value'].")";
1097 1097
 		}
1098 1098
 
1099 1099
 		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
@@ -1101,24 +1101,24 @@  discard block
 block discarded – undo
1101 1101
         	// 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
1102 1102
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1103 1103
         	{
1104
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1104
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1105 1105
         		$this->query($sqlbis);
1106 1106
         	}
1107 1107
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1108 1108
         	{
1109
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1109
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1110 1110
         		$this->query($sqlbis);
1111 1111
         	}
1112 1112
 		}
1113 1113
 
1114 1114
 		if ($field_desc['default'] != '')
1115 1115
 		{
1116
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1117
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1116
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
1117
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
1118 1118
 		}
1119 1119
 
1120
-		dol_syslog($sql,LOG_DEBUG);
1121
-		if (! $this->query($sql))
1120
+		dol_syslog($sql, LOG_DEBUG);
1121
+		if (!$this->query($sql))
1122 1122
 			return -1;
1123 1123
 		return 1;
1124 1124
 	}
@@ -1130,13 +1130,13 @@  discard block
 block discarded – undo
1130 1130
 	 *	@param	string	$field_name 	Name of field to drop
1131 1131
 	 *	@return	int						<0 if KO, >0 if OK
1132 1132
 	 */
1133
-	function DDLDropField($table,$field_name)
1133
+	function DDLDropField($table, $field_name)
1134 1134
 	{
1135
-		$sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1136
-		dol_syslog($sql,LOG_DEBUG);
1137
-		if (! $this->query($sql))
1135
+		$sql = "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1136
+		dol_syslog($sql, LOG_DEBUG);
1137
+		if (!$this->query($sql))
1138 1138
 		{
1139
-			$this->error=$this->lasterror();
1139
+			$this->error = $this->lasterror();
1140 1140
 			return -1;
1141 1141
 		}
1142 1142
 		return 1;
@@ -1149,10 +1149,10 @@  discard block
 block discarded – undo
1149 1149
 	 */
1150 1150
 	function getDefaultCharacterSetDatabase()
1151 1151
 	{
1152
-		$resql=$this->query('SHOW SERVER_ENCODING');
1152
+		$resql = $this->query('SHOW SERVER_ENCODING');
1153 1153
 		if ($resql)
1154 1154
 		{
1155
-            $liste=$this->fetch_array($resql);
1155
+            $liste = $this->fetch_array($resql);
1156 1156
 		    return $liste['server_encoding'];
1157 1157
 		}
1158 1158
 		else return '';
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
 	 */
1166 1166
 	function getListOfCharacterSet()
1167 1167
 	{
1168
-		$resql=$this->query('SHOW SERVER_ENCODING');
1168
+		$resql = $this->query('SHOW SERVER_ENCODING');
1169 1169
 		$liste = array();
1170 1170
 		if ($resql)
1171 1171
 		{
@@ -1190,10 +1190,10 @@  discard block
 block discarded – undo
1190 1190
 	 */
1191 1191
 	function getDefaultCollationDatabase()
1192 1192
 	{
1193
-		$resql=$this->query('SHOW LC_COLLATE');
1193
+		$resql = $this->query('SHOW LC_COLLATE');
1194 1194
 		if ($resql)
1195 1195
 		{
1196
-		    $liste=$this->fetch_array($resql);
1196
+		    $liste = $this->fetch_array($resql);
1197 1197
 			return $liste['lc_collate'];
1198 1198
 		}
1199 1199
 		else return '';
@@ -1206,12 +1206,12 @@  discard block
 block discarded – undo
1206 1206
 	 */
1207 1207
 	function getListOfCollation()
1208 1208
 	{
1209
-		$resql=$this->query('SHOW LC_COLLATE');
1209
+		$resql = $this->query('SHOW LC_COLLATE');
1210 1210
 		$liste = array();
1211 1211
 		if ($resql)
1212 1212
 		{
1213 1213
 			$i = 0;
1214
-			while ($obj = $this->fetch_object($resql) )
1214
+			while ($obj = $this->fetch_object($resql))
1215 1215
 			{
1216 1216
 				$liste[$i]['collation'] = $obj->lc_collate;
1217 1217
 				$i++;
@@ -1230,21 +1230,21 @@  discard block
 block discarded – undo
1230 1230
 	 */
1231 1231
 	function getPathOfDump()
1232 1232
 	{
1233
-		$fullpathofdump='/pathtopgdump/pg_dump';
1233
+		$fullpathofdump = '/pathtopgdump/pg_dump';
1234 1234
 
1235 1235
 		if (file_exists('/usr/bin/pg_dump'))
1236 1236
 		{
1237
-		    $fullpathofdump='/usr/bin/pg_dump';
1237
+		    $fullpathofdump = '/usr/bin/pg_dump';
1238 1238
 		}
1239 1239
 		else
1240 1240
 		{
1241 1241
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1242
-		    $resql=$this->query('SHOW data_directory');
1242
+		    $resql = $this->query('SHOW data_directory');
1243 1243
     		if ($resql)
1244 1244
     		{
1245
-    			$liste=$this->fetch_array($resql);
1246
-    			$basedir=$liste['data_directory'];
1247
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1245
+    			$liste = $this->fetch_array($resql);
1246
+    			$basedir = $liste['data_directory'];
1247
+    			$fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1248 1248
     		}
1249 1249
 		}
1250 1250
 
@@ -1259,23 +1259,23 @@  discard block
 block discarded – undo
1259 1259
 	function getPathOfRestore()
1260 1260
 	{
1261 1261
 		//$tool='pg_restore';
1262
-		$tool='psql';
1262
+		$tool = 'psql';
1263 1263
 
1264
-		$fullpathofdump='/pathtopgrestore/'.$tool;
1264
+		$fullpathofdump = '/pathtopgrestore/'.$tool;
1265 1265
 
1266 1266
         if (file_exists('/usr/bin/'.$tool))
1267 1267
         {
1268
-            $fullpathofdump='/usr/bin/'.$tool;
1268
+            $fullpathofdump = '/usr/bin/'.$tool;
1269 1269
         }
1270 1270
         else
1271 1271
         {
1272 1272
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1273
-            $resql=$this->query('SHOW data_directory');
1273
+            $resql = $this->query('SHOW data_directory');
1274 1274
             if ($resql)
1275 1275
             {
1276
-                $liste=$this->fetch_array($resql);
1277
-                $basedir=$liste['data_directory'];
1278
-                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1276
+                $liste = $this->fetch_array($resql);
1277
+                $basedir = $liste['data_directory'];
1278
+                $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1279 1279
             }
1280 1280
         }
1281 1281
 
@@ -1288,16 +1288,16 @@  discard block
 block discarded – undo
1288 1288
 	 * @param	string	$filter		Filter list on a particular value
1289 1289
 	 * @return	array				Array of key-values (key=>value)
1290 1290
 	 */
1291
-	function getServerParametersValues($filter='')
1291
+	function getServerParametersValues($filter = '')
1292 1292
 	{
1293
-		$result=array();
1293
+		$result = array();
1294 1294
 
1295
-		$resql='select name,setting from pg_settings';
1296
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1297
-		$resql=$this->query($resql);
1295
+		$resql = 'select name,setting from pg_settings';
1296
+		if ($filter) $resql .= " WHERE name = '".$this->escape($filter)."'";
1297
+		$resql = $this->query($resql);
1298 1298
 		if ($resql)
1299 1299
 		{
1300
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1300
+			while ($obj = $this->fetch_object($resql)) $result[$obj->name] = $obj->setting;
1301 1301
 		}
1302 1302
 
1303 1303
 		return $result;
@@ -1309,7 +1309,7 @@  discard block
 block discarded – undo
1309 1309
 	 * @param	string	$filter		Filter list on a particular value
1310 1310
 	 * @return  array				Array of key-values (key=>value)
1311 1311
 	 */
1312
-	function getServerStatusValues($filter='')
1312
+	function getServerStatusValues($filter = '')
1313 1313
 	{
1314 1314
 		/* This is to return current running requests.
1315 1315
 		$sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
Please login to merge, or discard this patch.
htdocs/core/db/sqlite3.class.php 5 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1449,7 +1449,7 @@
 block discarded – undo
1449 1449
      *
1450 1450
      * @param int	$daynr							???
1451 1451
      * @param bool	$sunday_first_day_of_week		???
1452
-     * @return int
1452
+     * @return double
1453 1453
      */
1454 1454
     private static function calc_weekday($daynr, $sunday_first_day_of_week) {
1455 1455
       $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
Please login to merge, or discard this patch.
Indentation   +1110 added lines, -1110 removed lines patch added patch discarded remove patch
@@ -32,48 +32,48 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class DoliDBSqlite3 extends DoliDB
34 34
 {
35
-    //! Database type
36
-    public $type='sqlite3';
37
-    //! Database label
38
-    const LABEL='Sqlite3';
39
-    //! Version min database
40
-    const VERSIONMIN='3.0.0';
35
+	//! Database type
36
+	public $type='sqlite3';
37
+	//! Database label
38
+	const LABEL='Sqlite3';
39
+	//! Version min database
40
+	const VERSIONMIN='3.0.0';
41 41
 	/** @var SQLite3Result Resultset of last query */
42 42
 	private $_results;
43 43
 
44
-    const WEEK_MONDAY_FIRST=1;
45
-    const WEEK_YEAR = 2;
46
-    const WEEK_FIRST_WEEKDAY=4;
44
+	const WEEK_MONDAY_FIRST=1;
45
+	const WEEK_YEAR = 2;
46
+	const WEEK_FIRST_WEEKDAY=4;
47 47
 
48 48
 
49
-    /**
49
+	/**
50 50
 	 *	Constructor.
51 51
 	 *	This create an opened connexion to a database server and eventually to a database
52
-     *
52
+	 *
53 53
 	 *	@param      string	$type		Type of database (mysql, pgsql...)
54 54
 	 *	@param	    string	$host		Address of database server
55 55
 	 *	@param	    string	$user		Nom de l'utilisateur autorise
56 56
 	 *	@param	    string	$pass		Mot de passe
57 57
 	 *	@param	    string	$name		Nom de la database
58 58
 	 *	@param	    int		$port		Port of database server
59
-     */
60
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
61
-    {
62
-        global $conf;
59
+	 */
60
+	function __construct($type, $host, $user, $pass, $name='', $port=0)
61
+	{
62
+		global $conf;
63 63
 
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;
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;
67 67
 
68
-        $this->database_user=$user;
69
-        $this->database_host=$host;
70
-        $this->database_port=$port;
68
+		$this->database_user=$user;
69
+		$this->database_host=$host;
70
+		$this->database_port=$port;
71 71
 
72
-        $this->transaction_opened=0;
72
+		$this->transaction_opened=0;
73 73
 
74
-        //print "Name DB: $host,$user,$pass,$name<br>";
74
+		//print "Name DB: $host,$user,$pass,$name<br>";
75 75
 
76
-        /*if (! function_exists("sqlite_query"))
76
+		/*if (! function_exists("sqlite_query"))
77 77
         {
78 78
             $this->connected = false;
79 79
             $this->ok = false;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
             return $this->ok;
83 83
         }*/
84 84
 
85
-        /*if (! $host)
85
+		/*if (! $host)
86 86
         {
87 87
             $this->connected = false;
88 88
             $this->ok = false;
@@ -91,229 +91,229 @@  discard block
 block discarded – undo
91 91
             return $this->ok;
92 92
         }*/
93 93
 
94
-        // Essai connexion serveur
95
-        // We do not try to connect to database, only to server. Connect to database is done later in constrcutor
96
-        $this->db = $this->connect($host, $user, $pass, $name, $port);
94
+		// Essai connexion serveur
95
+		// We do not try to connect to database, only to server. Connect to database is done later in constrcutor
96
+		$this->db = $this->connect($host, $user, $pass, $name, $port);
97
+
98
+		if ($this->db)
99
+		{
100
+			$this->connected = true;
101
+			$this->ok = true;
102
+			$this->database_selected = true;
103
+			$this->database_name = $name;
104
+
105
+			$this->addCustomFunction('IF');
106
+			$this->addCustomFunction('MONTH');
107
+			$this->addCustomFunction('CURTIME');
108
+			$this->addCustomFunction('CURDATE');
109
+			$this->addCustomFunction('WEEK', 1);
110
+			$this->addCustomFunction('WEEK', 2);
111
+			$this->addCustomFunction('WEEKDAY');
112
+			$this->addCustomFunction('date_format');
113
+			//$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
+		}
115
+		else
116
+		{
117
+			// host, login ou password incorrect
118
+			$this->connected = false;
119
+			$this->ok = false;
120
+			$this->database_selected = false;
121
+			$this->database_name = '';
122
+			//$this->error=sqlite_connect_error();
123
+			dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error,LOG_ERR);
124
+		}
125
+
126
+		return $this->ok;
127
+	}
97 128
 
98
-        if ($this->db)
99
-        {
100
-            $this->connected = true;
101
-            $this->ok = true;
102
-            $this->database_selected = true;
103
-            $this->database_name = $name;
104
-
105
-            $this->addCustomFunction('IF');
106
-            $this->addCustomFunction('MONTH');
107
-            $this->addCustomFunction('CURTIME');
108
-            $this->addCustomFunction('CURDATE');
109
-            $this->addCustomFunction('WEEK', 1);
110
-            $this->addCustomFunction('WEEK', 2);
111
-            $this->addCustomFunction('WEEKDAY');
112
-            $this->addCustomFunction('date_format');
113
-            //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
-        }
115
-        else
116
-        {
117
-            // host, login ou password incorrect
118
-            $this->connected = false;
119
-            $this->ok = false;
120
-            $this->database_selected = false;
121
-            $this->database_name = '';
122
-            //$this->error=sqlite_connect_error();
123
-            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error,LOG_ERR);
124
-        }
125 129
 
126
-        return $this->ok;
127
-    }
128
-
129
-
130
-    /**
131
-     *  Convert a SQL request in Mysql syntax to native syntax
132
-     *
133
-     *  @param     string	$line   SQL request line to convert
134
-     *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
135
-     *  @return    string   		SQL request line converted
136
-     */
137
-    static function convertSQLFromMysql($line,$type='ddl')
138
-    {
139
-        // Removed empty line if this is a comment line for SVN tagging
140
-        if (preg_match('/^--\s\$Id/i',$line)) {
141
-            return '';
142
-        }
143
-        // Return line if this is a comment
144
-        if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
145
-        {
146
-            return $line;
147
-        }
148
-        if ($line != "")
149
-        {
150
-            if ($type == 'auto')
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';
155
-            }
156
-
157
-            if ($type == 'dml')
158
-            {
159
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
160
-
161
-                // we are inside create table statement so lets process datatypes
162
-                if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
163
-                    $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
164
-                    $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
165
-                    $line=preg_replace('/,$/','',$line);
166
-                }
167
-
168
-                // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
169
-                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
170
-                    $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 integer PRIMARY KEY AUTOINCREMENT',$line);
171
-                    //$line = "-- ".$line." replaced by --\n".$newline;
172
-                    $line=$newline;
173
-                }
174
-
175
-                // tinyint type conversion
176
-                $line=str_replace('tinyint','smallint',$line);
177
-
178
-                // nuke unsigned
179
-                $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
180
-
181
-                // blob -> text
182
-                $line=preg_replace('/\w*blob/i','text',$line);
183
-
184
-                // tinytext/mediumtext -> text
185
-                $line=preg_replace('/tinytext/i','text',$line);
186
-                $line=preg_replace('/mediumtext/i','text',$line);
187
-
188
-                // change not null datetime field to null valid ones
189
-                // (to support remapping of "zero time" to null
190
-                $line=preg_replace('/datetime not null/i','datetime',$line);
191
-                $line=preg_replace('/datetime/i','timestamp',$line);
192
-
193
-                // double -> numeric
194
-                $line=preg_replace('/^double/i','numeric',$line);
195
-                $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
196
-                // float -> numeric
197
-                $line=preg_replace('/^float/i','numeric',$line);
198
-                $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
199
-
200
-                // unique index(field1,field2)
201
-                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
202
-                {
203
-                    $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
204
-                }
205
-
206
-                // We remove end of requests "AFTER fieldxxx"
207
-                $line=preg_replace('/AFTER [a-z0-9_]+/i','',$line);
208
-
209
-                // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
210
-                $line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line);
211
-
212
-                // Translate order to rename fields
213
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
214
-                {
215
-                    $line = "-- ".$line." replaced by --\n";
216
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
217
-                }
218
-
219
-                // Translate order to modify field format
220
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
221
-                {
222
-                    $line = "-- ".$line." replaced by --\n";
223
-                    $newreg3=$reg[3];
224
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
225
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
226
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
227
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
228
-                    $newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3);
229
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
230
-                    // TODO Add alter to set default value or null/not null if there is this in $reg[3]
231
-                }
232
-
233
-                // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
234
-                // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
235
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
236
-                {
237
-                    $line = "-- ".$line." replaced by --\n";
238
-                    $line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
239
-                }
240
-
241
-                // Translate order to drop foreign keys
242
-                // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
243
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
244
-                {
245
-                    $line = "-- ".$line." replaced by --\n";
246
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
247
-                }
248
-
249
-                // alter table add [unique] [index] (field1, field2 ...)
250
-                // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
251
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
252
-                {
253
-                    $fieldlist=$reg[4];
254
-                    $idxname=$reg[3];
255
-                    $tablename=$reg[1];
256
-                    $line = "-- ".$line." replaced by --\n";
257
-                    $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
258
-                }
259
-                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)) {
260
-                    // Pour l'instant les contraintes ne sont pas créées
261
-                    dol_syslog(get_class().'::query line emptied');
262
-                    $line = 'SELECT 0;';
263
-
264
-                }
265
-
266
-                //if (preg_match('/rowid\s+.*\s+PRIMARY\s+KEY,/i', $line)) {
267
-                    //preg_replace('/(rowid\s+.*\s+PRIMARY\s+KEY\s*,)/i', '/* \\1 */', $line);
268
-                //}
269
-            }
270
-
271
-            // Delete using criteria on other table must not declare twice the deleted table
272
-            // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
273
-            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
274
-            {
130
+	/**
131
+	 *  Convert a SQL request in Mysql syntax to native syntax
132
+	 *
133
+	 *  @param     string	$line   SQL request line to convert
134
+	 *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
135
+	 *  @return    string   		SQL request line converted
136
+	 */
137
+	static function convertSQLFromMysql($line,$type='ddl')
138
+	{
139
+		// Removed empty line if this is a comment line for SVN tagging
140
+		if (preg_match('/^--\s\$Id/i',$line)) {
141
+			return '';
142
+		}
143
+		// Return line if this is a comment
144
+		if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
145
+		{
146
+			return $line;
147
+		}
148
+		if ($line != "")
149
+		{
150
+			if ($type == 'auto')
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';
155
+			}
156
+
157
+			if ($type == 'dml')
158
+			{
159
+				$line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
160
+
161
+				// we are inside create table statement so lets process datatypes
162
+				if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
163
+					$line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
164
+					$line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
165
+					$line=preg_replace('/,$/','',$line);
166
+				}
167
+
168
+				// Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
169
+				if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
170
+					$newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 integer PRIMARY KEY AUTOINCREMENT',$line);
171
+					//$line = "-- ".$line." replaced by --\n".$newline;
172
+					$line=$newline;
173
+				}
174
+
175
+				// tinyint type conversion
176
+				$line=str_replace('tinyint','smallint',$line);
177
+
178
+				// nuke unsigned
179
+				$line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
180
+
181
+				// blob -> text
182
+				$line=preg_replace('/\w*blob/i','text',$line);
183
+
184
+				// tinytext/mediumtext -> text
185
+				$line=preg_replace('/tinytext/i','text',$line);
186
+				$line=preg_replace('/mediumtext/i','text',$line);
187
+
188
+				// change not null datetime field to null valid ones
189
+				// (to support remapping of "zero time" to null
190
+				$line=preg_replace('/datetime not null/i','datetime',$line);
191
+				$line=preg_replace('/datetime/i','timestamp',$line);
192
+
193
+				// double -> numeric
194
+				$line=preg_replace('/^double/i','numeric',$line);
195
+				$line=preg_replace('/(\s*)double/i','\\1numeric',$line);
196
+				// float -> numeric
197
+				$line=preg_replace('/^float/i','numeric',$line);
198
+				$line=preg_replace('/(\s*)float/i','\\1numeric',$line);
199
+
200
+				// unique index(field1,field2)
201
+				if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
202
+				{
203
+					$line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
204
+				}
205
+
206
+				// We remove end of requests "AFTER fieldxxx"
207
+				$line=preg_replace('/AFTER [a-z0-9_]+/i','',$line);
208
+
209
+				// We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
210
+				$line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line);
211
+
212
+				// Translate order to rename fields
213
+				if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
214
+				{
215
+					$line = "-- ".$line." replaced by --\n";
216
+					$line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
217
+				}
218
+
219
+				// Translate order to modify field format
220
+				if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
221
+				{
222
+					$line = "-- ".$line." replaced by --\n";
223
+					$newreg3=$reg[3];
224
+					$newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
225
+					$newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
226
+					$newreg3=preg_replace('/ NULL/i','',$newreg3);
227
+					$newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
228
+					$newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3);
229
+					$line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
230
+					// TODO Add alter to set default value or null/not null if there is this in $reg[3]
231
+				}
232
+
233
+				// alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
234
+				// ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
235
+				if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
236
+				{
237
+					$line = "-- ".$line." replaced by --\n";
238
+					$line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
239
+				}
240
+
241
+				// Translate order to drop foreign keys
242
+				// ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
243
+				if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
244
+				{
245
+					$line = "-- ".$line." replaced by --\n";
246
+					$line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
247
+				}
248
+
249
+				// alter table add [unique] [index] (field1, field2 ...)
250
+				// ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
251
+				if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
252
+				{
253
+					$fieldlist=$reg[4];
254
+					$idxname=$reg[3];
255
+					$tablename=$reg[1];
256
+					$line = "-- ".$line." replaced by --\n";
257
+					$line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
258
+				}
259
+				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)) {
260
+					// Pour l'instant les contraintes ne sont pas créées
261
+					dol_syslog(get_class().'::query line emptied');
262
+					$line = 'SELECT 0;';
263
+
264
+				}
265
+
266
+				//if (preg_match('/rowid\s+.*\s+PRIMARY\s+KEY,/i', $line)) {
267
+					//preg_replace('/(rowid\s+.*\s+PRIMARY\s+KEY\s*,)/i', '/* \\1 */', $line);
268
+				//}
269
+			}
270
+
271
+			// Delete using criteria on other table must not declare twice the deleted table
272
+			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
273
+			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
274
+			{
275 275
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
276
-                {
277
-                    $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
278
-                }
279
-            }
276
+				{
277
+					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
278
+				}
279
+			}
280 280
 
281
-            // Remove () in the tables in FROM if one table
282
-            $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
283
-            //print $line."\n";
281
+			// Remove () in the tables in FROM if one table
282
+			$line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
283
+			//print $line."\n";
284 284
 
285
-            // Remove () in the tables in FROM if two table
286
-            $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);
287
-            //print $line."\n";
285
+			// Remove () in the tables in FROM if two table
286
+			$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);
287
+			//print $line."\n";
288 288
 
289
-            // Remove () in the tables in FROM if two table
290
-            $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);
291
-            //print $line."\n";
289
+			// Remove () in the tables in FROM if two table
290
+			$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);
291
+			//print $line."\n";
292 292
 
293
-            //print "type=".$type." newline=".$line."<br>\n";
294
-        }
293
+			//print "type=".$type." newline=".$line."<br>\n";
294
+		}
295 295
 
296
-        return $line;
297
-    }
296
+		return $line;
297
+	}
298 298
 
299
-    /**
299
+	/**
300 300
 	 *	Select a database
301
-     *
301
+	 *
302 302
 	 *	@param	    string	$database	Name of database
303 303
 	 *	@return	    boolean  		    true if OK, false if KO
304
-     */
305
-    function select_db($database)
306
-    {
307
-        dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
308
-	    // sqlite_select_db() does not exist
309
-        //return sqlite_select_db($this->db,$database);
310
-        return true;
311
-    }
304
+	 */
305
+	function select_db($database)
306
+	{
307
+		dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
308
+		// sqlite_select_db() does not exist
309
+		//return sqlite_select_db($this->db,$database);
310
+		return true;
311
+	}
312 312
 
313 313
 
314
-    /**
314
+	/**
315 315
 	 *	Connexion to server
316
-     *
316
+	 *
317 317
 	 *	@param	    string	$host		database server host
318 318
 	 *	@param	    string	$login		login
319 319
 	 *	@param	    string	$passwd		password
@@ -321,310 +321,310 @@  discard block
 block discarded – undo
321 321
 	 *	@param		integer	$port		Port of database server
322 322
 	 *	@return		SQLite3				Database access handler
323 323
 	 *	@see		close
324
-     */
325
-    function connect($host, $login, $passwd, $name, $port=0)
326
-    {
327
-        global $main_data_dir;
328
-
329
-        dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
330
-
331
-        $dir=$main_data_dir;
332
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
333
-        // With sqlite, port must be in connect parameters
334
-        //if (! $newport) $newport=3306;
335
-        $database_name = $dir.'/database_'.$name.'.sdb';
336
-        try {
337
-            /*** connect to SQLite database ***/
338
-            //$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
324
+	 */
325
+	function connect($host, $login, $passwd, $name, $port=0)
326
+	{
327
+		global $main_data_dir;
328
+
329
+		dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
330
+
331
+		$dir=$main_data_dir;
332
+		if (empty($dir)) $dir=DOL_DATA_ROOT;
333
+		// With sqlite, port must be in connect parameters
334
+		//if (! $newport) $newport=3306;
335
+		$database_name = $dir.'/database_'.$name.'.sdb';
336
+		try {
337
+			/*** connect to SQLite database ***/
338
+			//$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
339 339
 			$this->db = new SQLite3($database_name);
340
-            //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
341
-        }
342
-        catch(Exception $e)
343
-        {
344
-            $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
345
-            return '';
346
-        }
340
+			//$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
341
+		}
342
+		catch(Exception $e)
343
+		{
344
+			$this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
345
+			return '';
346
+		}
347 347
 
348
-        //print "Resultat fonction connect: ".$this->db;
349
-        return $this->db;
350
-    }
348
+		//print "Resultat fonction connect: ".$this->db;
349
+		return $this->db;
350
+	}
351 351
 
352 352
 
353
-    /**
353
+	/**
354 354
 	 *	Return version of database server
355
-     *
355
+	 *
356 356
 	 *	@return	        string      Version string
357
-     */
358
-    function getVersion()
359
-    {
360
-    	$tmp=$this->db->version();
361
-        return $tmp['versionString'];
362
-    }
363
-
364
-    /**
365
-     *	Return version of database client driver
366
-     *
367
-     *	@return	        string      Version string
368
-     */
369
-    function getDriverInfo()
370
-    {
371
-        return 'sqlite3 php driver';
372
-    }
373
-
374
-
375
-    /**
376
-     *  Close database connexion
377
-     *
378
-     *  @return     bool     True if disconnect successfull, false otherwise
379
-     *  @see        connect
380
-     */
381
-    function close()
382
-    {
383
-        if ($this->db)
384
-        {
385
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
386
-            $this->connected=false;
387
-            $this->db->close();
388
-            unset($this->db);    // Clean this->db
389
-            return true;
390
-        }
391
-        return false;
392
-    }
393
-
394
-    /**
395
-     *  Execute a SQL request and return the resultset
396
-     *
397
-     * 	@param	string	$query			SQL query string
398
-     * 	@param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
399
-     * 									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.
400
-     *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
401
-     *	@return	SQLite3Result			Resultset of answer
402
-     */
403
-    function query($query,$usesavepoint=0,$type='auto')
404
-    {
405
-        $ret=null;
406
-        $query = trim($query);
407
-        $this->error = 0;
408
-
409
-        // Convert MySQL syntax to SQLite syntax
410
-        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)) {
411
-            // Ajout d'une clef étrangère à la table
412
-            // procédure de remplacement de la table pour ajouter la contrainte
413
-            // Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
414
-            // -> CREATE TABLE ( ... ,CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid))
415
-            $foreignFields = $reg[5];
416
-            $foreignTable = $reg[4];
417
-            $localfields = $reg[3];
418
-            $constraintname=trim($reg[2]);
419
-            $tablename=trim($reg[1]);
420
-
421
-            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='" . $tablename . "'");
422
-
423
-            // 1- Renommer la table avec un nom temporaire
424
-            $this->query('ALTER TABLE ' . $tablename . ' RENAME TO tmp_' . $tablename);
425
-
426
-            // 2- Recréer la table avec la contrainte ajoutée
427
-
428
-            // on bricole la requete pour ajouter la contrainte
429
-            $descTable = substr($descTable, 0, strlen($descTable) - 1);
430
-            $descTable .= ", CONSTRAINT " . $constraintname . " FOREIGN KEY (" . $localfields . ") REFERENCES " .$foreignTable . "(" . $foreignFields . ")";
431
-
432
-            // fermeture de l'instruction
433
-            $descTable .= ')';
434
-
435
-            // Création proprement dite de la table
436
-            $this->query($descTable);
437
-
438
-            // 3- Transférer les données
439
-            $this->query('INSERT INTO ' . $tablename . ' SELECT * FROM tmp_' . $tablename);
440
-
441
-            // 4- Supprimer la table temporaire
442
-            $this->query('DROP TABLE tmp_' . $tablename);
443
-
444
-            // dummy statement
445
-            $query="SELECT 0";
446
-
447
-        } else {
448
-            $query=$this->convertSQLFromMysql($query,$type);
449
-        }
450
-        //print "After convertSQLFromMysql:\n".$query."<br>\n";
357
+	 */
358
+	function getVersion()
359
+	{
360
+		$tmp=$this->db->version();
361
+		return $tmp['versionString'];
362
+	}
451 363
 
452
-        dol_syslog('sql='.$query, LOG_DEBUG);
364
+	/**
365
+	 *	Return version of database client driver
366
+	 *
367
+	 *	@return	        string      Version string
368
+	 */
369
+	function getDriverInfo()
370
+	{
371
+		return 'sqlite3 php driver';
372
+	}
453 373
 
454
-        // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
455
-        try {
456
-            //$ret = $this->db->exec($query);
457
-            $ret = $this->db->query($query);        // $ret is a Sqlite3Result
458
-            if ($ret) {
459
-                $ret->queryString = $query;
460
-            }
461
-        }
462
-        catch(Exception $e)
463
-        {
464
-            $this->error=$this->db->lastErrorMsg();
465
-        }
466 374
 
467
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
468
-        {
469
-            // Si requete utilisateur, on la sauvegarde ainsi que son resultset
470
-            if (! is_object($ret) || $this->error)
471
-            {
472
-                $this->lastqueryerror = $query;
473
-                $this->lasterror = $this->error();
474
-                $this->lasterrno = $this->errno();
375
+	/**
376
+	 *  Close database connexion
377
+	 *
378
+	 *  @return     bool     True if disconnect successfull, false otherwise
379
+	 *  @see        connect
380
+	 */
381
+	function close()
382
+	{
383
+		if ($this->db)
384
+		{
385
+			if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
386
+			$this->connected=false;
387
+			$this->db->close();
388
+			unset($this->db);    // Clean this->db
389
+			return true;
390
+		}
391
+		return false;
392
+	}
475 393
 
476
-                dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
394
+	/**
395
+	 *  Execute a SQL request and return the resultset
396
+	 *
397
+	 * 	@param	string	$query			SQL query string
398
+	 * 	@param	int		$usesavepoint	0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
399
+	 * 									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.
400
+	 *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
401
+	 *	@return	SQLite3Result			Resultset of answer
402
+	 */
403
+	function query($query,$usesavepoint=0,$type='auto')
404
+	{
405
+		$ret=null;
406
+		$query = trim($query);
407
+		$this->error = 0;
408
+
409
+		// Convert MySQL syntax to SQLite syntax
410
+		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)) {
411
+			// Ajout d'une clef étrangère à la table
412
+			// procédure de remplacement de la table pour ajouter la contrainte
413
+			// Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
414
+			// -> CREATE TABLE ( ... ,CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid))
415
+			$foreignFields = $reg[5];
416
+			$foreignTable = $reg[4];
417
+			$localfields = $reg[3];
418
+			$constraintname=trim($reg[2]);
419
+			$tablename=trim($reg[1]);
420
+
421
+			$descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='" . $tablename . "'");
422
+
423
+			// 1- Renommer la table avec un nom temporaire
424
+			$this->query('ALTER TABLE ' . $tablename . ' RENAME TO tmp_' . $tablename);
425
+
426
+			// 2- Recréer la table avec la contrainte ajoutée
427
+
428
+			// on bricole la requete pour ajouter la contrainte
429
+			$descTable = substr($descTable, 0, strlen($descTable) - 1);
430
+			$descTable .= ", CONSTRAINT " . $constraintname . " FOREIGN KEY (" . $localfields . ") REFERENCES " .$foreignTable . "(" . $foreignFields . ")";
431
+
432
+			// fermeture de l'instruction
433
+			$descTable .= ')';
434
+
435
+			// Création proprement dite de la table
436
+			$this->query($descTable);
437
+
438
+			// 3- Transférer les données
439
+			$this->query('INSERT INTO ' . $tablename . ' SELECT * FROM tmp_' . $tablename);
440
+
441
+			// 4- Supprimer la table temporaire
442
+			$this->query('DROP TABLE tmp_' . $tablename);
443
+
444
+			// dummy statement
445
+			$query="SELECT 0";
446
+
447
+		} else {
448
+			$query=$this->convertSQLFromMysql($query,$type);
449
+		}
450
+		//print "After convertSQLFromMysql:\n".$query."<br>\n";
451
+
452
+		dol_syslog('sql='.$query, LOG_DEBUG);
453
+
454
+		// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
455
+		try {
456
+			//$ret = $this->db->exec($query);
457
+			$ret = $this->db->query($query);        // $ret is a Sqlite3Result
458
+			if ($ret) {
459
+				$ret->queryString = $query;
460
+			}
461
+		}
462
+		catch(Exception $e)
463
+		{
464
+			$this->error=$this->db->lastErrorMsg();
465
+		}
466
+
467
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
468
+		{
469
+			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
470
+			if (! is_object($ret) || $this->error)
471
+			{
472
+				$this->lastqueryerror = $query;
473
+				$this->lasterror = $this->error();
474
+				$this->lasterrno = $this->errno();
475
+
476
+				dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
477
+
478
+				$errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
479
+
480
+				if (preg_match('/[0-9]/',$this->lasterrno)) {
481
+					$errormsg .= ' ('.$this->lasterrno.')';
482
+				}
483
+
484
+				dol_syslog($errormsg, LOG_ERR);
485
+			}
486
+			$this->lastquery=$query;
487
+			$this->_results = $ret;
488
+		}
489
+
490
+		return $ret;
491
+	}
477 492
 
478
-                $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
493
+	/**
494
+	 *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
495
+	 *
496
+	 *	@param	SQLite3Result	$resultset  Curseur de la requete voulue
497
+	 *	@return	false|object				Object result line or false if KO or end of cursor
498
+	 */
499
+	function fetch_object($resultset)
500
+	{
501
+		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
502
+		if (! is_object($resultset)) { $resultset=$this->_results; }
503
+		//return $resultset->fetch(PDO::FETCH_OBJ);
504
+		$ret = $resultset->fetchArray(SQLITE3_ASSOC);
505
+		if ($ret) {
506
+			return (object) $ret;
507
+		}
508
+		return false;
509
+	}
479 510
 
480
-                if (preg_match('/[0-9]/',$this->lasterrno)) {
481
-                    $errormsg .= ' ('.$this->lasterrno.')';
482
-                }
483 511
 
484
-                dol_syslog($errormsg, LOG_ERR);
485
-            }
486
-            $this->lastquery=$query;
487
-            $this->_results = $ret;
488
-        }
512
+	/**
513
+	 *	Return datas as an array
514
+	 *
515
+	 *	@param	SQLite3Result	$resultset  Resultset of request
516
+	 *	@return	false|array					Array or false if KO or end of cursor
517
+	 */
518
+	function fetch_array($resultset)
519
+	{
520
+		// If resultset not provided, we take the last used by connexion
521
+		if (! is_object($resultset)) { $resultset=$this->_results; }
522
+		//return $resultset->fetch(PDO::FETCH_ASSOC);
523
+		$ret = $resultset->fetchArray(SQLITE3_ASSOC);
524
+		return $ret;
525
+	}
489 526
 
490
-        return $ret;
491
-    }
492
-
493
-    /**
494
-     *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
495
-     *
496
-     *	@param	SQLite3Result	$resultset  Curseur de la requete voulue
497
-     *	@return	false|object				Object result line or false if KO or end of cursor
498
-     */
499
-    function fetch_object($resultset)
500
-    {
501
-        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
502
-        if (! is_object($resultset)) { $resultset=$this->_results; }
503
-        //return $resultset->fetch(PDO::FETCH_OBJ);
504
-        $ret = $resultset->fetchArray(SQLITE3_ASSOC);
505
-        if ($ret) {
506
-            return (object) $ret;
507
-        }
508
-		return false;
509
-    }
510
-
511
-
512
-    /**
513
-     *	Return datas as an array
514
-     *
515
-     *	@param	SQLite3Result	$resultset  Resultset of request
516
-     *	@return	false|array					Array or false if KO or end of cursor
517
-     */
518
-    function fetch_array($resultset)
519
-    {
520
-        // If resultset not provided, we take the last used by connexion
521
-        if (! is_object($resultset)) { $resultset=$this->_results; }
522
-        //return $resultset->fetch(PDO::FETCH_ASSOC);
523
-        $ret = $resultset->fetchArray(SQLITE3_ASSOC);
524
-	    return $ret;
525
-    }
526
-
527
-    /**
528
-     *	Return datas as an array
529
-     *
530
-     *	@param	SQLite3Result	$resultset  Resultset of request
531
-     *	@return	false|array					Array or false if KO or end of cursor
532
-     */
533
-    function fetch_row($resultset)
534
-    {
535
-        // If resultset not provided, we take the last used by connexion
536
-        if (! is_bool($resultset))
537
-        {
538
-            if (! is_object($resultset)) { $resultset=$this->_results; }
539
-            return $resultset->fetchArray(SQLITE3_NUM);
540
-        }
541
-        else
542
-        {
543
-            // si le curseur est un booleen on retourne la valeur 0
544
-            return false;
545
-        }
546
-    }
547
-
548
-    /**
549
-     *	Return number of lines for result of a SELECT
550
-     *
551
-     *	@param	SQLite3Result	$resultset  Resulset of requests
552
-     *	@return int		    			Nb of lines
553
-     *	@see    affected_rows
554
-     */
555
-    function num_rows($resultset)
556
-    {
557
-	    // FIXME: SQLite3Result does not have a queryString member
558
-
559
-        // If resultset not provided, we take the last used by connexion
560
-        if (! is_object($resultset)) { $resultset=$this->_results; }
561
-        if (preg_match("/^SELECT/i", $resultset->queryString)) {
562
-            return $this->db->querySingle("SELECT count(*) FROM (" . $resultset->queryString . ") q");
563
-        }
564
-        return 0;
565
-    }
566
-
567
-    /**
568
-     *	Return number of lines for result of a SELECT
569
-     *
570
-     *	@param	SQLite3Result	$resultset  Resulset of requests
571
-     *	@return int		    			Nb of lines
572
-     *	@see    affected_rows
573
-     */
574
-    function affected_rows($resultset)
575
-    {
576
-	    // FIXME: SQLite3Result does not have a queryString member
577
-
578
-        // If resultset not provided, we take the last used by connexion
579
-        if (! is_object($resultset)) { $resultset=$this->_results; }
580
-        if (preg_match("/^SELECT/i", $resultset->queryString)) {
581
-            return $this->num_rows($resultset);
582
-        }
583
-        // mysql necessite un link de base pour cette fonction contrairement
584
-        // a pqsql qui prend un resultset
585
-        return $this->db->changes();
586
-    }
527
+	/**
528
+	 *	Return datas as an array
529
+	 *
530
+	 *	@param	SQLite3Result	$resultset  Resultset of request
531
+	 *	@return	false|array					Array or false if KO or end of cursor
532
+	 */
533
+	function fetch_row($resultset)
534
+	{
535
+		// If resultset not provided, we take the last used by connexion
536
+		if (! is_bool($resultset))
537
+		{
538
+			if (! is_object($resultset)) { $resultset=$this->_results; }
539
+			return $resultset->fetchArray(SQLITE3_NUM);
540
+		}
541
+		else
542
+		{
543
+			// si le curseur est un booleen on retourne la valeur 0
544
+			return false;
545
+		}
546
+	}
587 547
 
548
+	/**
549
+	 *	Return number of lines for result of a SELECT
550
+	 *
551
+	 *	@param	SQLite3Result	$resultset  Resulset of requests
552
+	 *	@return int		    			Nb of lines
553
+	 *	@see    affected_rows
554
+	 */
555
+	function num_rows($resultset)
556
+	{
557
+		// FIXME: SQLite3Result does not have a queryString member
558
+
559
+		// If resultset not provided, we take the last used by connexion
560
+		if (! is_object($resultset)) { $resultset=$this->_results; }
561
+		if (preg_match("/^SELECT/i", $resultset->queryString)) {
562
+			return $this->db->querySingle("SELECT count(*) FROM (" . $resultset->queryString . ") q");
563
+		}
564
+		return 0;
565
+	}
588 566
 
589
-    /**
567
+	/**
568
+	 *	Return number of lines for result of a SELECT
569
+	 *
570
+	 *	@param	SQLite3Result	$resultset  Resulset of requests
571
+	 *	@return int		    			Nb of lines
572
+	 *	@see    affected_rows
573
+	 */
574
+	function affected_rows($resultset)
575
+	{
576
+		// FIXME: SQLite3Result does not have a queryString member
577
+
578
+		// If resultset not provided, we take the last used by connexion
579
+		if (! is_object($resultset)) { $resultset=$this->_results; }
580
+		if (preg_match("/^SELECT/i", $resultset->queryString)) {
581
+			return $this->num_rows($resultset);
582
+		}
583
+		// mysql necessite un link de base pour cette fonction contrairement
584
+		// a pqsql qui prend un resultset
585
+		return $this->db->changes();
586
+	}
587
+
588
+
589
+	/**
590 590
 	 *	Free last resultset used.
591
-     *
591
+	 *
592 592
 	 *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
593 593
 	 *	@return	void
594
-     */
595
-    function free($resultset=null)
596
-    {
597
-        // If resultset not provided, we take the last used by connexion
598
-        if (! is_object($resultset)) { $resultset=$this->_results; }
599
-        // Si resultset en est un, on libere la memoire
600
-        if ($resultset && is_object($resultset)) $resultset->finalize();
601
-    }
602
-
603
-    /**
594
+	 */
595
+	function free($resultset=null)
596
+	{
597
+		// If resultset not provided, we take the last used by connexion
598
+		if (! is_object($resultset)) { $resultset=$this->_results; }
599
+		// Si resultset en est un, on libere la memoire
600
+		if ($resultset && is_object($resultset)) $resultset->finalize();
601
+	}
602
+
603
+	/**
604 604
 	 *	Escape a string to insert data
605
-     *
605
+	 *
606 606
 	 *  @param	string	$stringtoencode		String to escape
607 607
 	 *  @return	string						String escaped
608
-     */
609
-    function escape($stringtoencode)
610
-    {
611
-        return Sqlite3::escapeString($stringtoencode);
612
-    }
613
-
614
-    /**
615
-     *	Renvoie le code erreur generique de l'operation precedente.
616
-     *
617
-     *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
618
-     */
619
-    function errno()
620
-    {
621
-        if (! $this->connected) {
622
-            // Si il y a eu echec de connexion, $this->db n'est pas valide.
623
-            return 'DB_ERROR_FAILED_TO_CONNECT';
624
-        }
625
-        else {
626
-            // Constants to convert error code to a generic Dolibarr error code
627
-            /*$errorcode_map = array(
608
+	 */
609
+	function escape($stringtoencode)
610
+	{
611
+		return Sqlite3::escapeString($stringtoencode);
612
+	}
613
+
614
+	/**
615
+	 *	Renvoie le code erreur generique de l'operation precedente.
616
+	 *
617
+	 *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
618
+	 */
619
+	function errno()
620
+	{
621
+		if (! $this->connected) {
622
+			// Si il y a eu echec de connexion, $this->db n'est pas valide.
623
+			return 'DB_ERROR_FAILED_TO_CONNECT';
624
+		}
625
+		else {
626
+			// Constants to convert error code to a generic Dolibarr error code
627
+			/*$errorcode_map = array(
628 628
             1004 => 'DB_ERROR_CANNOT_CREATE',
629 629
             1005 => 'DB_ERROR_CANNOT_CREATE',
630 630
             1006 => 'DB_ERROR_CANNOT_CREATE',
@@ -656,220 +656,220 @@  discard block
 block discarded – undo
656 656
             {
657 657
                 return $errorcode_map[$this->db->errorCode()];
658 658
             }*/
659
-            $errno=$this->db->lastErrorCode();
659
+			$errno=$this->db->lastErrorCode();
660 660
 			if ($errno=='HY000' || $errno == 0)
661
-            {
662
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
663
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
664
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
665
-            }
666
-            if ($errno=='23000')
667
-            {
668
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
669
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
670
-            }
671
-            if ($errno > 1) {
672
-                // TODO Voir la liste des messages d'erreur
673
-            }
674
-
675
-            return ($errno?'DB_ERROR_'.$errno:'0');
676
-        }
677
-    }
678
-
679
-    /**
680
-     *	Renvoie le texte de l'erreur mysql de l'operation precedente.
681
-     *
682
-     *	@return	string	Error text
683
-     */
684
-    function error()
685
-    {
686
-        if (! $this->connected) {
687
-            // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
688
-            return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
689
-        }
690
-        else {
691
-            return $this->error;
692
-        }
693
-    }
661
+			{
662
+				if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
663
+				elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
664
+				elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
665
+			}
666
+			if ($errno=='23000')
667
+			{
668
+				if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
669
+				elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
670
+			}
671
+			if ($errno > 1) {
672
+				// TODO Voir la liste des messages d'erreur
673
+			}
674
+
675
+			return ($errno?'DB_ERROR_'.$errno:'0');
676
+		}
677
+	}
694 678
 
695
-    /**
696
-     * Get last ID after an insert INSERT
697
-     *
679
+	/**
680
+	 *	Renvoie le texte de l'erreur mysql de l'operation precedente.
681
+	 *
682
+	 *	@return	string	Error text
683
+	 */
684
+	function error()
685
+	{
686
+		if (! $this->connected) {
687
+			// Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
688
+			return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
689
+		}
690
+		else {
691
+			return $this->error;
692
+		}
693
+	}
694
+
695
+	/**
696
+	 * Get last ID after an insert INSERT
697
+	 *
698 698
 	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
699 699
 	 * @param	string	$fieldid	Field name
700 700
 	 * @return  int     			Id of row
701
-     */
702
-    function last_insert_id($tab,$fieldid='rowid')
703
-    {
704
-        return $this->db->lastInsertRowId();
705
-    }
706
-
707
-    /**
708
-     *  Encrypt sensitive data in database
709
-     *  Warning: This function includes the escape, so it must use direct value
710
-     *
711
-     *  @param  string  $fieldorvalue   Field name or value to encrypt
712
-     *  @param	int		$withQuotes     Return string with quotes
713
-     *  @return string          		XXX(field) or XXX('value') or field or 'value'
714
-     */
715
-    function encrypt($fieldorvalue, $withQuotes=0)
716
-    {
717
-        global $conf;
718
-
719
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
720
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
721
-
722
-        //Encryption key
723
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
724
-
725
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
726
-
727
-        if ($cryptType && !empty($cryptKey))
728
-        {
729
-            if ($cryptType == 2)
730
-            {
731
-                $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
732
-            }
733
-            else if ($cryptType == 1)
734
-            {
735
-                $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
736
-            }
737
-        }
701
+	 */
702
+	function last_insert_id($tab,$fieldid='rowid')
703
+	{
704
+		return $this->db->lastInsertRowId();
705
+	}
738 706
 
739
-        return $return;
740
-    }
707
+	/**
708
+	 *  Encrypt sensitive data in database
709
+	 *  Warning: This function includes the escape, so it must use direct value
710
+	 *
711
+	 *  @param  string  $fieldorvalue   Field name or value to encrypt
712
+	 *  @param	int		$withQuotes     Return string with quotes
713
+	 *  @return string          		XXX(field) or XXX('value') or field or 'value'
714
+	 */
715
+	function encrypt($fieldorvalue, $withQuotes=0)
716
+	{
717
+		global $conf;
741 718
 
742
-    /**
743
-     *	Decrypt sensitive data in database
744
-     *
745
-     *	@param	string	$value			Value to decrypt
746
-     * 	@return	string					Decrypted value if used
747
-     */
748
-    function decrypt($value)
749
-    {
750
-        global $conf;
719
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
720
+		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
751 721
 
752
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
753
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
722
+		//Encryption key
723
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
754 724
 
755
-        //Encryption key
756
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
725
+		$return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
757 726
 
758
-        $return = $value;
727
+		if ($cryptType && !empty($cryptKey))
728
+		{
729
+			if ($cryptType == 2)
730
+			{
731
+				$return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
732
+			}
733
+			else if ($cryptType == 1)
734
+			{
735
+				$return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
736
+			}
737
+		}
759 738
 
760
-        if ($cryptType && !empty($cryptKey))
761
-        {
762
-            if ($cryptType == 2)
763
-            {
764
-                $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
765
-            }
766
-            else if ($cryptType == 1)
767
-            {
768
-                $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
769
-            }
770
-        }
739
+		return $return;
740
+	}
741
+
742
+	/**
743
+	 *	Decrypt sensitive data in database
744
+	 *
745
+	 *	@param	string	$value			Value to decrypt
746
+	 * 	@return	string					Decrypted value if used
747
+	 */
748
+	function decrypt($value)
749
+	{
750
+		global $conf;
751
+
752
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
753
+		$cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
754
+
755
+		//Encryption key
756
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
757
+
758
+		$return = $value;
771 759
 
772
-        return $return;
773
-    }
760
+		if ($cryptType && !empty($cryptKey))
761
+		{
762
+			if ($cryptType == 2)
763
+			{
764
+				$return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
765
+			}
766
+			else if ($cryptType == 1)
767
+			{
768
+				$return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
769
+			}
770
+		}
774 771
 
772
+		return $return;
773
+	}
775 774
 
776
-    /**
777
-     * Return connexion ID
778
-     *
775
+
776
+	/**
777
+	 * Return connexion ID
778
+	 *
779 779
 	 * @return	        string      Id connexion
780
-     */
781
-    function DDLGetConnectId()
782
-    {
783
-        return '?';
784
-    }
780
+	 */
781
+	function DDLGetConnectId()
782
+	{
783
+		return '?';
784
+	}
785 785
 
786 786
 
787
-    /**
787
+	/**
788 788
 	 *	Create a new database
789 789
 	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
790 790
 	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
791
-     *
791
+	 *
792 792
 	 *	@param	string	$database		Database name to create
793 793
 	 * 	@param	string	$charset		Charset used to store data
794 794
 	 * 	@param	string	$collation		Charset used to sort data
795 795
 	 * 	@param	string	$owner			Username of database owner
796 796
 	 * 	@return	SQLite3Result   		resource defined if OK, null if KO
797
-     */
798
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
799
-    {
800
-        if (empty($charset))   $charset=$this->forcecharset;
801
-        if (empty($collation)) $collation=$this->forcecollate;
802
-
803
-        // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
804
-        $sql = 'CREATE DATABASE '.$database;
805
-        $sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
806
-
807
-        dol_syslog($sql,LOG_DEBUG);
808
-        $ret=$this->query($sql);
809
-        if (! $ret)
810
-        {
811
-            // We try again for compatibility with Mysql < 4.1.1
812
-            $sql = 'CREATE DATABASE '.$database;
813
-            $ret=$this->query($sql);
814
-            dol_syslog($sql,LOG_DEBUG);
815
-        }
816
-        return $ret;
817
-    }
797
+	 */
798
+	function DDLCreateDb($database,$charset='',$collation='',$owner='')
799
+	{
800
+		if (empty($charset))   $charset=$this->forcecharset;
801
+		if (empty($collation)) $collation=$this->forcecollate;
802
+
803
+		// ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
804
+		$sql = 'CREATE DATABASE '.$database;
805
+		$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
806
+
807
+		dol_syslog($sql,LOG_DEBUG);
808
+		$ret=$this->query($sql);
809
+		if (! $ret)
810
+		{
811
+			// We try again for compatibility with Mysql < 4.1.1
812
+			$sql = 'CREATE DATABASE '.$database;
813
+			$ret=$this->query($sql);
814
+			dol_syslog($sql,LOG_DEBUG);
815
+		}
816
+		return $ret;
817
+	}
818 818
 
819
-    /**
820
-     *  List tables into a database
821
-     *
819
+	/**
820
+	 *  List tables into a database
821
+	 *
822 822
 	 *  @param	string		$database	Name of database
823 823
 	 *  @param	string		$table		Name of table filter ('xxx%')
824 824
 	 *  @return	array					List of tables in an array
825
-     */
826
-    function DDLListTables($database, $table='')
827
-    {
828
-        $listtables=array();
829
-
830
-        $like = '';
831
-        if ($table) $like = "LIKE '".$table."'";
832
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
833
-        //print $sql;
834
-        $result = $this->query($sql);
835
-        if ($result)
836
-        {
837
-            while($row = $this->fetch_row($result))
838
-            {
839
-                $listtables[] = $row[0];
840
-            }
841
-        }
842
-        return $listtables;
843
-    }
825
+	 */
826
+	function DDLListTables($database, $table='')
827
+	{
828
+		$listtables=array();
829
+
830
+		$like = '';
831
+		if ($table) $like = "LIKE '".$table."'";
832
+		$sql="SHOW TABLES FROM ".$database." ".$like.";";
833
+		//print $sql;
834
+		$result = $this->query($sql);
835
+		if ($result)
836
+		{
837
+			while($row = $this->fetch_row($result))
838
+			{
839
+				$listtables[] = $row[0];
840
+			}
841
+		}
842
+		return $listtables;
843
+	}
844 844
 
845
-    /**
845
+	/**
846 846
 	 *	List information of columns into a table.
847
-     *
847
+	 *
848 848
 	 *	@param	string	$table		Name of table
849 849
 	 *	@return	array				Tableau des informations des champs de la table
850 850
 	 *	TODO modify for sqlite
851
-     */
852
-    function DDLInfoTable($table)
853
-    {
854
-        $infotables=array();
855
-
856
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
857
-
858
-        dol_syslog($sql,LOG_DEBUG);
859
-        $result = $this->query($sql);
860
-        if ($result)
861
-        {
862
-            while($row = $this->fetch_row($result))
863
-            {
864
-                $infotables[] = $row;
865
-            }
866
-        }
867
-        return $infotables;
868
-    }
851
+	 */
852
+	function DDLInfoTable($table)
853
+	{
854
+		$infotables=array();
855
+
856
+		$sql="SHOW FULL COLUMNS FROM ".$table.";";
857
+
858
+		dol_syslog($sql,LOG_DEBUG);
859
+		$result = $this->query($sql);
860
+		if ($result)
861
+		{
862
+			while($row = $this->fetch_row($result))
863
+			{
864
+				$infotables[] = $row;
865
+			}
866
+		}
867
+		return $infotables;
868
+	}
869 869
 
870
-    /**
870
+	/**
871 871
 	 *	Create a table into database
872
-     *
872
+	 *
873 873
 	 *	@param	    string	$table 			Nom de la table
874 874
 	 *	@param	    array	$fields 		Tableau associatif [nom champ][tableau des descriptions]
875 875
 	 *	@param	    string	$primary_key 	Nom du champ qui sera la clef primaire
@@ -878,367 +878,367 @@  discard block
 block discarded – undo
878 878
 	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
879 879
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
880 880
 	 *	@return	    int						<0 if KO, >=0 if OK
881
-     */
882
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
883
-    {
884
-	    // FIXME: $fulltext_keys parameter is unused
885
-
886
-        // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
887
-        // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
888
-        $sql = "create table ".$table."(";
889
-        $i=0;
890
-        foreach($fields as $field_name => $field_desc)
891
-        {
892
-            $sqlfields[$i] = $field_name." ";
893
-            $sqlfields[$i]  .= $field_desc['type'];
894
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
895
-            $sqlfields[$i]  .= "(".$field_desc['value'].")";
896
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
897
-            $sqlfields[$i]  .= " ".$field_desc['attribute'];
898
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
899
-            {
900
-                if(preg_match("/null/i",$field_desc['default']))
901
-                $sqlfields[$i]  .= " default ".$field_desc['default'];
902
-                else
903
-                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
904
-            }
905
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
906
-            $sqlfields[$i]  .= " ".$field_desc['null'];
907
-
908
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
909
-            $sqlfields[$i]  .= " ".$field_desc['extra'];
910
-            $i++;
911
-        }
912
-        if($primary_key != "")
913
-        $pk = "primary key(".$primary_key.")";
881
+	 */
882
+	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
883
+	{
884
+		// FIXME: $fulltext_keys parameter is unused
885
+
886
+		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
887
+		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
888
+		$sql = "create table ".$table."(";
889
+		$i=0;
890
+		foreach($fields as $field_name => $field_desc)
891
+		{
892
+			$sqlfields[$i] = $field_name." ";
893
+			$sqlfields[$i]  .= $field_desc['type'];
894
+			if( preg_match("/^[^\s]/i",$field_desc['value']))
895
+			$sqlfields[$i]  .= "(".$field_desc['value'].")";
896
+			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
897
+			$sqlfields[$i]  .= " ".$field_desc['attribute'];
898
+			else if( preg_match("/^[^\s]/i",$field_desc['default']))
899
+			{
900
+				if(preg_match("/null/i",$field_desc['default']))
901
+				$sqlfields[$i]  .= " default ".$field_desc['default'];
902
+				else
903
+				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
904
+			}
905
+			else if( preg_match("/^[^\s]/i",$field_desc['null']))
906
+			$sqlfields[$i]  .= " ".$field_desc['null'];
907
+
908
+			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
909
+			$sqlfields[$i]  .= " ".$field_desc['extra'];
910
+			$i++;
911
+		}
912
+		if($primary_key != "")
913
+		$pk = "primary key(".$primary_key.")";
914
+
915
+		if(is_array($unique_keys))
916
+		{
917
+			$i = 0;
918
+			foreach($unique_keys as $key => $value)
919
+			{
920
+				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
921
+				$i++;
922
+			}
923
+		}
924
+		if(is_array($keys))
925
+		{
926
+			$i = 0;
927
+			foreach($keys as $key => $value)
928
+			{
929
+				$sqlk[$i] = "KEY ".$key." (".$value.")";
930
+				$i++;
931
+			}
932
+		}
933
+		$sql .= implode(',',$sqlfields);
934
+		if($primary_key != "")
935
+		$sql .= ",".$pk;
936
+		if(is_array($unique_keys))
937
+		$sql .= ",".implode(',',$sqluq);
938
+		if(is_array($keys))
939
+		$sql .= ",".implode(',',$sqlk);
940
+		$sql .=") type=".$type;
941
+
942
+		dol_syslog($sql,LOG_DEBUG);
943
+		if(! $this -> query($sql))
944
+			return -1;
945
+		return 1;
946
+	}
914 947
 
915
-        if(is_array($unique_keys))
916
-        {
917
-            $i = 0;
918
-            foreach($unique_keys as $key => $value)
919
-            {
920
-                $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
921
-                $i++;
922
-            }
923
-        }
924
-        if(is_array($keys))
925
-        {
926
-            $i = 0;
927
-            foreach($keys as $key => $value)
928
-            {
929
-                $sqlk[$i] = "KEY ".$key." (".$value.")";
930
-                $i++;
931
-            }
932
-        }
933
-        $sql .= implode(',',$sqlfields);
934
-        if($primary_key != "")
935
-        $sql .= ",".$pk;
936
-        if(is_array($unique_keys))
937
-        $sql .= ",".implode(',',$sqluq);
938
-        if(is_array($keys))
939
-        $sql .= ",".implode(',',$sqlk);
940
-        $sql .=") type=".$type;
941
-
942
-        dol_syslog($sql,LOG_DEBUG);
943
-        if(! $this -> query($sql))
944
-            return -1;
945
-        return 1;
946
-    }
947
-
948
-    /**
948
+	/**
949 949
 	 *	Return a pointer of line with description of a table or field
950
-     *
950
+	 *
951 951
 	 *	@param	string		$table	Name of table
952 952
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
953 953
 	 *	@return	SQLite3Result		Resource
954
-     */
955
-    function DDLDescTable($table,$field="")
956
-    {
957
-        $sql="DESC ".$table." ".$field;
954
+	 */
955
+	function DDLDescTable($table,$field="")
956
+	{
957
+		$sql="DESC ".$table." ".$field;
958 958
 
959
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
960
-        $this->_results = $this->query($sql);
961
-        return $this->_results;
962
-    }
959
+		dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
960
+		$this->_results = $this->query($sql);
961
+		return $this->_results;
962
+	}
963 963
 
964
-    /**
964
+	/**
965 965
 	 *	Create a new field into table
966
-     *
966
+	 *
967 967
 	 *	@param	string	$table 				Name of table
968 968
 	 *	@param	string	$field_name 		Name of field to add
969 969
 	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
970 970
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
971 971
 	 *	@return	int							<0 if KO, >0 if OK
972
-     */
973
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
974
-    {
975
-        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
976
-        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
977
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
978
-        $sql.= $field_desc['type'];
979
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
980
-        if (! in_array($field_desc['type'],array('date','datetime')))
981
-        {
982
-            $sql.= "(".$field_desc['value'].")";
983
-        }
984
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
985
-        $sql.= " ".$field_desc['attribute'];
986
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
987
-        $sql.= " ".$field_desc['null'];
988
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
989
-        {
990
-            if(preg_match("/null/i",$field_desc['default']))
991
-            $sql.= " default ".$field_desc['default'];
992
-            else
993
-            $sql.= " default '".$field_desc['default']."'";
994
-        }
995
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
996
-        $sql.= " ".$field_desc['extra'];
997
-        $sql.= " ".$field_position;
998
-
999
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1000
-        if(! $this->query($sql))
1001
-        {
1002
-            return -1;
1003
-        }
1004
-        return 1;
1005
-    }
972
+	 */
973
+	function DDLAddField($table,$field_name,$field_desc,$field_position="")
974
+	{
975
+		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
976
+		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
977
+		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
978
+		$sql.= $field_desc['type'];
979
+		if(preg_match("/^[^\s]/i",$field_desc['value']))
980
+		if (! in_array($field_desc['type'],array('date','datetime')))
981
+		{
982
+			$sql.= "(".$field_desc['value'].")";
983
+		}
984
+		if(preg_match("/^[^\s]/i",$field_desc['attribute']))
985
+		$sql.= " ".$field_desc['attribute'];
986
+		if(preg_match("/^[^\s]/i",$field_desc['null']))
987
+		$sql.= " ".$field_desc['null'];
988
+		if(preg_match("/^[^\s]/i",$field_desc['default']))
989
+		{
990
+			if(preg_match("/null/i",$field_desc['default']))
991
+			$sql.= " default ".$field_desc['default'];
992
+			else
993
+			$sql.= " default '".$field_desc['default']."'";
994
+		}
995
+		if(preg_match("/^[^\s]/i",$field_desc['extra']))
996
+		$sql.= " ".$field_desc['extra'];
997
+		$sql.= " ".$field_position;
998
+
999
+		dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1000
+		if(! $this->query($sql))
1001
+		{
1002
+			return -1;
1003
+		}
1004
+		return 1;
1005
+	}
1006 1006
 
1007
-    /**
1007
+	/**
1008 1008
 	 *	Update format of a field into a table
1009
-     *
1009
+	 *
1010 1010
 	 *	@param	string	$table 				Name of table
1011 1011
 	 *	@param	string	$field_name 		Name of field to modify
1012 1012
 	 *	@param	string	$field_desc 		Array with description of field format
1013 1013
 	 *	@return	int							<0 if KO, >0 if OK
1014
-     */
1015
-    function DDLUpdateField($table,$field_name,$field_desc)
1016
-    {
1017
-        $sql = "ALTER TABLE ".$table;
1018
-        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1019
-        if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1020
-            $sql.="(".$field_desc['value'].")";
1021
-        }
1022
-
1023
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1024
-        if (! $this->query($sql))
1025
-            return -1;
1026
-        return 1;
1027
-    }
1014
+	 */
1015
+	function DDLUpdateField($table,$field_name,$field_desc)
1016
+	{
1017
+		$sql = "ALTER TABLE ".$table;
1018
+		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1019
+		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1020
+			$sql.="(".$field_desc['value'].")";
1021
+		}
1022
+
1023
+		dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1024
+		if (! $this->query($sql))
1025
+			return -1;
1026
+		return 1;
1027
+	}
1028 1028
 
1029
-    /**
1029
+	/**
1030 1030
 	 *	Drop a field from table
1031
-     *
1031
+	 *
1032 1032
 	 *	@param	string	$table 			Name of table
1033 1033
 	 *	@param	string	$field_name 	Name of field to drop
1034 1034
 	 *	@return	int						<0 if KO, >0 if OK
1035
-     */
1036
-    function DDLDropField($table,$field_name)
1037
-    {
1038
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1039
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1040
-        if (! $this->query($sql))
1041
-        {
1042
-            $this->error=$this->lasterror();
1043
-            return -1;
1044
-        }
1045
-        return 1;
1046
-    }
1035
+	 */
1036
+	function DDLDropField($table,$field_name)
1037
+	{
1038
+		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1039
+		dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1040
+		if (! $this->query($sql))
1041
+		{
1042
+			$this->error=$this->lasterror();
1043
+			return -1;
1044
+		}
1045
+		return 1;
1046
+	}
1047 1047
 
1048 1048
 
1049
-    /**
1049
+	/**
1050 1050
 	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
1051
-     *
1051
+	 *
1052 1052
 	 *	@param	string	$dolibarr_main_db_host 		Ip serveur
1053 1053
 	 *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1054 1054
 	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1055 1055
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1056 1056
 	 *	@return	int									<0 if KO, >=0 if OK
1057
-     */
1058
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1059
-    {
1060
-        $sql = "INSERT INTO user ";
1061
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1062
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1063
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1064
-
1065
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1066
-        $resql=$this->query($sql);
1067
-        if (! $resql)
1068
-        {
1069
-            return -1;
1070
-        }
1071
-
1072
-        $sql = "INSERT INTO db ";
1073
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1074
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1075
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1076
-
1077
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1078
-        $resql=$this->query($sql);
1079
-        if (! $resql)
1080
-        {
1081
-            return -1;
1082
-        }
1083
-
1084
-        $sql="FLUSH Privileges";
1085
-
1086
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1087
-        $resql=$this->query($sql);
1088
-        if (! $resql)
1089
-        {
1090
-            return -1;
1091
-        }
1092
-        return 1;
1093
-    }
1057
+	 */
1058
+	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1059
+	{
1060
+		$sql = "INSERT INTO user ";
1061
+		$sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1062
+		$sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1063
+		$sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1064
+
1065
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1066
+		$resql=$this->query($sql);
1067
+		if (! $resql)
1068
+		{
1069
+			return -1;
1070
+		}
1071
+
1072
+		$sql = "INSERT INTO db ";
1073
+		$sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1074
+		$sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1075
+		$sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1076
+
1077
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1078
+		$resql=$this->query($sql);
1079
+		if (! $resql)
1080
+		{
1081
+			return -1;
1082
+		}
1083
+
1084
+		$sql="FLUSH Privileges";
1085
+
1086
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1087
+		$resql=$this->query($sql);
1088
+		if (! $resql)
1089
+		{
1090
+			return -1;
1091
+		}
1092
+		return 1;
1093
+	}
1094 1094
 
1095
-    /**
1095
+	/**
1096 1096
 	 *	Return charset used to store data in database
1097
-     *
1097
+	 *
1098 1098
 	 *	@return		string		Charset
1099
-     */
1100
-    function getDefaultCharacterSetDatabase()
1101
-    {
1102
-        return 'UTF-8';
1103
-    }
1099
+	 */
1100
+	function getDefaultCharacterSetDatabase()
1101
+	{
1102
+		return 'UTF-8';
1103
+	}
1104 1104
 
1105
-    /**
1105
+	/**
1106 1106
 	 *	Return list of available charset that can be used to store data in database
1107
-     *
1107
+	 *
1108 1108
 	 *	@return		array		List of Charset
1109
-     */
1110
-    function getListOfCharacterSet()
1111
-    {
1112
-        $liste = array();
1113
-        $i=0;
1114
-        $liste[$i]['charset'] = 'UTF-8';
1115
-        $liste[$i]['description'] = 'UTF-8';
1116
-        return $liste;
1117
-    }
1118
-
1119
-    /**
1109
+	 */
1110
+	function getListOfCharacterSet()
1111
+	{
1112
+		$liste = array();
1113
+		$i=0;
1114
+		$liste[$i]['charset'] = 'UTF-8';
1115
+		$liste[$i]['description'] = 'UTF-8';
1116
+		return $liste;
1117
+	}
1118
+
1119
+	/**
1120 1120
 	 *	Return collation used in database
1121
-     *
1121
+	 *
1122 1122
 	 *	@return		string		Collation value
1123
-     */
1124
-    function getDefaultCollationDatabase()
1125
-    {
1126
-        return 'UTF-8';
1127
-    }
1123
+	 */
1124
+	function getDefaultCollationDatabase()
1125
+	{
1126
+		return 'UTF-8';
1127
+	}
1128 1128
 
1129
-    /**
1129
+	/**
1130 1130
 	 *	Return list of available collation that can be used for database
1131
-     *
1131
+	 *
1132 1132
 	 *	@return		array		List of Collation
1133
-     */
1134
-    function getListOfCollation()
1135
-    {
1136
-        $liste = array();
1137
-        $i=0;
1138
-        $liste[$i]['charset'] = 'UTF-8';
1139
-        $liste[$i]['description'] = 'UTF-8';
1140
-        return $liste;
1141
-    }
1142
-
1143
-    /**
1133
+	 */
1134
+	function getListOfCollation()
1135
+	{
1136
+		$liste = array();
1137
+		$i=0;
1138
+		$liste[$i]['charset'] = 'UTF-8';
1139
+		$liste[$i]['description'] = 'UTF-8';
1140
+		return $liste;
1141
+	}
1142
+
1143
+	/**
1144 1144
 	 *	Return full path of dump program
1145
-     *
1145
+	 *
1146 1146
 	 *	@return		string		Full path of dump program
1147
-     */
1148
-    function getPathOfDump()
1149
-    {
1150
-	    // FIXME: not for SQLite
1151
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1152
-
1153
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1154
-        if ($resql)
1155
-        {
1156
-            $liste=$this->fetch_array($resql);
1157
-            $basedir=$liste['Value'];
1158
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1159
-        }
1160
-        return $fullpathofdump;
1161
-    }
1147
+	 */
1148
+	function getPathOfDump()
1149
+	{
1150
+		// FIXME: not for SQLite
1151
+		$fullpathofdump='/pathtomysqldump/mysqldump';
1152
+
1153
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1154
+		if ($resql)
1155
+		{
1156
+			$liste=$this->fetch_array($resql);
1157
+			$basedir=$liste['Value'];
1158
+			$fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1159
+		}
1160
+		return $fullpathofdump;
1161
+	}
1162 1162
 
1163
-    /**
1163
+	/**
1164 1164
 	 *	Return full path of restore program
1165
-     *
1165
+	 *
1166 1166
 	 *	@return		string		Full path of restore program
1167
-     */
1168
-    function getPathOfRestore()
1169
-    {
1170
-	    // FIXME: not for SQLite
1171
-        $fullpathofimport='/pathtomysql/mysql';
1172
-
1173
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1174
-        if ($resql)
1175
-        {
1176
-            $liste=$this->fetch_array($resql);
1177
-            $basedir=$liste['Value'];
1178
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1179
-        }
1180
-        return $fullpathofimport;
1181
-    }
1167
+	 */
1168
+	function getPathOfRestore()
1169
+	{
1170
+		// FIXME: not for SQLite
1171
+		$fullpathofimport='/pathtomysql/mysql';
1172
+
1173
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1174
+		if ($resql)
1175
+		{
1176
+			$liste=$this->fetch_array($resql);
1177
+			$basedir=$liste['Value'];
1178
+			$fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1179
+		}
1180
+		return $fullpathofimport;
1181
+	}
1182 1182
 
1183
-    /**
1184
-     * Return value of server parameters
1185
-     *
1183
+	/**
1184
+	 * Return value of server parameters
1185
+	 *
1186 1186
 	 * @param	string	$filter		Filter list on a particular value
1187 1187
 	 * @return	array				Array of key-values (key=>value)
1188
-     */
1189
-    function getServerParametersValues($filter='')
1190
-    {
1191
-        $result=array();
1192
-        static $pragmas;
1193
-        if (! isset($pragmas)) {
1194
-            // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1195
-            // indépendante de la base de données.
1196
-            // cf. http://www.sqlite.org/pragma.html
1197
-            $pragmas = array(
1198
-                'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1199
-                'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1188
+	 */
1189
+	function getServerParametersValues($filter='')
1190
+	{
1191
+		$result=array();
1192
+		static $pragmas;
1193
+		if (! isset($pragmas)) {
1194
+			// Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1195
+			// indépendante de la base de données.
1196
+			// cf. http://www.sqlite.org/pragma.html
1197
+			$pragmas = array(
1198
+				'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1199
+				'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1200 1200
 				'compile_options', 'data_version',	/*'database_list',*/
1201
-                'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1202
-                'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1203
-                'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
1204
-                'max_page_count', 'page_count', 'page_size', 'parser_trace',
1205
-                'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
1206
-                'reverse_unordered_selects', 'schema_version', 'user_version',
1207
-                'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
1208
-                'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
1209
-                'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
1210
-                'wal_autocheckpoint',
1211
-            );
1212
-        }
1213
-
1214
-        // TODO prendre en compte le filtre
1215
-        foreach($pragmas as $var) {
1216
-            $sql = "PRAGMA $var";
1217
-            $resql=$this->query($sql);
1218
-            if ($resql)
1219
-            {
1220
-                $obj = $this->fetch_row($resql);
1221
-                //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1222
-                $result[$var] = $obj[0];
1223
-            }
1224
-            else {
1225
-                // TODO Récupérer le message
1226
-                $result[$var] = 'FAIL';
1227
-            }
1228
-        }
1229
-        return $result;
1230
-    }
1201
+				'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1202
+				'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1203
+				'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
1204
+				'max_page_count', 'page_count', 'page_size', 'parser_trace',
1205
+				'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
1206
+				'reverse_unordered_selects', 'schema_version', 'user_version',
1207
+				'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
1208
+				'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
1209
+				'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
1210
+				'wal_autocheckpoint',
1211
+			);
1212
+		}
1213
+
1214
+		// TODO prendre en compte le filtre
1215
+		foreach($pragmas as $var) {
1216
+			$sql = "PRAGMA $var";
1217
+			$resql=$this->query($sql);
1218
+			if ($resql)
1219
+			{
1220
+				$obj = $this->fetch_row($resql);
1221
+				//dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1222
+				$result[$var] = $obj[0];
1223
+			}
1224
+			else {
1225
+				// TODO Récupérer le message
1226
+				$result[$var] = 'FAIL';
1227
+			}
1228
+		}
1229
+		return $result;
1230
+	}
1231 1231
 
1232
-    /**
1233
-     * Return value of server status
1234
-     *
1232
+	/**
1233
+	 * Return value of server status
1234
+	 *
1235 1235
 	 * @param	string	$filter		Filter list on a particular value
1236 1236
 	 * @return  array				Array of key-values (key=>value)
1237
-     */
1238
-    function getServerStatusValues($filter='')
1239
-    {
1240
-        $result=array();
1241
-        /*
1237
+	 */
1238
+	function getServerStatusValues($filter='')
1239
+	{
1240
+		$result=array();
1241
+		/*
1242 1242
         $sql='SHOW STATUS';
1243 1243
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1244 1244
         $resql=$this->query($sql);
@@ -1248,79 +1248,79 @@  discard block
 block discarded – undo
1248 1248
         }
1249 1249
          */
1250 1250
 
1251
-        return $result;
1252
-    }
1253
-
1254
-    /**
1255
-     * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
1256
-     * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
1257
-     * statique et publique. Le nombre de parametres est determine automatiquement.
1258
-     *
1259
-     * @param 	string 	$name 			Le nom de la fonction a definir dans Sqlite
1260
-     * @param	int		$arg_count		Arg count
1261
-     * @return	void
1262
-     */
1263
-    private function addCustomFunction($name, $arg_count = -1)
1264
-    {
1265
-        if ($this->db)
1266
-        {
1267
-        	$newname=preg_replace('/_/','',$name);
1268
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1269
-            $reflectClass = new ReflectionClass(__CLASS__);
1270
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1271
-            if ($arg_count < 0) {
1272
-                $arg_count = $reflectFunction->getNumberOfParameters();
1273
-            }
1274
-            if (!$this->db->createFunction($name, $localname, $arg_count))
1275
-            {
1276
-                $this->error = "unable to create custom function '$name'";
1277
-            }
1278
-        }
1279
-    }
1280
-
1281
-    /**
1282
-     * calc_daynr
1283
-     *
1284
-     * @param 	int 	$year		Year
1285
-     * @param 	int 	$month		Month
1286
-     * @param	int     $day 		Day
1287
-     * @return int Formatted date
1288
-     */
1289
-    private static function calc_daynr($year, $month, $day) {
1290
-        $y = $year;
1291
-        if ($y == 0 && $month == 0) return 0;
1292
-        $num = (365* $y + 31 * ($month - 1) + $day);
1293
-        if ($month <= 2) {
1294
-            $y--; }
1295
-        else {
1296
-            $num -= floor(($month * 4 + 23) / 10);
1297
-        }
1298
-        $temp = floor(($y / 100 + 1) * 3 / 4);
1299
-        return $num + floor($y / 4) - $temp;
1300
-    }
1301
-
1302
-    /**
1303
-     * calc_weekday
1304
-     *
1305
-     * @param int	$daynr							???
1306
-     * @param bool	$sunday_first_day_of_week		???
1307
-     * @return int
1308
-     */
1309
-    private static function calc_weekday($daynr, $sunday_first_day_of_week) {
1310
-      $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
1311
-      return $ret;
1312
-    }
1313
-
1314
-    /**
1315
-     * calc_days_in_year
1316
-     *
1317
-     * @param 	string	$year		Year
1318
-     * @return	int					Nb of days in year
1319
-     */
1320
-    private static function calc_days_in_year($year)
1321
-    {
1322
-      return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1323
-    }
1251
+		return $result;
1252
+	}
1253
+
1254
+	/**
1255
+	 * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
1256
+	 * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
1257
+	 * statique et publique. Le nombre de parametres est determine automatiquement.
1258
+	 *
1259
+	 * @param 	string 	$name 			Le nom de la fonction a definir dans Sqlite
1260
+	 * @param	int		$arg_count		Arg count
1261
+	 * @return	void
1262
+	 */
1263
+	private function addCustomFunction($name, $arg_count = -1)
1264
+	{
1265
+		if ($this->db)
1266
+		{
1267
+			$newname=preg_replace('/_/','',$name);
1268
+			$localname = __CLASS__ . '::' . 'db' . $newname;
1269
+			$reflectClass = new ReflectionClass(__CLASS__);
1270
+			$reflectFunction = $reflectClass->getMethod('db' . $newname);
1271
+			if ($arg_count < 0) {
1272
+				$arg_count = $reflectFunction->getNumberOfParameters();
1273
+			}
1274
+			if (!$this->db->createFunction($name, $localname, $arg_count))
1275
+			{
1276
+				$this->error = "unable to create custom function '$name'";
1277
+			}
1278
+		}
1279
+	}
1280
+
1281
+	/**
1282
+	 * calc_daynr
1283
+	 *
1284
+	 * @param 	int 	$year		Year
1285
+	 * @param 	int 	$month		Month
1286
+	 * @param	int     $day 		Day
1287
+	 * @return int Formatted date
1288
+	 */
1289
+	private static function calc_daynr($year, $month, $day) {
1290
+		$y = $year;
1291
+		if ($y == 0 && $month == 0) return 0;
1292
+		$num = (365* $y + 31 * ($month - 1) + $day);
1293
+		if ($month <= 2) {
1294
+			$y--; }
1295
+		else {
1296
+			$num -= floor(($month * 4 + 23) / 10);
1297
+		}
1298
+		$temp = floor(($y / 100 + 1) * 3 / 4);
1299
+		return $num + floor($y / 4) - $temp;
1300
+	}
1301
+
1302
+	/**
1303
+	 * calc_weekday
1304
+	 *
1305
+	 * @param int	$daynr							???
1306
+	 * @param bool	$sunday_first_day_of_week		???
1307
+	 * @return int
1308
+	 */
1309
+	private static function calc_weekday($daynr, $sunday_first_day_of_week) {
1310
+	  $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
1311
+	  return $ret;
1312
+	}
1313
+
1314
+	/**
1315
+	 * calc_days_in_year
1316
+	 *
1317
+	 * @param 	string	$year		Year
1318
+	 * @return	int					Nb of days in year
1319
+	 */
1320
+	private static function calc_days_in_year($year)
1321
+	{
1322
+	  return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1323
+	}
1324 1324
 
1325 1325
 	/**
1326 1326
 	 * calc_week
@@ -1332,44 +1332,44 @@  discard block
 block discarded – undo
1332 1332
 	 * @param 	string	$calc_year			???
1333 1333
 	 * @return	string						???
1334 1334
 	 */
1335
-    private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1336
-        $daynr=self::calc_daynr($year,$month,$day);
1337
-        $first_daynr=self::calc_daynr($year,1,1);
1338
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1339
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1340
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1341
-
1342
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1343
-        $calc_year=$year;
1344
-
1345
-        if ($month == 1 && $day <= 7-$weekday)
1346
-        {
1347
-            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1348
-                return 0;
1349
-            $week_year= 1;
1350
-            $calc_year--;
1351
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1352
-            $weekday= ($weekday + 53*7- $days) % 7;
1353
-      }
1354
-
1355
-      if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1356
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1357
-      }
1358
-      else {
1359
-        $days= $daynr - ($first_daynr - $weekday);
1360
-      }
1361
-
1362
-      if ($week_year && $days >= 52*7)
1363
-      {
1364
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1365
-        if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1366
-        {
1367
-          $calc_year++;
1368
-          return 1;
1369
-        }
1370
-      }
1371
-      return floor($days/7+1);
1372
-    }
1335
+	private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1336
+		$daynr=self::calc_daynr($year,$month,$day);
1337
+		$first_daynr=self::calc_daynr($year,1,1);
1338
+		$monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1339
+		$week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1340
+		$first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1341
+
1342
+		$weekday=self::calc_weekday($first_daynr, !$monday_first);
1343
+		$calc_year=$year;
1344
+
1345
+		if ($month == 1 && $day <= 7-$weekday)
1346
+		{
1347
+			if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1348
+				return 0;
1349
+			$week_year= 1;
1350
+			$calc_year--;
1351
+			$first_daynr-= ($days=self::calc_days_in_year($calc_year));
1352
+			$weekday= ($weekday + 53*7- $days) % 7;
1353
+	  }
1354
+
1355
+	  if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1356
+		$days= $daynr - ($first_daynr+ (7-$weekday));
1357
+	  }
1358
+	  else {
1359
+		$days= $daynr - ($first_daynr - $weekday);
1360
+	  }
1361
+
1362
+	  if ($week_year && $days >= 52*7)
1363
+	  {
1364
+		$weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1365
+		if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1366
+		{
1367
+		  $calc_year++;
1368
+		  return 1;
1369
+		}
1370
+	  }
1371
+	  return floor($days/7+1);
1372
+	}
1373 1373
 
1374 1374
 }
1375 1375
 
Please login to merge, or discard this patch.
Spacing   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
  *	\brief      Class file to manage Dolibarr database access for a SQLite database
26 26
  */
27 27
 
28
-require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
28
+require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
29 29
 
30 30
 /**
31 31
  *	Class to manage Dolibarr database access for a SQLite database
@@ -33,17 +33,17 @@  discard block
 block discarded – undo
33 33
 class DoliDBSqlite3 extends DoliDB
34 34
 {
35 35
     //! Database type
36
-    public $type='sqlite3';
36
+    public $type = 'sqlite3';
37 37
     //! Database label
38
-    const LABEL='Sqlite3';
38
+    const LABEL = 'Sqlite3';
39 39
     //! Version min database
40
-    const VERSIONMIN='3.0.0';
40
+    const VERSIONMIN = '3.0.0';
41 41
 	/** @var SQLite3Result Resultset of last query */
42 42
 	private $_results;
43 43
 
44
-    const WEEK_MONDAY_FIRST=1;
44
+    const WEEK_MONDAY_FIRST = 1;
45 45
     const WEEK_YEAR = 2;
46
-    const WEEK_FIRST_WEEKDAY=4;
46
+    const WEEK_FIRST_WEEKDAY = 4;
47 47
 
48 48
 
49 49
     /**
@@ -57,19 +57,19 @@  discard block
 block discarded – undo
57 57
 	 *	@param	    string	$name		Nom de la database
58 58
 	 *	@param	    int		$port		Port of database server
59 59
      */
60
-    function __construct($type, $host, $user, $pass, $name='', $port=0)
60
+    function __construct($type, $host, $user, $pass, $name = '', $port = 0)
61 61
     {
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)) $this->forcecharset = $conf->db->character_set;
66
+        if (!empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate = $conf->db->dolibarr_main_db_collation;
67 67
 
68
-        $this->database_user=$user;
69
-        $this->database_host=$host;
70
-        $this->database_port=$port;
68
+        $this->database_user = $user;
69
+        $this->database_host = $host;
70
+        $this->database_port = $port;
71 71
 
72
-        $this->transaction_opened=0;
72
+        $this->transaction_opened = 0;
73 73
 
74 74
         //print "Name DB: $host,$user,$pass,$name<br>";
75 75
 
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
             $this->database_selected = false;
121 121
             $this->database_name = '';
122 122
             //$this->error=sqlite_connect_error();
123
-            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error,LOG_ERR);
123
+            dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error, LOG_ERR);
124 124
         }
125 125
 
126 126
         return $this->ok;
@@ -134,14 +134,14 @@  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')
137
+    static function convertSQLFromMysql($line, $type = 'ddl')
138 138
     {
139 139
         // Removed empty line if this is a comment line for SVN tagging
140
-        if (preg_match('/^--\s\$Id/i',$line)) {
140
+        if (preg_match('/^--\s\$Id/i', $line)) {
141 141
             return '';
142 142
         }
143 143
         // Return line if this is a comment
144
-        if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line))
144
+        if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line))
145 145
         {
146 146
             return $line;
147 147
         }
@@ -149,114 +149,114 @@  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')
158 158
             {
159
-                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
159
+                $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
160 160
 
161 161
                 // we are inside create table statement so lets process datatypes
162
-                if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
163
-                    $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
164
-                    $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
165
-                    $line=preg_replace('/,$/','',$line);
162
+                if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
163
+                    $line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
164
+                    $line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
165
+                    $line = preg_replace('/,$/', '', $line);
166 166
                 }
167 167
 
168 168
                 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
169
-                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
170
-                    $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 integer PRIMARY KEY AUTOINCREMENT',$line);
169
+                if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
170
+                    $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 integer PRIMARY KEY AUTOINCREMENT', $line);
171 171
                     //$line = "-- ".$line." replaced by --\n".$newline;
172
-                    $line=$newline;
172
+                    $line = $newline;
173 173
                 }
174 174
 
175 175
                 // tinyint type conversion
176
-                $line=str_replace('tinyint','smallint',$line);
176
+                $line = str_replace('tinyint', 'smallint', $line);
177 177
 
178 178
                 // nuke unsigned
179
-                $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
179
+                $line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
180 180
 
181 181
                 // blob -> text
182
-                $line=preg_replace('/\w*blob/i','text',$line);
182
+                $line = preg_replace('/\w*blob/i', 'text', $line);
183 183
 
184 184
                 // tinytext/mediumtext -> text
185
-                $line=preg_replace('/tinytext/i','text',$line);
186
-                $line=preg_replace('/mediumtext/i','text',$line);
185
+                $line = preg_replace('/tinytext/i', 'text', $line);
186
+                $line = preg_replace('/mediumtext/i', 'text', $line);
187 187
 
188 188
                 // change not null datetime field to null valid ones
189 189
                 // (to support remapping of "zero time" to null
190
-                $line=preg_replace('/datetime not null/i','datetime',$line);
191
-                $line=preg_replace('/datetime/i','timestamp',$line);
190
+                $line = preg_replace('/datetime not null/i', 'datetime', $line);
191
+                $line = preg_replace('/datetime/i', 'timestamp', $line);
192 192
 
193 193
                 // double -> numeric
194
-                $line=preg_replace('/^double/i','numeric',$line);
195
-                $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
194
+                $line = preg_replace('/^double/i', 'numeric', $line);
195
+                $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
196 196
                 // float -> numeric
197
-                $line=preg_replace('/^float/i','numeric',$line);
198
-                $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
197
+                $line = preg_replace('/^float/i', 'numeric', $line);
198
+                $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
199 199
 
200 200
                 // unique index(field1,field2)
201
-                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
201
+                if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line))
202 202
                 {
203
-                    $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
203
+                    $line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
204 204
                 }
205 205
 
206 206
                 // We remove end of requests "AFTER fieldxxx"
207
-                $line=preg_replace('/AFTER [a-z0-9_]+/i','',$line);
207
+                $line = preg_replace('/AFTER [a-z0-9_]+/i', '', $line);
208 208
 
209 209
                 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
210
-                $line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line);
210
+                $line = preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i', 'DROP INDEX', $line);
211 211
 
212 212
                 // Translate order to rename fields
213
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
213
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg))
214 214
                 {
215 215
                     $line = "-- ".$line." replaced by --\n";
216
-                    $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
216
+                    $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
217 217
                 }
218 218
 
219 219
                 // Translate order to modify field format
220
-                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
220
+                if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg))
221 221
                 {
222 222
                     $line = "-- ".$line." replaced by --\n";
223
-                    $newreg3=$reg[3];
224
-                    $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
225
-                    $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
226
-                    $newreg3=preg_replace('/ NULL/i','',$newreg3);
227
-                    $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
228
-                    $newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3);
229
-                    $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
223
+                    $newreg3 = $reg[3];
224
+                    $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
225
+                    $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
226
+                    $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
227
+                    $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
228
+                    $newreg3 = preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i', '', $newreg3);
229
+                    $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
230 230
                     // TODO Add alter to set default value or null/not null if there is this in $reg[3]
231 231
                 }
232 232
 
233 233
                 // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
234 234
                 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
235
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
235
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg))
236 236
                 {
237 237
                     $line = "-- ".$line." replaced by --\n";
238
-                    $line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
238
+                    $line .= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
239 239
                 }
240 240
 
241 241
                 // Translate order to drop foreign keys
242 242
                 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
243
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
243
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg))
244 244
                 {
245 245
                     $line = "-- ".$line." replaced by --\n";
246
-                    $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
246
+                    $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
247 247
                 }
248 248
 
249 249
                 // alter table add [unique] [index] (field1, field2 ...)
250 250
                 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
251
-                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
251
+                if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg))
252 252
                 {
253
-                    $fieldlist=$reg[4];
254
-                    $idxname=$reg[3];
255
-                    $tablename=$reg[1];
253
+                    $fieldlist = $reg[4];
254
+                    $idxname = $reg[3];
255
+                    $tablename = $reg[1];
256 256
                     $line = "-- ".$line." replaced by --\n";
257
-                    $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
257
+                    $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
258 258
                 }
259
-                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)) {
259
+                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)) {
260 260
                     // Pour l'instant les contraintes ne sont pas créées
261 261
                     dol_syslog(get_class().'::query line emptied');
262 262
                     $line = 'SELECT 0;';
@@ -270,24 +270,24 @@  discard block
 block discarded – undo
270 270
 
271 271
             // Delete using criteria on other table must not declare twice the deleted table
272 272
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
273
-            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
273
+            if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg))
274 274
             {
275 275
 				if ($reg[1] == $reg[2])	// If same table, we remove second one
276 276
                 {
277
-                    $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
277
+                    $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
278 278
                 }
279 279
             }
280 280
 
281 281
             // Remove () in the tables in FROM if one table
282
-            $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line);
282
+            $line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
283 283
             //print $line."\n";
284 284
 
285 285
             // Remove () in the tables in FROM if two table
286
-            $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);
286
+            $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);
287 287
             //print $line."\n";
288 288
 
289 289
             // Remove () in the tables in FROM if two table
290
-            $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);
290
+            $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);
291 291
             //print $line."\n";
292 292
 
293 293
             //print "type=".$type." newline=".$line."<br>\n";
@@ -322,14 +322,14 @@  discard block
 block discarded – undo
322 322
 	 *	@return		SQLite3				Database access handler
323 323
 	 *	@see		close
324 324
      */
325
-    function connect($host, $login, $passwd, $name, $port=0)
325
+    function connect($host, $login, $passwd, $name, $port = 0)
326 326
     {
327 327
         global $main_data_dir;
328 328
 
329
-        dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
329
+        dol_syslog(get_class($this)."::connect name=".$name, LOG_DEBUG);
330 330
 
331
-        $dir=$main_data_dir;
332
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
331
+        $dir = $main_data_dir;
332
+        if (empty($dir)) $dir = DOL_DATA_ROOT;
333 333
         // With sqlite, port must be in connect parameters
334 334
         //if (! $newport) $newport=3306;
335 335
         $database_name = $dir.'/database_'.$name.'.sdb';
@@ -339,9 +339,9 @@  discard block
 block discarded – undo
339 339
 			$this->db = new SQLite3($database_name);
340 340
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
341 341
         }
342
-        catch(Exception $e)
342
+        catch (Exception $e)
343 343
         {
344
-            $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
344
+            $this->error = self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
345 345
             return '';
346 346
         }
347 347
 
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
      */
358 358
     function getVersion()
359 359
     {
360
-    	$tmp=$this->db->version();
360
+    	$tmp = $this->db->version();
361 361
         return $tmp['versionString'];
362 362
     }
363 363
 
@@ -382,10 +382,10 @@  discard block
 block discarded – undo
382 382
     {
383 383
         if ($this->db)
384 384
         {
385
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
386
-            $this->connected=false;
385
+            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
386
+            $this->connected = false;
387 387
             $this->db->close();
388
-            unset($this->db);    // Clean this->db
388
+            unset($this->db); // Clean this->db
389 389
             return true;
390 390
         }
391 391
         return false;
@@ -400,14 +400,14 @@  discard block
 block discarded – undo
400 400
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
401 401
      *	@return	SQLite3Result			Resultset of answer
402 402
      */
403
-    function query($query,$usesavepoint=0,$type='auto')
403
+    function query($query, $usesavepoint = 0, $type = 'auto')
404 404
     {
405
-        $ret=null;
405
+        $ret = null;
406 406
         $query = trim($query);
407 407
         $this->error = 0;
408 408
 
409 409
         // Convert MySQL syntax to SQLite syntax
410
-        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)) {
410
+        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)) {
411 411
             // Ajout d'une clef étrangère à la table
412 412
             // procédure de remplacement de la table pour ajouter la contrainte
413 413
             // Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
@@ -415,19 +415,19 @@  discard block
 block discarded – undo
415 415
             $foreignFields = $reg[5];
416 416
             $foreignTable = $reg[4];
417 417
             $localfields = $reg[3];
418
-            $constraintname=trim($reg[2]);
419
-            $tablename=trim($reg[1]);
418
+            $constraintname = trim($reg[2]);
419
+            $tablename = trim($reg[1]);
420 420
 
421
-            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='" . $tablename . "'");
421
+            $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='".$tablename."'");
422 422
 
423 423
             // 1- Renommer la table avec un nom temporaire
424
-            $this->query('ALTER TABLE ' . $tablename . ' RENAME TO tmp_' . $tablename);
424
+            $this->query('ALTER TABLE '.$tablename.' RENAME TO tmp_'.$tablename);
425 425
 
426 426
             // 2- Recréer la table avec la contrainte ajoutée
427 427
 
428 428
             // on bricole la requete pour ajouter la contrainte
429 429
             $descTable = substr($descTable, 0, strlen($descTable) - 1);
430
-            $descTable .= ", CONSTRAINT " . $constraintname . " FOREIGN KEY (" . $localfields . ") REFERENCES " .$foreignTable . "(" . $foreignFields . ")";
430
+            $descTable .= ", CONSTRAINT ".$constraintname." FOREIGN KEY (".$localfields.") REFERENCES ".$foreignTable."(".$foreignFields.")";
431 431
 
432 432
             // fermeture de l'instruction
433 433
             $descTable .= ')';
@@ -436,16 +436,16 @@  discard block
 block discarded – undo
436 436
             $this->query($descTable);
437 437
 
438 438
             // 3- Transférer les données
439
-            $this->query('INSERT INTO ' . $tablename . ' SELECT * FROM tmp_' . $tablename);
439
+            $this->query('INSERT INTO '.$tablename.' SELECT * FROM tmp_'.$tablename);
440 440
 
441 441
             // 4- Supprimer la table temporaire
442
-            $this->query('DROP TABLE tmp_' . $tablename);
442
+            $this->query('DROP TABLE tmp_'.$tablename);
443 443
 
444 444
             // dummy statement
445
-            $query="SELECT 0";
445
+            $query = "SELECT 0";
446 446
 
447 447
         } else {
448
-            $query=$this->convertSQLFromMysql($query,$type);
448
+            $query = $this->convertSQLFromMysql($query, $type);
449 449
         }
450 450
         //print "After convertSQLFromMysql:\n".$query."<br>\n";
451 451
 
@@ -454,20 +454,20 @@  discard block
 block discarded – undo
454 454
         // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
455 455
         try {
456 456
             //$ret = $this->db->exec($query);
457
-            $ret = $this->db->query($query);        // $ret is a Sqlite3Result
457
+            $ret = $this->db->query($query); // $ret is a Sqlite3Result
458 458
             if ($ret) {
459 459
                 $ret->queryString = $query;
460 460
             }
461 461
         }
462
-        catch(Exception $e)
462
+        catch (Exception $e)
463 463
         {
464
-            $this->error=$this->db->lastErrorMsg();
464
+            $this->error = $this->db->lastErrorMsg();
465 465
         }
466 466
 
467
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
467
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
468 468
         {
469 469
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
470
-            if (! is_object($ret) || $this->error)
470
+            if (!is_object($ret) || $this->error)
471 471
             {
472 472
                 $this->lastqueryerror = $query;
473 473
                 $this->lasterror = $this->error();
@@ -477,13 +477,13 @@  discard block
 block discarded – undo
477 477
 
478 478
                 $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
479 479
 
480
-                if (preg_match('/[0-9]/',$this->lasterrno)) {
480
+                if (preg_match('/[0-9]/', $this->lasterrno)) {
481 481
                     $errormsg .= ' ('.$this->lasterrno.')';
482 482
                 }
483 483
 
484 484
                 dol_syslog($errormsg, LOG_ERR);
485 485
             }
486
-            $this->lastquery=$query;
486
+            $this->lastquery = $query;
487 487
             $this->_results = $ret;
488 488
         }
489 489
 
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
     function fetch_object($resultset)
500 500
     {
501 501
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
502
-        if (! is_object($resultset)) { $resultset=$this->_results; }
502
+        if (!is_object($resultset)) { $resultset = $this->_results; }
503 503
         //return $resultset->fetch(PDO::FETCH_OBJ);
504 504
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
505 505
         if ($ret) {
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
     function fetch_array($resultset)
519 519
     {
520 520
         // If resultset not provided, we take the last used by connexion
521
-        if (! is_object($resultset)) { $resultset=$this->_results; }
521
+        if (!is_object($resultset)) { $resultset = $this->_results; }
522 522
         //return $resultset->fetch(PDO::FETCH_ASSOC);
523 523
         $ret = $resultset->fetchArray(SQLITE3_ASSOC);
524 524
 	    return $ret;
@@ -533,9 +533,9 @@  discard block
 block discarded – undo
533 533
     function fetch_row($resultset)
534 534
     {
535 535
         // If resultset not provided, we take the last used by connexion
536
-        if (! is_bool($resultset))
536
+        if (!is_bool($resultset))
537 537
         {
538
-            if (! is_object($resultset)) { $resultset=$this->_results; }
538
+            if (!is_object($resultset)) { $resultset = $this->_results; }
539 539
             return $resultset->fetchArray(SQLITE3_NUM);
540 540
         }
541 541
         else
@@ -557,9 +557,9 @@  discard block
 block discarded – undo
557 557
 	    // FIXME: SQLite3Result does not have a queryString member
558 558
 
559 559
         // If resultset not provided, we take the last used by connexion
560
-        if (! is_object($resultset)) { $resultset=$this->_results; }
560
+        if (!is_object($resultset)) { $resultset = $this->_results; }
561 561
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
562
-            return $this->db->querySingle("SELECT count(*) FROM (" . $resultset->queryString . ") q");
562
+            return $this->db->querySingle("SELECT count(*) FROM (".$resultset->queryString.") q");
563 563
         }
564 564
         return 0;
565 565
     }
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 	    // FIXME: SQLite3Result does not have a queryString member
577 577
 
578 578
         // If resultset not provided, we take the last used by connexion
579
-        if (! is_object($resultset)) { $resultset=$this->_results; }
579
+        if (!is_object($resultset)) { $resultset = $this->_results; }
580 580
         if (preg_match("/^SELECT/i", $resultset->queryString)) {
581 581
             return $this->num_rows($resultset);
582 582
         }
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
 	 *	@param  SQLite3Result	$resultset   Curseur de la requete voulue
593 593
 	 *	@return	void
594 594
      */
595
-    function free($resultset=null)
595
+    function free($resultset = null)
596 596
     {
597 597
         // If resultset not provided, we take the last used by connexion
598
-        if (! is_object($resultset)) { $resultset=$this->_results; }
598
+        if (!is_object($resultset)) { $resultset = $this->_results; }
599 599
         // Si resultset en est un, on libere la memoire
600 600
         if ($resultset && is_object($resultset)) $resultset->finalize();
601 601
     }
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
      */
619 619
     function errno()
620 620
     {
621
-        if (! $this->connected) {
621
+        if (!$this->connected) {
622 622
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
623 623
             return 'DB_ERROR_FAILED_TO_CONNECT';
624 624
         }
@@ -656,23 +656,23 @@  discard block
 block discarded – undo
656 656
             {
657 657
                 return $errorcode_map[$this->db->errorCode()];
658 658
             }*/
659
-            $errno=$this->db->lastErrorCode();
660
-			if ($errno=='HY000' || $errno == 0)
659
+            $errno = $this->db->lastErrorCode();
660
+			if ($errno == 'HY000' || $errno == 0)
661 661
             {
662
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
663
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
664
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
662
+                if (preg_match('/table.*already exists/i', $this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
663
+                elseif (preg_match('/index.*already exists/i', $this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
664
+                elseif (preg_match('/syntax error/i', $this->error))          return 'DB_ERROR_SYNTAX';
665 665
             }
666
-            if ($errno=='23000')
666
+            if ($errno == '23000')
667 667
             {
668
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
669
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
668
+                if (preg_match('/column.* not unique/i', $this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
669
+                elseif (preg_match('/PRIMARY KEY must be unique/i', $this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
670 670
             }
671 671
             if ($errno > 1) {
672 672
                 // TODO Voir la liste des messages d'erreur
673 673
             }
674 674
 
675
-            return ($errno?'DB_ERROR_'.$errno:'0');
675
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
676 676
         }
677 677
     }
678 678
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
      */
684 684
     function error()
685 685
     {
686
-        if (! $this->connected) {
686
+        if (!$this->connected) {
687 687
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
688 688
             return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
689 689
         }
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 	 * @param	string	$fieldid	Field name
700 700
 	 * @return  int     			Id of row
701 701
      */
702
-    function last_insert_id($tab,$fieldid='rowid')
702
+    function last_insert_id($tab, $fieldid = 'rowid')
703 703
     {
704 704
         return $this->db->lastInsertRowId();
705 705
     }
@@ -712,17 +712,17 @@  discard block
 block discarded – undo
712 712
      *  @param	int		$withQuotes     Return string with quotes
713 713
      *  @return string          		XXX(field) or XXX('value') or field or 'value'
714 714
      */
715
-    function encrypt($fieldorvalue, $withQuotes=0)
715
+    function encrypt($fieldorvalue, $withQuotes = 0)
716 716
     {
717 717
         global $conf;
718 718
 
719 719
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
720
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
720
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
721 721
 
722 722
         //Encryption key
723
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
723
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
724 724
 
725
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
725
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
726 726
 
727 727
         if ($cryptType && !empty($cryptKey))
728 728
         {
@@ -750,10 +750,10 @@  discard block
 block discarded – undo
750 750
         global $conf;
751 751
 
752 752
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
753
-        $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
753
+        $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
754 754
 
755 755
         //Encryption key
756
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
756
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
757 757
 
758 758
         $return = $value;
759 759
 
@@ -795,23 +795,23 @@  discard block
 block discarded – undo
795 795
 	 * 	@param	string	$owner			Username of database owner
796 796
 	 * 	@return	SQLite3Result   		resource defined if OK, null if KO
797 797
      */
798
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
798
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
799 799
     {
800
-        if (empty($charset))   $charset=$this->forcecharset;
801
-        if (empty($collation)) $collation=$this->forcecollate;
800
+        if (empty($charset))   $charset = $this->forcecharset;
801
+        if (empty($collation)) $collation = $this->forcecollate;
802 802
 
803 803
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
804 804
         $sql = 'CREATE DATABASE '.$database;
805
-        $sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
805
+        $sql .= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
806 806
 
807
-        dol_syslog($sql,LOG_DEBUG);
808
-        $ret=$this->query($sql);
809
-        if (! $ret)
807
+        dol_syslog($sql, LOG_DEBUG);
808
+        $ret = $this->query($sql);
809
+        if (!$ret)
810 810
         {
811 811
             // We try again for compatibility with Mysql < 4.1.1
812 812
             $sql = 'CREATE DATABASE '.$database;
813
-            $ret=$this->query($sql);
814
-            dol_syslog($sql,LOG_DEBUG);
813
+            $ret = $this->query($sql);
814
+            dol_syslog($sql, LOG_DEBUG);
815 815
         }
816 816
         return $ret;
817 817
     }
@@ -823,18 +823,18 @@  discard block
 block discarded – undo
823 823
 	 *  @param	string		$table		Name of table filter ('xxx%')
824 824
 	 *  @return	array					List of tables in an array
825 825
      */
826
-    function DDLListTables($database, $table='')
826
+    function DDLListTables($database, $table = '')
827 827
     {
828
-        $listtables=array();
828
+        $listtables = array();
829 829
 
830 830
         $like = '';
831 831
         if ($table) $like = "LIKE '".$table."'";
832
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
832
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
833 833
         //print $sql;
834 834
         $result = $this->query($sql);
835 835
         if ($result)
836 836
         {
837
-            while($row = $this->fetch_row($result))
837
+            while ($row = $this->fetch_row($result))
838 838
             {
839 839
                 $listtables[] = $row[0];
840 840
             }
@@ -851,15 +851,15 @@  discard block
 block discarded – undo
851 851
      */
852 852
     function DDLInfoTable($table)
853 853
     {
854
-        $infotables=array();
854
+        $infotables = array();
855 855
 
856
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
856
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
857 857
 
858
-        dol_syslog($sql,LOG_DEBUG);
858
+        dol_syslog($sql, LOG_DEBUG);
859 859
         $result = $this->query($sql);
860 860
         if ($result)
861 861
         {
862
-            while($row = $this->fetch_row($result))
862
+            while ($row = $this->fetch_row($result))
863 863
             {
864 864
                 $infotables[] = $row;
865 865
             }
@@ -879,68 +879,68 @@  discard block
 block discarded – undo
879 879
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
880 880
 	 *	@return	    int						<0 if KO, >=0 if OK
881 881
      */
882
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
882
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
883 883
     {
884 884
 	    // FIXME: $fulltext_keys parameter is unused
885 885
 
886 886
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
887 887
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
888 888
         $sql = "create table ".$table."(";
889
-        $i=0;
890
-        foreach($fields as $field_name => $field_desc)
889
+        $i = 0;
890
+        foreach ($fields as $field_name => $field_desc)
891 891
         {
892 892
             $sqlfields[$i] = $field_name." ";
893 893
             $sqlfields[$i]  .= $field_desc['type'];
894
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
894
+            if (preg_match("/^[^\s]/i", $field_desc['value']))
895 895
             $sqlfields[$i]  .= "(".$field_desc['value'].")";
896
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
896
+            else if (preg_match("/^[^\s]/i", $field_desc['attribute']))
897 897
             $sqlfields[$i]  .= " ".$field_desc['attribute'];
898
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
898
+            else if (preg_match("/^[^\s]/i", $field_desc['default']))
899 899
             {
900
-                if(preg_match("/null/i",$field_desc['default']))
900
+                if (preg_match("/null/i", $field_desc['default']))
901 901
                 $sqlfields[$i]  .= " default ".$field_desc['default'];
902 902
                 else
903 903
                 $sqlfields[$i]  .= " default '".$field_desc['default']."'";
904 904
             }
905
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
905
+            else if (preg_match("/^[^\s]/i", $field_desc['null']))
906 906
             $sqlfields[$i]  .= " ".$field_desc['null'];
907 907
 
908
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
908
+            else if (preg_match("/^[^\s]/i", $field_desc['extra']))
909 909
             $sqlfields[$i]  .= " ".$field_desc['extra'];
910 910
             $i++;
911 911
         }
912
-        if($primary_key != "")
912
+        if ($primary_key != "")
913 913
         $pk = "primary key(".$primary_key.")";
914 914
 
915
-        if(is_array($unique_keys))
915
+        if (is_array($unique_keys))
916 916
         {
917 917
             $i = 0;
918
-            foreach($unique_keys as $key => $value)
918
+            foreach ($unique_keys as $key => $value)
919 919
             {
920 920
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
921 921
                 $i++;
922 922
             }
923 923
         }
924
-        if(is_array($keys))
924
+        if (is_array($keys))
925 925
         {
926 926
             $i = 0;
927
-            foreach($keys as $key => $value)
927
+            foreach ($keys as $key => $value)
928 928
             {
929 929
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
930 930
                 $i++;
931 931
             }
932 932
         }
933
-        $sql .= implode(',',$sqlfields);
934
-        if($primary_key != "")
933
+        $sql .= implode(',', $sqlfields);
934
+        if ($primary_key != "")
935 935
         $sql .= ",".$pk;
936
-        if(is_array($unique_keys))
937
-        $sql .= ",".implode(',',$sqluq);
938
-        if(is_array($keys))
939
-        $sql .= ",".implode(',',$sqlk);
940
-        $sql .=") type=".$type;
941
-
942
-        dol_syslog($sql,LOG_DEBUG);
943
-        if(! $this -> query($sql))
936
+        if (is_array($unique_keys))
937
+        $sql .= ",".implode(',', $sqluq);
938
+        if (is_array($keys))
939
+        $sql .= ",".implode(',', $sqlk);
940
+        $sql .= ") type=".$type;
941
+
942
+        dol_syslog($sql, LOG_DEBUG);
943
+        if (!$this -> query($sql))
944 944
             return -1;
945 945
         return 1;
946 946
     }
@@ -952,11 +952,11 @@  discard block
 block discarded – undo
952 952
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
953 953
 	 *	@return	SQLite3Result		Resource
954 954
      */
955
-    function DDLDescTable($table,$field="")
955
+    function DDLDescTable($table, $field = "")
956 956
     {
957
-        $sql="DESC ".$table." ".$field;
957
+        $sql = "DESC ".$table." ".$field;
958 958
 
959
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
959
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
960 960
         $this->_results = $this->query($sql);
961 961
         return $this->_results;
962 962
     }
@@ -970,34 +970,34 @@  discard block
 block discarded – undo
970 970
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
971 971
 	 *	@return	int							<0 if KO, >0 if OK
972 972
      */
973
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
973
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
974 974
     {
975 975
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
976 976
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
977
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
978
-        $sql.= $field_desc['type'];
979
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
980
-        if (! in_array($field_desc['type'],array('date','datetime')))
977
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
978
+        $sql .= $field_desc['type'];
979
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
980
+        if (!in_array($field_desc['type'], array('date', 'datetime')))
981 981
         {
982
-            $sql.= "(".$field_desc['value'].")";
982
+            $sql .= "(".$field_desc['value'].")";
983 983
         }
984
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
985
-        $sql.= " ".$field_desc['attribute'];
986
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
987
-        $sql.= " ".$field_desc['null'];
988
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
984
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
985
+        $sql .= " ".$field_desc['attribute'];
986
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
987
+        $sql .= " ".$field_desc['null'];
988
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
989 989
         {
990
-            if(preg_match("/null/i",$field_desc['default']))
991
-            $sql.= " default ".$field_desc['default'];
990
+            if (preg_match("/null/i", $field_desc['default']))
991
+            $sql .= " default ".$field_desc['default'];
992 992
             else
993
-            $sql.= " default '".$field_desc['default']."'";
993
+            $sql .= " default '".$field_desc['default']."'";
994 994
         }
995
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
996
-        $sql.= " ".$field_desc['extra'];
997
-        $sql.= " ".$field_position;
995
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
996
+        $sql .= " ".$field_desc['extra'];
997
+        $sql .= " ".$field_position;
998 998
 
999
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1000
-        if(! $this->query($sql))
999
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1000
+        if (!$this->query($sql))
1001 1001
         {
1002 1002
             return -1;
1003 1003
         }
@@ -1012,16 +1012,16 @@  discard block
 block discarded – undo
1012 1012
 	 *	@param	string	$field_desc 		Array with description of field format
1013 1013
 	 *	@return	int							<0 if KO, >0 if OK
1014 1014
      */
1015
-    function DDLUpdateField($table,$field_name,$field_desc)
1015
+    function DDLUpdateField($table, $field_name, $field_desc)
1016 1016
     {
1017 1017
         $sql = "ALTER TABLE ".$table;
1018 1018
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1019 1019
         if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1020
-            $sql.="(".$field_desc['value'].")";
1020
+            $sql .= "(".$field_desc['value'].")";
1021 1021
         }
1022 1022
 
1023
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1024
-        if (! $this->query($sql))
1023
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1024
+        if (!$this->query($sql))
1025 1025
             return -1;
1026 1026
         return 1;
1027 1027
     }
@@ -1033,13 +1033,13 @@  discard block
 block discarded – undo
1033 1033
 	 *	@param	string	$field_name 	Name of field to drop
1034 1034
 	 *	@return	int						<0 if KO, >0 if OK
1035 1035
      */
1036
-    function DDLDropField($table,$field_name)
1036
+    function DDLDropField($table, $field_name)
1037 1037
     {
1038
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1039
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1040
-        if (! $this->query($sql))
1038
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1039
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
1040
+        if (!$this->query($sql))
1041 1041
         {
1042
-            $this->error=$this->lasterror();
1042
+            $this->error = $this->lasterror();
1043 1043
             return -1;
1044 1044
         }
1045 1045
         return 1;
@@ -1055,37 +1055,37 @@  discard block
 block discarded – undo
1055 1055
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1056 1056
 	 *	@return	int									<0 if KO, >=0 if OK
1057 1057
      */
1058
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1058
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1059 1059
     {
1060 1060
         $sql = "INSERT INTO user ";
1061
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1062
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1063
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1061
+        $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1062
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1063
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1064 1064
 
1065
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1066
-        $resql=$this->query($sql);
1067
-        if (! $resql)
1065
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1066
+        $resql = $this->query($sql);
1067
+        if (!$resql)
1068 1068
         {
1069 1069
             return -1;
1070 1070
         }
1071 1071
 
1072 1072
         $sql = "INSERT INTO db ";
1073
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1074
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1075
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1073
+        $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1074
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1075
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1076 1076
 
1077 1077
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1078
-        $resql=$this->query($sql);
1079
-        if (! $resql)
1078
+        $resql = $this->query($sql);
1079
+        if (!$resql)
1080 1080
         {
1081 1081
             return -1;
1082 1082
         }
1083 1083
 
1084
-        $sql="FLUSH Privileges";
1084
+        $sql = "FLUSH Privileges";
1085 1085
 
1086 1086
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1087
-        $resql=$this->query($sql);
1088
-        if (! $resql)
1087
+        $resql = $this->query($sql);
1088
+        if (!$resql)
1089 1089
         {
1090 1090
             return -1;
1091 1091
         }
@@ -1110,7 +1110,7 @@  discard block
 block discarded – undo
1110 1110
     function getListOfCharacterSet()
1111 1111
     {
1112 1112
         $liste = array();
1113
-        $i=0;
1113
+        $i = 0;
1114 1114
         $liste[$i]['charset'] = 'UTF-8';
1115 1115
         $liste[$i]['description'] = 'UTF-8';
1116 1116
         return $liste;
@@ -1134,7 +1134,7 @@  discard block
 block discarded – undo
1134 1134
     function getListOfCollation()
1135 1135
     {
1136 1136
         $liste = array();
1137
-        $i=0;
1137
+        $i = 0;
1138 1138
         $liste[$i]['charset'] = 'UTF-8';
1139 1139
         $liste[$i]['description'] = 'UTF-8';
1140 1140
         return $liste;
@@ -1148,14 +1148,14 @@  discard block
 block discarded – undo
1148 1148
     function getPathOfDump()
1149 1149
     {
1150 1150
 	    // FIXME: not for SQLite
1151
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1151
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1152 1152
 
1153
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1153
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1154 1154
         if ($resql)
1155 1155
         {
1156
-            $liste=$this->fetch_array($resql);
1157
-            $basedir=$liste['Value'];
1158
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1156
+            $liste = $this->fetch_array($resql);
1157
+            $basedir = $liste['Value'];
1158
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1159 1159
         }
1160 1160
         return $fullpathofdump;
1161 1161
     }
@@ -1168,14 +1168,14 @@  discard block
 block discarded – undo
1168 1168
     function getPathOfRestore()
1169 1169
     {
1170 1170
 	    // FIXME: not for SQLite
1171
-        $fullpathofimport='/pathtomysql/mysql';
1171
+        $fullpathofimport = '/pathtomysql/mysql';
1172 1172
 
1173
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1173
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1174 1174
         if ($resql)
1175 1175
         {
1176
-            $liste=$this->fetch_array($resql);
1177
-            $basedir=$liste['Value'];
1178
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1176
+            $liste = $this->fetch_array($resql);
1177
+            $basedir = $liste['Value'];
1178
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1179 1179
         }
1180 1180
         return $fullpathofimport;
1181 1181
     }
@@ -1186,18 +1186,18 @@  discard block
 block discarded – undo
1186 1186
 	 * @param	string	$filter		Filter list on a particular value
1187 1187
 	 * @return	array				Array of key-values (key=>value)
1188 1188
      */
1189
-    function getServerParametersValues($filter='')
1189
+    function getServerParametersValues($filter = '')
1190 1190
     {
1191
-        $result=array();
1191
+        $result = array();
1192 1192
         static $pragmas;
1193
-        if (! isset($pragmas)) {
1193
+        if (!isset($pragmas)) {
1194 1194
             // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1195 1195
             // indépendante de la base de données.
1196 1196
             // cf. http://www.sqlite.org/pragma.html
1197 1197
             $pragmas = array(
1198 1198
                 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1199 1199
                 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1200
-				'compile_options', 'data_version',	/*'database_list',*/
1200
+				'compile_options', 'data_version', /*'database_list',*/
1201 1201
                 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1202 1202
                 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1203 1203
                 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
@@ -1212,9 +1212,9 @@  discard block
 block discarded – undo
1212 1212
         }
1213 1213
 
1214 1214
         // TODO prendre en compte le filtre
1215
-        foreach($pragmas as $var) {
1215
+        foreach ($pragmas as $var) {
1216 1216
             $sql = "PRAGMA $var";
1217
-            $resql=$this->query($sql);
1217
+            $resql = $this->query($sql);
1218 1218
             if ($resql)
1219 1219
             {
1220 1220
                 $obj = $this->fetch_row($resql);
@@ -1235,9 +1235,9 @@  discard block
 block discarded – undo
1235 1235
 	 * @param	string	$filter		Filter list on a particular value
1236 1236
 	 * @return  array				Array of key-values (key=>value)
1237 1237
      */
1238
-    function getServerStatusValues($filter='')
1238
+    function getServerStatusValues($filter = '')
1239 1239
     {
1240
-        $result=array();
1240
+        $result = array();
1241 1241
         /*
1242 1242
         $sql='SHOW STATUS';
1243 1243
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
@@ -1264,10 +1264,10 @@  discard block
 block discarded – undo
1264 1264
     {
1265 1265
         if ($this->db)
1266 1266
         {
1267
-        	$newname=preg_replace('/_/','',$name);
1268
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1267
+        	$newname = preg_replace('/_/', '', $name);
1268
+            $localname = __CLASS__.'::'.'db'.$newname;
1269 1269
             $reflectClass = new ReflectionClass(__CLASS__);
1270
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1270
+            $reflectFunction = $reflectClass->getMethod('db'.$newname);
1271 1271
             if ($arg_count < 0) {
1272 1272
                 $arg_count = $reflectFunction->getNumberOfParameters();
1273 1273
             }
@@ -1289,7 +1289,7 @@  discard block
 block discarded – undo
1289 1289
     private static function calc_daynr($year, $month, $day) {
1290 1290
         $y = $year;
1291 1291
         if ($y == 0 && $month == 0) return 0;
1292
-        $num = (365* $y + 31 * ($month - 1) + $day);
1292
+        $num = (365 * $y + 31 * ($month - 1) + $day);
1293 1293
         if ($month <= 2) {
1294 1294
             $y--; }
1295 1295
         else {
@@ -1319,7 +1319,7 @@  discard block
 block discarded – undo
1319 1319
      */
1320 1320
     private static function calc_days_in_year($year)
1321 1321
     {
1322
-      return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1322
+      return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
1323 1323
     }
1324 1324
 
1325 1325
 	/**
@@ -1333,42 +1333,42 @@  discard block
 block discarded – undo
1333 1333
 	 * @return	string						???
1334 1334
 	 */
1335 1335
     private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1336
-        $daynr=self::calc_daynr($year,$month,$day);
1337
-        $first_daynr=self::calc_daynr($year,1,1);
1338
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1339
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1340
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1336
+        $daynr = self::calc_daynr($year, $month, $day);
1337
+        $first_daynr = self::calc_daynr($year, 1, 1);
1338
+        $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1339
+        $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1340
+        $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1341 1341
 
1342
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1343
-        $calc_year=$year;
1342
+        $weekday = self::calc_weekday($first_daynr, !$monday_first);
1343
+        $calc_year = $year;
1344 1344
 
1345
-        if ($month == 1 && $day <= 7-$weekday)
1345
+        if ($month == 1 && $day <= 7 - $weekday)
1346 1346
         {
1347 1347
             if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1348 1348
                 return 0;
1349
-            $week_year= 1;
1349
+            $week_year = 1;
1350 1350
             $calc_year--;
1351
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1352
-            $weekday= ($weekday + 53*7- $days) % 7;
1351
+            $first_daynr -= ($days = self::calc_days_in_year($calc_year));
1352
+            $weekday = ($weekday + 53 * 7 - $days) % 7;
1353 1353
       }
1354 1354
 
1355 1355
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1356
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1356
+        $days = $daynr - ($first_daynr + (7 - $weekday));
1357 1357
       }
1358 1358
       else {
1359
-        $days= $daynr - ($first_daynr - $weekday);
1359
+        $days = $daynr - ($first_daynr - $weekday);
1360 1360
       }
1361 1361
 
1362
-      if ($week_year && $days >= 52*7)
1362
+      if ($week_year && $days >= 52 * 7)
1363 1363
       {
1364
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1364
+        $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
1365 1365
         if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1366 1366
         {
1367 1367
           $calc_year++;
1368 1368
           return 1;
1369 1369
         }
1370 1370
       }
1371
-      return floor($days/7+1);
1371
+      return floor($days / 7 + 1);
1372 1372
     }
1373 1373
 
1374 1374
 }
Please login to merge, or discard this patch.
Braces   +112 added lines, -80 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')
@@ -272,9 +279,11 @@  discard block
 block discarded – undo
272 279
             // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
273 280
             if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
274 281
             {
275
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
282
+				if ($reg[1] == $reg[2]) {
283
+					// If same table, we remove second one
276 284
                 {
277 285
                     $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
286
+				}
278 287
                 }
279 288
             }
280 289
 
@@ -329,7 +338,9 @@  discard block
 block discarded – undo
329 338
         dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG);
330 339
 
331 340
         $dir=$main_data_dir;
332
-        if (empty($dir)) $dir=DOL_DATA_ROOT;
341
+        if (empty($dir)) {
342
+        	$dir=DOL_DATA_ROOT;
343
+        }
333 344
         // With sqlite, port must be in connect parameters
334 345
         //if (! $newport) $newport=3306;
335 346
         $database_name = $dir.'/database_'.$name.'.sdb';
@@ -338,8 +349,7 @@  discard block
 block discarded – undo
338 349
             //$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
339 350
 			$this->db = new SQLite3($database_name);
340 351
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
341
-        }
342
-        catch(Exception $e)
352
+        } catch(Exception $e)
343 353
         {
344 354
             $this->error=  self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
345 355
             return '';
@@ -382,7 +392,9 @@  discard block
 block discarded – undo
382 392
     {
383 393
         if ($this->db)
384 394
         {
385
-            if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
395
+            if ($this->transaction_opened > 0) {
396
+            	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
397
+            }
386 398
             $this->connected=false;
387 399
             $this->db->close();
388 400
             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
         }
@@ -537,8 +548,7 @@  discard block
 block discarded – undo
537 548
         {
538 549
             if (! is_object($resultset)) { $resultset=$this->_results; }
539 550
             return $resultset->fetchArray(SQLITE3_NUM);
540
-        }
541
-        else
551
+        } else
542 552
         {
543 553
             // si le curseur est un booleen on retourne la valeur 0
544 554
             return false;
@@ -597,7 +607,9 @@  discard block
 block discarded – undo
597 607
         // If resultset not provided, we take the last used by connexion
598 608
         if (! is_object($resultset)) { $resultset=$this->_results; }
599 609
         // Si resultset en est un, on libere la memoire
600
-        if ($resultset && is_object($resultset)) $resultset->finalize();
610
+        if ($resultset && is_object($resultset)) {
611
+        	$resultset->finalize();
612
+        }
601 613
     }
602 614
 
603 615
     /**
@@ -621,8 +633,7 @@  discard block
 block discarded – undo
621 633
         if (! $this->connected) {
622 634
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
623 635
             return 'DB_ERROR_FAILED_TO_CONNECT';
624
-        }
625
-        else {
636
+        } else {
626 637
             // Constants to convert error code to a generic Dolibarr error code
627 638
             /*$errorcode_map = array(
628 639
             1004 => 'DB_ERROR_CANNOT_CREATE',
@@ -659,14 +670,21 @@  discard block
 block discarded – undo
659 670
             $errno=$this->db->lastErrorCode();
660 671
 			if ($errno=='HY000' || $errno == 0)
661 672
             {
662
-                if (preg_match('/table.*already exists/i',$this->error))     return 'DB_ERROR_TABLE_ALREADY_EXISTS';
663
-                elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
664
-                elseif (preg_match('/syntax error/i',$this->error))          return 'DB_ERROR_SYNTAX';
673
+                if (preg_match('/table.*already exists/i',$this->error)) {
674
+                	return 'DB_ERROR_TABLE_ALREADY_EXISTS';
675
+                } elseif (preg_match('/index.*already exists/i',$this->error)) {
676
+                	return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
677
+                } elseif (preg_match('/syntax error/i',$this->error)) {
678
+                	return 'DB_ERROR_SYNTAX';
679
+                }
665 680
             }
666 681
             if ($errno=='23000')
667 682
             {
668
-                if (preg_match('/column.* not unique/i',$this->error))       return 'DB_ERROR_RECORD_ALREADY_EXISTS';
669
-                elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS';
683
+                if (preg_match('/column.* not unique/i',$this->error)) {
684
+                	return 'DB_ERROR_RECORD_ALREADY_EXISTS';
685
+                } elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) {
686
+                	return 'DB_ERROR_RECORD_ALREADY_EXISTS';
687
+                }
670 688
             }
671 689
             if ($errno > 1) {
672 690
                 // TODO Voir la liste des messages d'erreur
@@ -686,8 +704,7 @@  discard block
 block discarded – undo
686 704
         if (! $this->connected) {
687 705
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
688 706
             return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
689
-        }
690
-        else {
707
+        } else {
691 708
             return $this->error;
692 709
         }
693 710
     }
@@ -729,8 +746,7 @@  discard block
 block discarded – undo
729 746
             if ($cryptType == 2)
730 747
             {
731 748
                 $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
732
-            }
733
-            else if ($cryptType == 1)
749
+            } else if ($cryptType == 1)
734 750
             {
735 751
                 $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
736 752
             }
@@ -762,8 +778,7 @@  discard block
 block discarded – undo
762 778
             if ($cryptType == 2)
763 779
             {
764 780
                 $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
765
-            }
766
-            else if ($cryptType == 1)
781
+            } else if ($cryptType == 1)
767 782
             {
768 783
                 $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
769 784
             }
@@ -797,8 +812,12 @@  discard block
 block discarded – undo
797 812
      */
798 813
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
799 814
     {
800
-        if (empty($charset))   $charset=$this->forcecharset;
801
-        if (empty($collation)) $collation=$this->forcecollate;
815
+        if (empty($charset)) {
816
+        	$charset=$this->forcecharset;
817
+        }
818
+        if (empty($collation)) {
819
+        	$collation=$this->forcecollate;
820
+        }
802 821
 
803 822
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
804 823
         $sql = 'CREATE DATABASE '.$database;
@@ -828,7 +847,9 @@  discard block
 block discarded – undo
828 847
         $listtables=array();
829 848
 
830 849
         $like = '';
831
-        if ($table) $like = "LIKE '".$table."'";
850
+        if ($table) {
851
+        	$like = "LIKE '".$table."'";
852
+        }
832 853
         $sql="SHOW TABLES FROM ".$database." ".$like.";";
833 854
         //print $sql;
834 855
         $result = $this->query($sql);
@@ -891,26 +912,27 @@  discard block
 block discarded – undo
891 912
         {
892 913
             $sqlfields[$i] = $field_name." ";
893 914
             $sqlfields[$i]  .= $field_desc['type'];
894
-            if( preg_match("/^[^\s]/i",$field_desc['value']))
895
-            $sqlfields[$i]  .= "(".$field_desc['value'].")";
896
-            else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
897
-            $sqlfields[$i]  .= " ".$field_desc['attribute'];
898
-            else if( preg_match("/^[^\s]/i",$field_desc['default']))
915
+            if( preg_match("/^[^\s]/i",$field_desc['value'])) {
916
+                        $sqlfields[$i]  .= "(".$field_desc['value'].")";
917
+            } else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
918
+                        $sqlfields[$i]  .= " ".$field_desc['attribute'];
919
+            } else if( preg_match("/^[^\s]/i",$field_desc['default']))
899 920
             {
900
-                if(preg_match("/null/i",$field_desc['default']))
901
-                $sqlfields[$i]  .= " default ".$field_desc['default'];
902
-                else
903
-                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
921
+                if(preg_match("/null/i",$field_desc['default'])) {
922
+                                $sqlfields[$i]  .= " default ".$field_desc['default'];
923
+                } else {
924
+                                $sqlfields[$i]  .= " default '".$field_desc['default']."'";
925
+                }
926
+            } else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
927
+                        $sqlfields[$i]  .= " ".$field_desc['null'];
928
+            } else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
929
+                        $sqlfields[$i]  .= " ".$field_desc['extra'];
904 930
             }
905
-            else if( preg_match("/^[^\s]/i",$field_desc['null']))
906
-            $sqlfields[$i]  .= " ".$field_desc['null'];
907
-
908
-            else if( preg_match("/^[^\s]/i",$field_desc['extra']))
909
-            $sqlfields[$i]  .= " ".$field_desc['extra'];
910 931
             $i++;
911 932
         }
912
-        if($primary_key != "")
913
-        $pk = "primary key(".$primary_key.")";
933
+        if($primary_key != "") {
934
+                $pk = "primary key(".$primary_key.")";
935
+        }
914 936
 
915 937
         if(is_array($unique_keys))
916 938
         {
@@ -931,17 +953,21 @@  discard block
 block discarded – undo
931 953
             }
932 954
         }
933 955
         $sql .= implode(',',$sqlfields);
934
-        if($primary_key != "")
935
-        $sql .= ",".$pk;
936
-        if(is_array($unique_keys))
937
-        $sql .= ",".implode(',',$sqluq);
938
-        if(is_array($keys))
939
-        $sql .= ",".implode(',',$sqlk);
956
+        if($primary_key != "") {
957
+                $sql .= ",".$pk;
958
+        }
959
+        if(is_array($unique_keys)) {
960
+                $sql .= ",".implode(',',$sqluq);
961
+        }
962
+        if(is_array($keys)) {
963
+                $sql .= ",".implode(',',$sqlk);
964
+        }
940 965
         $sql .=") type=".$type;
941 966
 
942 967
         dol_syslog($sql,LOG_DEBUG);
943
-        if(! $this -> query($sql))
944
-            return -1;
968
+        if(! $this -> query($sql)) {
969
+                    return -1;
970
+        }
945 971
         return 1;
946 972
     }
947 973
 
@@ -976,24 +1002,29 @@  discard block
 block discarded – undo
976 1002
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
977 1003
         $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
978 1004
         $sql.= $field_desc['type'];
979
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
980
-        if (! in_array($field_desc['type'],array('date','datetime')))
1005
+        if(preg_match("/^[^\s]/i",$field_desc['value'])) {
1006
+                if (! in_array($field_desc['type'],array('date','datetime')))
981 1007
         {
982 1008
             $sql.= "(".$field_desc['value'].")";
983 1009
         }
984
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
985
-        $sql.= " ".$field_desc['attribute'];
986
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
987
-        $sql.= " ".$field_desc['null'];
1010
+        }
1011
+        if(preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1012
+                $sql.= " ".$field_desc['attribute'];
1013
+        }
1014
+        if(preg_match("/^[^\s]/i",$field_desc['null'])) {
1015
+                $sql.= " ".$field_desc['null'];
1016
+        }
988 1017
         if(preg_match("/^[^\s]/i",$field_desc['default']))
989 1018
         {
990
-            if(preg_match("/null/i",$field_desc['default']))
991
-            $sql.= " default ".$field_desc['default'];
992
-            else
993
-            $sql.= " default '".$field_desc['default']."'";
1019
+            if(preg_match("/null/i",$field_desc['default'])) {
1020
+                        $sql.= " default ".$field_desc['default'];
1021
+            } else {
1022
+                        $sql.= " default '".$field_desc['default']."'";
1023
+            }
1024
+        }
1025
+        if(preg_match("/^[^\s]/i",$field_desc['extra'])) {
1026
+                $sql.= " ".$field_desc['extra'];
994 1027
         }
995
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
996
-        $sql.= " ".$field_desc['extra'];
997 1028
         $sql.= " ".$field_position;
998 1029
 
999 1030
         dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
@@ -1021,8 +1052,9 @@  discard block
 block discarded – undo
1021 1052
         }
1022 1053
 
1023 1054
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1024
-        if (! $this->query($sql))
1025
-            return -1;
1055
+        if (! $this->query($sql)) {
1056
+                    return -1;
1057
+        }
1026 1058
         return 1;
1027 1059
     }
1028 1060
 
@@ -1220,8 +1252,7 @@  discard block
 block discarded – undo
1220 1252
                 $obj = $this->fetch_row($resql);
1221 1253
                 //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1222 1254
                 $result[$var] = $obj[0];
1223
-            }
1224
-            else {
1255
+            } else {
1225 1256
                 // TODO Récupérer le message
1226 1257
                 $result[$var] = 'FAIL';
1227 1258
             }
@@ -1288,11 +1319,12 @@  discard block
 block discarded – undo
1288 1319
      */
1289 1320
     private static function calc_daynr($year, $month, $day) {
1290 1321
         $y = $year;
1291
-        if ($y == 0 && $month == 0) return 0;
1322
+        if ($y == 0 && $month == 0) {
1323
+        	return 0;
1324
+        }
1292 1325
         $num = (365* $y + 31 * ($month - 1) + $day);
1293 1326
         if ($month <= 2) {
1294
-            $y--; }
1295
-        else {
1327
+            $y--; } else {
1296 1328
             $num -= floor(($month * 4 + 23) / 10);
1297 1329
         }
1298 1330
         $temp = floor(($y / 100 + 1) * 3 / 4);
@@ -1344,8 +1376,9 @@  discard block
 block discarded – undo
1344 1376
 
1345 1377
         if ($month == 1 && $day <= 7-$weekday)
1346 1378
         {
1347
-            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1348
-                return 0;
1379
+            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4))) {
1380
+                            return 0;
1381
+            }
1349 1382
             $week_year= 1;
1350 1383
             $calc_year--;
1351 1384
             $first_daynr-= ($days=self::calc_days_in_year($calc_year));
@@ -1354,8 +1387,7 @@  discard block
 block discarded – undo
1354 1387
 
1355 1388
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1356 1389
         $days= $daynr - ($first_daynr+ (7-$weekday));
1357
-      }
1358
-      else {
1390
+      } else {
1359 1391
         $days= $daynr - ($first_daynr - $weekday);
1360 1392
       }
1361 1393
 
Please login to merge, or discard this patch.
Upper-Lower-Casing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1213,7 +1213,7 @@
 block discarded – undo
1213 1213
 
1214 1214
         // TODO prendre en compte le filtre
1215 1215
         foreach($pragmas as $var) {
1216
-            $sql = "PRAGMA $var";
1216
+            $sql = "pragma $var";
1217 1217
             $resql=$this->query($sql);
1218 1218
             if ($resql)
1219 1219
             {
Please login to merge, or discard this patch.
htdocs/core/filemanagerdol/connectors/php/util.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
  * Returns true if file contain insecure HTML code at the beginning.
131 131
  *
132 132
  * @param string $filePath absolute path to file
133
- * @return boolean
133
+ * @return string
134 134
  */
135 135
 function DetectHtml( $filePath )
136 136
 {
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
  *
201 201
  * @param 	string 	$filePath 		Absolute path to file
202 202
  * @param 	string 	$extension 		File extension
203
- * @return 	boolean					True or false
203
+ * @return 	string					True or false
204 204
  */
205 205
 function IsImageValid( $filePath, $extension )
206 206
 {
Please login to merge, or discard this patch.
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -209,24 +209,24 @@
 block discarded – undo
209 209
 	}
210 210
 
211 211
 	$imageCheckExtensions = array(
212
-        'gif',
213
-        'jpeg',
214
-        'jpg',
215
-        'png',
216
-        'swf',
217
-        'psd',
218
-        'bmp',
219
-        'iff',
220
-        'tiff',
221
-        'tif',
222
-        'swc',
223
-        'jpc',
224
-        'jp2',
225
-        'jpx',
226
-        'jb2',
227
-        'xbm',
228
-        'wbmp'
229
-    );
212
+		'gif',
213
+		'jpeg',
214
+		'jpg',
215
+		'png',
216
+		'swf',
217
+		'psd',
218
+		'bmp',
219
+		'iff',
220
+		'tiff',
221
+		'tif',
222
+		'swc',
223
+		'jpc',
224
+		'jp2',
225
+		'jpx',
226
+		'jb2',
227
+		'xbm',
228
+		'wbmp'
229
+	);
230 230
 
231 231
 	if (!in_array($extension, $imageCheckExtensions) ) {
232 232
 		return true;
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
  */
32 32
 function RemoveFromStart($sourceString, $charToRemove)
33 33
 {
34
-	$sPattern = '|^' . $charToRemove . '+|' ;
34
+	$sPattern = '|^'.$charToRemove.'+|';
35 35
 	return preg_replace($sPattern, '', $sourceString);
36 36
 }
37 37
 
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
  */
45 45
 function RemoveFromEnd($sourceString, $charToRemove)
46 46
 {
47
-	$sPattern = '|' . $charToRemove . '+$|' ;
47
+	$sPattern = '|'.$charToRemove.'+$|';
48 48
 	return preg_replace($sPattern, '', $sourceString);
49 49
 }
50 50
 
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 	'|(.{1}))';
68 68
 
69 69
 	while (preg_match('/'.$regex.'/S', $string, $matches)) {
70
-		if ( isset($matches[2])) {
70
+		if (isset($matches[2])) {
71 71
 			return true;
72 72
 		}
73 73
 		$string = substr($string, strlen($matches[0]));
@@ -82,11 +82,11 @@  discard block
 block discarded – undo
82 82
  * @param 	string		$value		Value
83 83
  * @return	string
84 84
  */
85
-function ConvertToXmlAttribute( $value )
85
+function ConvertToXmlAttribute($value)
86 86
 {
87
-	if ( defined('PHP_OS') )
87
+	if (defined('PHP_OS'))
88 88
 	{
89
-		$os = PHP_OS ;
89
+		$os = PHP_OS;
90 90
 	}
91 91
 	else
92 92
 	{
@@ -110,14 +110,14 @@  discard block
 block discarded – undo
110 110
  * @param 	array 		$formExtensions		Array of extensions
111 111
  * @return 	boolean
112 112
  */
113
-function IsHtmlExtension( $ext, $formExtensions )
113
+function IsHtmlExtension($ext, $formExtensions)
114 114
 {
115
-	if (!$formExtensions || !is_array($formExtensions) )
115
+	if (!$formExtensions || !is_array($formExtensions))
116 116
 	{
117
-		return false ;
117
+		return false;
118 118
 	}
119 119
 	$lcaseHtmlExtensions = array();
120
-	foreach ( $formExtensions as $key => $val )
120
+	foreach ($formExtensions as $key => $val)
121 121
 	{
122 122
 		$lcaseHtmlExtensions[$key] = strtolower($val);
123 123
 	}
@@ -132,14 +132,14 @@  discard block
 block discarded – undo
132 132
  * @param string $filePath absolute path to file
133 133
  * @return boolean
134 134
  */
135
-function DetectHtml( $filePath )
135
+function DetectHtml($filePath)
136 136
 {
137 137
 	$fp = @fopen($filePath, 'rb');
138 138
 
139 139
 	//open_basedir restriction, see #1906
140
-	if ( $fp === false || !flock($fp, LOCK_SH) )
140
+	if ($fp === false || !flock($fp, LOCK_SH))
141 141
 	{
142
-		return -1 ;
142
+		return -1;
143 143
 	}
144 144
 
145 145
 	$chunk = fread($fp, 1024);
@@ -150,47 +150,47 @@  discard block
 block discarded – undo
150 150
 
151 151
 	if (!$chunk)
152 152
 	{
153
-		return false ;
153
+		return false;
154 154
 	}
155 155
 
156 156
 	$chunk = trim($chunk);
157 157
 
158
-	if ( preg_match("/<!DOCTYPE\W*X?HTML/sim", $chunk) )
158
+	if (preg_match("/<!DOCTYPE\W*X?HTML/sim", $chunk))
159 159
 	{
160 160
 		return true;
161 161
 	}
162 162
 
163
-	$tags = array( '<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title' );
163
+	$tags = array('<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title');
164 164
 
165
-	foreach( $tags as $tag )
165
+	foreach ($tags as $tag)
166 166
 	{
167
-		if( false !== strpos($chunk, $tag) )
167
+		if (false !== strpos($chunk, $tag))
168 168
 		{
169
-			return true ;
169
+			return true;
170 170
 		}
171 171
 	}
172 172
 
173 173
 	//type = javascript
174
-	if ( preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk) )
174
+	if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk))
175 175
 	{
176
-		return true ;
176
+		return true;
177 177
 	}
178 178
 
179 179
 	//href = javascript
180 180
 	//src = javascript
181 181
 	//data = javascript
182
-	if ( preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk) )
182
+	if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk))
183 183
 	{
184
-		return true ;
184
+		return true;
185 185
 	}
186 186
 
187 187
 	//url(javascript
188
-	if ( preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk) )
188
+	if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk))
189 189
 	{
190
-		return true ;
190
+		return true;
191 191
 	}
192 192
 
193
-	return false ;
193
+	return false;
194 194
 }
195 195
 
196 196
 /**
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
  * @param 	string 	$extension 		File extension
203 203
  * @return 	boolean					True or false
204 204
  */
205
-function IsImageValid( $filePath, $extension )
205
+function IsImageValid($filePath, $extension)
206 206
 {
207 207
 	if (!@is_readable($filePath)) {
208 208
 		return -1;
@@ -228,12 +228,12 @@  discard block
 block discarded – undo
228 228
         'wbmp'
229 229
     );
230 230
 
231
-	if (!in_array($extension, $imageCheckExtensions) ) {
231
+	if (!in_array($extension, $imageCheckExtensions)) {
232 232
 		return true;
233 233
 	}
234 234
 
235 235
 	if (@getimagesize($filePath) === false) {
236
-		return false ;
236
+		return false;
237 237
 	}
238 238
 
239 239
 	return true;
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -87,8 +87,7 @@  discard block
 block discarded – undo
87 87
 	if ( defined('PHP_OS') )
88 88
 	{
89 89
 		$os = PHP_OS ;
90
-	}
91
-	else
90
+	} else
92 91
 	{
93 92
 		$os = php_uname();
94 93
 	}
@@ -96,8 +95,7 @@  discard block
 block discarded – undo
96 95
 	if (strtoupper(substr($os, 0, 3)) === 'WIN' || FindBadUtf8($value))
97 96
 	{
98 97
 		return (utf8_encode(htmlspecialchars($value)));
99
-	}
100
-	else
98
+	} else
101 99
 	{
102 100
 		return (htmlspecialchars($value));
103 101
 	}
Please login to merge, or discard this patch.
htdocs/core/lib/ajax.lib.php 4 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
  *	@param	string	$message	Message of dialog box
315 315
  *	@param	int		$w			Width of dialog box
316 316
  *	@param	int		$h			height of dialog box
317
- *	@return	void
317
+ *	@return	string
318 318
  */
319 319
 function ajax_dialog($title,$message,$w=350,$h=150)
320 320
 {
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
  * 	@param	array	$input			Array of type->list of CSS element to switch. Example: array('disabled'=>array(0=>'cssid'))
442 442
  * 	@param	int		$entity			Entity to set
443 443
  *  @param	int		$revertonoff	Revert on/off
444
- *  @param	bool	$strict			Use only "disabled" with delConstant and "enabled" with setConstant
444
+ *  @param	integer	$strict			Use only "disabled" with delConstant and "enabled" with setConstant
445 445
  * 	@return	string
446 446
  */
447 447
 function ajax_constantonoff($code, $input=array(), $entity=null, $revertonoff=0, $strict=0)
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
  *  @param  string  $text_on    Text if on
511 511
  *  @param  string  $text_off   Text if off
512 512
  *  @param  array   $input      Array of type->list of CSS element to switch. Example: array('disabled'=>array(0=>'cssid'))
513
- *  @return void
513
+ *  @return string
514 514
  */
515 515
 function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input=array())
516 516
 {
Please login to merge, or discard this patch.
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -45,16 +45,16 @@  discard block
 block discarded – undo
45 45
  */
46 46
 function ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array())
47 47
 {
48
-    if (empty($minLength)) $minLength=1;
48
+	if (empty($minLength)) $minLength=1;
49 49
 
50
-    $dataforrenderITem='ui-autocomplete';
51
-    $dataforitem='ui-autocomplete-item';
52
-    // Allow two constant to use other values for backward compatibility
53
-    if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem=constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
54
-    if (defined('JS_QUERY_AUTOCOMPLETE_ITEM'))       $dataforitem=constant('JS_QUERY_AUTOCOMPLETE_ITEM');
50
+	$dataforrenderITem='ui-autocomplete';
51
+	$dataforitem='ui-autocomplete-item';
52
+	// Allow two constant to use other values for backward compatibility
53
+	if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem=constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
54
+	if (defined('JS_QUERY_AUTOCOMPLETE_ITEM'))       $dataforitem=constant('JS_QUERY_AUTOCOMPLETE_ITEM');
55 55
 
56
-    // Input search_htmlname is original field
57
-    // Input htmlname is a second input field used when using ajax autocomplete.
56
+	// Input search_htmlname is original field
57
+	// Input htmlname is a second input field used when using ajax autocomplete.
58 58
 	$script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" />';
59 59
 
60 60
 	$script.= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
 	$msg= '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
337 337
 	$msg.= $message;
338 338
 	$msg.= '</div>'."\n";
339
-    $msg.= '<script type="text/javascript">
339
+	$msg.= '<script type="text/javascript">
340 340
     jQuery(function() {
341 341
         jQuery("#dialog-info").dialog({
342 342
 	        resizable: false,
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
 	});
353 353
 	</script>';
354 354
 
355
-    $msg.= "\n";
355
+	$msg.= "\n";
356 356
 
357
-    return $msg;
357
+	return $msg;
358 358
 }
359 359
 
360 360
 
@@ -401,8 +401,8 @@  discard block
 block discarded – undo
401 401
 
402 402
 	if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete=0;
403 403
 
404
-    $tmpplugin='select2';
405
-    $msg="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
404
+	$tmpplugin='select2';
405
+	$msg="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
406 406
           <script type="text/javascript">
407 407
         	$(document).ready(function () {
408 408
     			var query = {};
@@ -478,9 +478,9 @@  discard block
 block discarded – undo
478 478
 	}
479 479
 
480 480
 	$msg.= '});'."\n";
481
-    $msg.= "</script>\n";
481
+	$msg.= "</script>\n";
482 482
 
483
-    return $msg;
483
+	return $msg;
484 484
 }
485 485
 
486 486
 /**
@@ -563,9 +563,9 @@  discard block
 block discarded – undo
563 563
  */
564 564
 function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input=array())
565 565
 {
566
-    global $langs;
566
+	global $langs;
567 567
 
568
-    $out= '<script type="text/javascript">
568
+	$out= '<script type="text/javascript">
569 569
         $(function() {
570 570
             var input = '.json_encode($input).';
571 571
 
@@ -630,9 +630,9 @@  discard block
 block discarded – undo
630 630
             });
631 631
         });
632 632
     </script>';
633
-    $out.= '<span id="set_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'hideobject':'').'">'.img_picto($langs->trans($text_off),'switch_off').'</span>';
634
-    $out.= '<span id="del_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'':'hideobject').'">'.img_picto($langs->trans($text_on),'switch_on').'</span>';
633
+	$out.= '<span id="set_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'hideobject':'').'">'.img_picto($langs->trans($text_off),'switch_off').'</span>';
634
+	$out.= '<span id="del_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'':'hideobject').'">'.img_picto($langs->trans($text_on),'switch_on').'</span>';
635 635
 
636
-    return $out;
636
+	return $out;
637 637
 }
638 638
 
Please login to merge, or discard this patch.
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -43,23 +43,23 @@  discard block
 block discarded – undo
43 43
  *                                          Ex: array('option_disabled'=> id to disable and warning to show if we select a disabled value (this is possible when using autocomplete ajax)
44 44
  *	@return string              		Script
45 45
  */
46
-function ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array())
46
+function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array())
47 47
 {
48
-    if (empty($minLength)) $minLength=1;
48
+    if (empty($minLength)) $minLength = 1;
49 49
 
50
-    $dataforrenderITem='ui-autocomplete';
51
-    $dataforitem='ui-autocomplete-item';
50
+    $dataforrenderITem = 'ui-autocomplete';
51
+    $dataforitem = 'ui-autocomplete-item';
52 52
     // Allow two constant to use other values for backward compatibility
53
-    if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem=constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
54
-    if (defined('JS_QUERY_AUTOCOMPLETE_ITEM'))       $dataforitem=constant('JS_QUERY_AUTOCOMPLETE_ITEM');
53
+    if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
54
+    if (defined('JS_QUERY_AUTOCOMPLETE_ITEM'))       $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
55 55
 
56 56
     // Input search_htmlname is original field
57 57
     // Input htmlname is a second input field used when using ajax autocomplete.
58 58
 	$script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" />';
59 59
 
60
-	$script.= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
61
-	$script.= '<script type="text/javascript">'."\n";
62
-	$script.= '$(document).ready(function() {
60
+	$script .= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
61
+	$script .= '<script type="text/javascript">'."\n";
62
+	$script .= '$(document).ready(function() {
63 63
 					var autoselect = '.$autoselect.';
64 64
 					var options = '.json_encode($ajaxoptions).';
65 65
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
                     });
110 110
     				$("input#search_'.$htmlname.'").autocomplete({
111 111
     					source: function( request, response ) {
112
-    						$.get("'.$url.($urloption?'?'.$urloption:'').'", { '.$htmlname.': request.term }, function(data){
112
+    						$.get("'.$url.($urloption ? '?'.$urloption : '').'", { '.$htmlname.': request.term }, function(data){
113 113
 								if (data != null)
114 114
 								{
115 115
 									response($.map( data, function(item) {
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 										return { label: label, value: item.value, id: item.key, update: update, textarea: textarea, disabled: item.disabled }
134 134
 									}));
135 135
 								}
136
-								else console.error("Error: Ajax url '.$url.($urloption?'?'.$urloption:'').' has returned an empty page. Should be an empty json array.");
136
+								else console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
137 137
 							}, "json");
138 138
 						},
139 139
 						dataType: "json",
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 					};
203 203
 
204 204
   				});';
205
-	$script.= '</script>';
205
+	$script .= '</script>';
206 206
 
207 207
 	return $script;
208 208
 }
@@ -221,11 +221,11 @@  discard block
 block discarded – undo
221 221
  *	@param	int		$autoselect			Automatic selection if just one value
222 222
  *	@return string              		Script
223 223
  */
224
-function ajax_multiautocompleter($htmlname, $fields, $url, $option='', $minLength=2, $autoselect=0)
224
+function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
225 225
 {
226 226
 	$script = '<!-- Autocomplete -->'."\n";
227
-	$script.= '<script type="text/javascript">';
228
-	$script.= 'jQuery(document).ready(function() {
227
+	$script .= '<script type="text/javascript">';
228
+	$script .= 'jQuery(document).ready(function() {
229 229
 					var fields = '.json_encode($fields).';
230 230
 					var nboffields = fields.length;
231 231
 					var autoselect = '.$autoselect.';
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
     					dataType: "json",
236 236
     					minLength: '.$minLength.',
237 237
     					source: function( request, response ) {
238
-    						jQuery.getJSON( "'.$url.($option?'?'.$option:'').'", { '.$htmlname.': request.term }, function(data){
238
+    						jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
239 239
 								response( jQuery.map( data, function( item ) {
240 240
 									if (autoselect == 1 && data.length == 1) {
241 241
 										jQuery("#'.$htmlname.'").val(item.value);
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
     					}
315 315
 					});
316 316
   				});';
317
-	$script.= '</script>';
317
+	$script .= '</script>';
318 318
 
319 319
 	return $script;
320 320
 }
@@ -328,15 +328,15 @@  discard block
 block discarded – undo
328 328
  *	@param	int		$h			height of dialog box
329 329
  *	@return	void
330 330
  */
331
-function ajax_dialog($title,$message,$w=350,$h=150)
331
+function ajax_dialog($title, $message, $w = 350, $h = 150)
332 332
 {
333 333
 	global $langs;
334 334
 
335
-	$newtitle=dol_textishtml($title)?dol_string_nohtmltag($title,1):$title;
336
-	$msg= '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
337
-	$msg.= $message;
338
-	$msg.= '</div>'."\n";
339
-    $msg.= '<script type="text/javascript">
335
+	$newtitle = dol_textishtml($title) ?dol_string_nohtmltag($title, 1) : $title;
336
+	$msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
337
+	$msg .= $message;
338
+	$msg .= '</div>'."\n";
339
+    $msg .= '<script type="text/javascript">
340 340
     jQuery(function() {
341 341
         jQuery("#dialog-info").dialog({
342 342
 	        resizable: false,
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 	});
353 353
 	</script>';
354 354
 
355
-    $msg.= "\n";
355
+    $msg .= "\n";
356 356
 
357 357
     return $msg;
358 358
 }
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
  * @param string	$htmlname	Id of html object
365 365
  * @param string	$addlink	Add a 'link to' after
366 366
  */
367
-function ajax_autoselect($htmlname, $addlink='')
367
+function ajax_autoselect($htmlname, $addlink = '')
368 368
 {
369 369
 	global $langs;
370 370
 	$out = '<script type="text/javascript">
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
 				    jQuery("#'.$htmlname.'").click(function() { jQuery(this).select(); } );
373 373
 				});
374 374
 		    </script>';
375
-	if ($addlink) $out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
375
+	if ($addlink) $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
376 376
 	return $out;
377 377
 }
378 378
 
@@ -389,24 +389,24 @@  discard block
 block discarded – undo
389 389
  * @return	string								Return html string to convert a select field into a combo, or '' if feature has been disabled for some reason.
390 390
  * @see selectArrayAjax of html.form.class
391 391
  */
392
-function ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve')
392
+function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve')
393 393
 {
394 394
 	global $conf;
395 395
 
396
-	if (! empty($conf->browser->phone)) return '';	// select2 disabled for smartphones with standard browser (does not works, popup appears outside screen)
396
+	if (!empty($conf->browser->phone)) return ''; // select2 disabled for smartphones with standard browser (does not works, popup appears outside screen)
397 397
 	//if (! empty($conf->dol_use_jmobile)) return '';	// select2 works with jmobile but it breaks the autosize feature of jmobile.
398
-	if (! empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) return '';
398
+	if (!empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) return '';
399 399
 	if (empty($conf->use_javascript_ajax)) return '';
400
-	if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
400
+	if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
401 401
 
402
-	if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete=0;
402
+	if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete = 0;
403 403
 
404
-    $tmpplugin='select2';
405
-    $msg="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
404
+    $tmpplugin = 'select2';
405
+    $msg = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
406 406
           <script type="text/javascript">
407 407
         	$(document).ready(function () {
408 408
     			var query = {};
409
-        		$(\''.(preg_match('/^\./',$htmlname)?$htmlname:'#'.$htmlname).'\').'.$tmpplugin.'({
409
+        		$(\''.(preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname).'\').'.$tmpplugin.'({
410 410
         		    dir: \'ltr\',
411 411
         			width: \''.$widthTypeOfAutocomplete.'\',		/* off or resolve */
412 412
 					minimumInputLength: '.$minLengthToAutocomplete.',
@@ -429,12 +429,12 @@  discard block
 block discarded – undo
429 429
 						return markup;
430 430
 					}
431 431
 				})';
432
-	if ($forcefocus) $msg.= '.select2(\'focus\')';
433
-	$msg.= ';'."\n";
432
+	if ($forcefocus) $msg .= '.select2(\'focus\')';
433
+	$msg .= ';'."\n";
434 434
 
435 435
 	if (count($events))    // If an array of js events to do were provided.
436 436
 	{
437
-		$msg.= '
437
+		$msg .= '
438 438
 			jQuery("#'.$htmlname.'").change(function () {
439 439
 				var obj = '.json_encode($events).';
440 440
 		   		$.each(obj, function(key,values) {
@@ -483,8 +483,8 @@  discard block
 block discarded – undo
483 483
 			}';
484 484
 	}
485 485
 
486
-	$msg.= '});'."\n";
487
-    $msg.= "</script>\n";
486
+	$msg .= '});'."\n";
487
+    $msg .= "</script>\n";
488 488
 
489 489
     return $msg;
490 490
 }
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
  *  @param	bool	$strict			Use only "disabled" with delConstant and "enabled" with setConstant
500 500
  * 	@return	string
501 501
  */
502
-function ajax_constantonoff($code, $input=array(), $entity=null, $revertonoff=0, $strict=0)
502
+function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0)
503 503
 {
504 504
 	global $conf, $langs;
505 505
 
@@ -507,12 +507,12 @@  discard block
 block discarded – undo
507 507
 
508 508
 	if (empty($conf->use_javascript_ajax))
509 509
 	{
510
-		if (empty($conf->global->$code)) print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Disabled"),'off').'</a>';
511
-		else print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Enabled"),'on').'</a>';
510
+		if (empty($conf->global->$code)) print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
511
+		else print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Enabled"), 'on').'</a>';
512 512
 	}
513 513
 	else
514 514
 	{
515
-		$out= "\n<!-- Ajax code to switch constant ".$code." -->".'
515
+		$out = "\n<!-- Ajax code to switch constant ".$code." -->".'
516 516
 		<script type="text/javascript">
517 517
 			$(document).ready(function() {
518 518
 				var input = '.json_encode($input).';
@@ -547,10 +547,10 @@  discard block
 block discarded – undo
547 547
 			});
548 548
 		</script>'."\n";
549 549
 
550
-		$out.= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
551
-		$out.= '<span id="set_'.$code.'" class="linkobject '.(! empty($conf->global->$code)?'hideobject':'').'">'.($revertonoff?img_picto($langs->trans("Enabled"),'switch_on'):img_picto($langs->trans("Disabled"),'switch_off')).'</span>';
552
-		$out.= '<span id="del_'.$code.'" class="linkobject '.(! empty($conf->global->$code)?'':'hideobject').'">'.($revertonoff?img_picto($langs->trans("Disabled"),'switch_off'):img_picto($langs->trans("Enabled"),'switch_on')).'</span>';
553
-		$out.="\n";
550
+		$out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
551
+		$out .= '<span id="set_'.$code.'" class="linkobject '.(!empty($conf->global->$code) ? 'hideobject' : '').'">'.($revertonoff ?img_picto($langs->trans("Enabled"), 'switch_on') : img_picto($langs->trans("Disabled"), 'switch_off')).'</span>';
552
+		$out .= '<span id="del_'.$code.'" class="linkobject '.(!empty($conf->global->$code) ? '' : 'hideobject').'">'.($revertonoff ?img_picto($langs->trans("Disabled"), 'switch_off') : img_picto($langs->trans("Enabled"), 'switch_on')).'</span>';
553
+		$out .= "\n";
554 554
 	}
555 555
 
556 556
 	return $out;
@@ -567,11 +567,11 @@  discard block
 block discarded – undo
567 567
  *  @param  array   $input      Array of type->list of CSS element to switch. Example: array('disabled'=>array(0=>'cssid'))
568 568
  *  @return void
569 569
  */
570
-function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input=array())
570
+function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array())
571 571
 {
572 572
     global $langs;
573 573
 
574
-    $out= '<script type="text/javascript">
574
+    $out = '<script type="text/javascript">
575 575
         $(function() {
576 576
             var input = '.json_encode($input).';
577 577
 
@@ -636,8 +636,8 @@  discard block
 block discarded – undo
636 636
             });
637 637
         });
638 638
     </script>';
639
-    $out.= '<span id="set_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'hideobject':'').'">'.img_picto($langs->trans($text_off),'switch_off').'</span>';
640
-    $out.= '<span id="del_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code==1?'':'hideobject').'">'.img_picto($langs->trans($text_on),'switch_on').'</span>';
639
+    $out .= '<span id="set_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').'">'.img_picto($langs->trans($text_off), 'switch_off').'</span>';
640
+    $out .= '<span id="del_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').'">'.img_picto($langs->trans($text_on), 'switch_on').'</span>';
641 641
 
642 642
     return $out;
643 643
 }
Please login to merge, or discard this patch.
Braces   +40 added lines, -15 removed lines patch added patch discarded remove patch
@@ -45,13 +45,19 @@  discard block
 block discarded – undo
45 45
  */
46 46
 function ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array())
47 47
 {
48
-    if (empty($minLength)) $minLength=1;
48
+    if (empty($minLength)) {
49
+    	$minLength=1;
50
+    }
49 51
 
50 52
     $dataforrenderITem='ui-autocomplete';
51 53
     $dataforitem='ui-autocomplete-item';
52 54
     // Allow two constant to use other values for backward compatibility
53
-    if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem=constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
54
-    if (defined('JS_QUERY_AUTOCOMPLETE_ITEM'))       $dataforitem=constant('JS_QUERY_AUTOCOMPLETE_ITEM');
55
+    if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
56
+    	$dataforrenderITem=constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
57
+    }
58
+    if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
59
+    	$dataforitem=constant('JS_QUERY_AUTOCOMPLETE_ITEM');
60
+    }
55 61
 
56 62
     // Input search_htmlname is original field
57 63
     // Input htmlname is a second input field used when using ajax autocomplete.
@@ -372,7 +378,9 @@  discard block
 block discarded – undo
372 378
 				    jQuery("#'.$htmlname.'").click(function() { jQuery(this).select(); } );
373 379
 				});
374 380
 		    </script>';
375
-	if ($addlink) $out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
381
+	if ($addlink) {
382
+		$out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
383
+	}
376 384
 	return $out;
377 385
 }
378 386
 
@@ -393,13 +401,24 @@  discard block
 block discarded – undo
393 401
 {
394 402
 	global $conf;
395 403
 
396
-	if (! empty($conf->browser->phone)) return '';	// select2 disabled for smartphones with standard browser (does not works, popup appears outside screen)
404
+	if (! empty($conf->browser->phone)) {
405
+		return '';
406
+	}
407
+	// select2 disabled for smartphones with standard browser (does not works, popup appears outside screen)
397 408
 	//if (! empty($conf->dol_use_jmobile)) return '';	// select2 works with jmobile but it breaks the autosize feature of jmobile.
398
-	if (! empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) return '';
399
-	if (empty($conf->use_javascript_ajax)) return '';
400
-	if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
409
+	if (! empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) {
410
+		return '';
411
+	}
412
+	if (empty($conf->use_javascript_ajax)) {
413
+		return '';
414
+	}
415
+	if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) {
416
+		return '';
417
+	}
401 418
 
402
-	if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete=0;
419
+	if (empty($minLengthToAutocomplete)) {
420
+		$minLengthToAutocomplete=0;
421
+	}
403 422
 
404 423
     $tmpplugin='select2';
405 424
     $msg="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
@@ -429,10 +448,13 @@  discard block
 block discarded – undo
429 448
 						return markup;
430 449
 					}
431 450
 				})';
432
-	if ($forcefocus) $msg.= '.select2(\'focus\')';
451
+	if ($forcefocus) {
452
+		$msg.= '.select2(\'focus\')';
453
+	}
433 454
 	$msg.= ';'."\n";
434 455
 
435
-	if (count($events))    // If an array of js events to do were provided.
456
+	if (count($events)) {
457
+		// If an array of js events to do were provided.
436 458
 	{
437 459
 		$msg.= '
438 460
 			jQuery("#'.$htmlname.'").change(function () {
@@ -482,6 +504,7 @@  discard block
 block discarded – undo
482 504
 				);
483 505
 			}';
484 506
 	}
507
+	}
485 508
 
486 509
 	$msg.= '});'."\n";
487 510
     $msg.= "</script>\n";
@@ -507,10 +530,12 @@  discard block
 block discarded – undo
507 530
 
508 531
 	if (empty($conf->use_javascript_ajax))
509 532
 	{
510
-		if (empty($conf->global->$code)) print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Disabled"),'off').'</a>';
511
-		else print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Enabled"),'on').'</a>';
512
-	}
513
-	else
533
+		if (empty($conf->global->$code)) {
534
+			print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Disabled"),'off').'</a>';
535
+		} else {
536
+			print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_'.$code.'&entity='.$entity.'">'.img_picto($langs->trans("Enabled"),'on').'</a>';
537
+		}
538
+	} else
514 539
 	{
515 540
 		$out= "\n<!-- Ajax code to switch constant ".$code." -->".'
516 541
 		<script type="text/javascript">
Please login to merge, or discard this patch.