Completed
Branch develop (c604ce)
by
unknown
32:31
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.
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.
Indentation   +15 added lines, -15 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
 
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	 * 	Renvoie le nombre de facture par mois pour une annee donnee
92 92
 	 *
93 93
 	 *	@param	string	$year	Year to scan
94
-     *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
94
+	 *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
95 95
 	 *	@return	array			Array of values
96 96
 	 */
97 97
 	function getNbByMonth($year, $format=0)
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 		$sql.= " WHERE YEAR(dated) = ".$year;
102 102
 		$sql.= " AND ".$this->where;
103 103
 		$sql.= " GROUP BY dm";
104
-        $sql.= $this->db->order('dm','DESC');
104
+		$sql.= $this->db->order('dm','DESC');
105 105
 
106 106
 		$res=$this->_getNbByMonth($year, $sql, $format);
107 107
 		//var_dump($res);print '<br>';
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 	 * 	Renvoie le montant de facture par mois pour une annee donnee
114 114
 	 *
115 115
 	 *	@param	int		$year		Year to scan
116
-     *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
116
+	 *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
117 117
 	 *	@return	array				Array of values
118 118
 	 */
119 119
 	function getAmountByMonth($year, $format=0)
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
144 144
 		$sql.= " AND ".$this->where;
145 145
 		$sql.= " GROUP BY dm";
146
-        $sql.= $this->db->order('dm','DESC');
146
+		$sql.= $this->db->order('dm','DESC');
147 147
 
148 148
 		return $this->_getAverageByMonth($year, $sql);
149 149
 	}
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		$sql.= " FROM ".$this->from;
160 160
 		$sql.= " WHERE ".$this->where;
161 161
 		$sql.= " GROUP BY year";
162
-        $sql.= $this->db->order('year','DESC');
162
+		$sql.= $this->db->order('year','DESC');
163 163
 
164 164
 		return $this->_getAllByYear($sql);
165 165
 	}
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 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
  *	Classe permettant la gestion des stats des deplacements et notes de frais
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
      * @param   mixed		$userid    Id user for filter or array of user ids
48 48
 	 * @return 	void
49 49
 	 */
50
-	function __construct($db, $socid=0, $userid=0)
50
+	function __construct($db, $socid = 0, $userid = 0)
51 51
 	{
52 52
 		global $conf;
53 53
 
@@ -55,18 +55,18 @@  discard block
 block discarded – undo
55 55
         $this->socid = $socid;
56 56
         $this->userid = $userid;
57 57
 
58
-		$object=new Deplacement($this->db);
58
+		$object = new Deplacement($this->db);
59 59
 		$this->from = MAIN_DB_PREFIX.$object->table_element;
60
-		$this->field='km';
60
+		$this->field = 'km';
61 61
 
62 62
 		$this->where = " fk_statut > 0";
63
-		$this->where.= " AND entity = ".$conf->entity;
63
+		$this->where .= " AND entity = ".$conf->entity;
64 64
 		if ($this->socid)
65 65
 		{
66
-			$this->where.=" AND fk_soc = ".$this->socid;
66
+			$this->where .= " AND fk_soc = ".$this->socid;
67 67
 		}
68
-		if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
69
-        else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
68
+		if (is_array($this->userid) && count($this->userid) > 0) $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')';
69
+        else if ($this->userid > 0) $this->where .= ' AND fk_user = '.$this->userid;
70 70
 	}
71 71
 
72 72
 
@@ -78,9 +78,9 @@  discard block
 block discarded – undo
78 78
 	function getNbByYear()
79 79
 	{
80 80
 		$sql = "SELECT YEAR(dated) as dm, count(*)";
81
-		$sql.= " FROM ".$this->from;
82
-		$sql.= " GROUP BY dm DESC";
83
-		$sql.= " WHERE ".$this->where;
81
+		$sql .= " FROM ".$this->from;
82
+		$sql .= " GROUP BY dm DESC";
83
+		$sql .= " WHERE ".$this->where;
84 84
 
85 85
 		return $this->_getNbByYear($sql);
86 86
 	}
@@ -93,16 +93,16 @@  discard block
 block discarded – undo
93 93
      *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
94 94
 	 *	@return	array			Array of values
95 95
 	 */
96
-	function getNbByMonth($year, $format=0)
96
+	function getNbByMonth($year, $format = 0)
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, $format);
105
+		$res = $this->_getNbByMonth($year, $sql, $format);
106 106
 		//var_dump($res);print '<br>';
107 107
 		return $res;
108 108
 	}
@@ -115,16 +115,16 @@  discard block
 block discarded – undo
115 115
      *	@param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
116 116
 	 *	@return	array				Array of values
117 117
 	 */
118
-	function getAmountByMonth($year, $format=0)
118
+	function getAmountByMonth($year, $format = 0)
119 119
 	{
120 120
 		$sql = "SELECT date_format(dated,'%m') as dm, sum(".$this->field.")";
121
-		$sql.= " FROM ".$this->from;
122
-		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
123
-		$sql.= " AND ".$this->where;
124
-		$sql.= " GROUP BY dm";
125
-		$sql.= $this->db->order('dm','DESC');
121
+		$sql .= " FROM ".$this->from;
122
+		$sql .= " WHERE date_format(dated,'%Y') = '".$year."'";
123
+		$sql .= " AND ".$this->where;
124
+		$sql .= " GROUP BY dm";
125
+		$sql .= $this->db->order('dm', 'DESC');
126 126
 
127
-		$res=$this->_getAmountByMonth($year, $sql, $format);
127
+		$res = $this->_getAmountByMonth($year, $sql, $format);
128 128
 		//var_dump($res);print '<br>';
129 129
 		return $res;
130 130
 	}
@@ -138,11 +138,11 @@  discard block
 block discarded – undo
138 138
 	function getAverageByMonth($year)
139 139
 	{
140 140
 		$sql = "SELECT date_format(dated,'%m') as dm, avg(".$this->field.")";
141
-		$sql.= " FROM ".$this->from;
142
-		$sql.= " WHERE date_format(dated,'%Y') = '".$year."'";
143
-		$sql.= " AND ".$this->where;
144
-		$sql.= " GROUP BY dm";
145
-        $sql.= $this->db->order('dm','DESC');
141
+		$sql .= " FROM ".$this->from;
142
+		$sql .= " WHERE date_format(dated,'%Y') = '".$year."'";
143
+		$sql .= " AND ".$this->where;
144
+		$sql .= " GROUP BY dm";
145
+        $sql .= $this->db->order('dm', 'DESC');
146 146
 
147 147
 		return $this->_getAverageByMonth($year, $sql);
148 148
 	}
@@ -155,10 +155,10 @@  discard block
 block discarded – undo
155 155
 	function getAllByYear()
156 156
 	{
157 157
 		$sql = "SELECT date_format(dated,'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg";
158
-		$sql.= " FROM ".$this->from;
159
-		$sql.= " WHERE ".$this->where;
160
-		$sql.= " GROUP BY year";
161
-        $sql.= $this->db->order('year','DESC');
158
+		$sql .= " FROM ".$this->from;
159
+		$sql .= " WHERE ".$this->where;
160
+		$sql .= " GROUP BY year";
161
+        $sql .= $this->db->order('year', 'DESC');
162 162
 
163 163
 		return $this->_getAllByYear($sql);
164 164
 	}
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/class/rssparser.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -151,7 +151,7 @@
 block discarded – undo
151 151
     /**
152 152
      * getLastFetchDate
153 153
      *
154
-     * @return string
154
+     * @return integer
155 155
      */
156 156
     public function getLastFetchDate()
157 157
     {
Please login to merge, or discard this patch.
Indentation   +741 added lines, -741 removed lines patch added patch discarded remove patch
@@ -26,702 +26,702 @@  discard block
 block discarded – undo
26 26
  */
27 27
 class RssParser
28 28
 {
29
-    var $db;
30
-    var $error;
31
-
32
-    private $_format='';
33
-    private $_urlRSS;
34
-    private $_language;
35
-    private $_generator;
36
-    private $_copyright;
37
-    private $_lastbuilddate;
38
-    private $_imageurl;
39
-    private $_link;
40
-    private $_title;
41
-    private $_description;
42
-    private $_lastfetchdate;    // Last successful fetch
43
-    private $_rssarray=array();
44
-
45
-    // For parsing with xmlparser
46
-    var $stack               = array(); // parser stack
47
-    var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
48
-
49
-
50
-    /**
51
-     *	Constructor
52
-     *
53
-     *  @param		DoliDB		$db      Database handler
54
-     */
55
-    public function __construct($db)
56
-    {
57
-    	$this->db=$db;
58
-    }
59
-
60
-    /**
61
-     * getFormat
62
-     *
63
-     * @return string
64
-     */
65
-    public function getFormat()
66
-    {
67
-        return $this->_format;
68
-    }
69
-
70
-    /**
71
-     * getUrlRss
72
-     *
73
-     * @return string
74
-     */
75
-    public function getUrlRss()
76
-    {
77
-        return $this->_urlRSS;
78
-    }
79
-    /**
80
-     * getLanguage
81
-     *
82
-     * @return string
83
-     */
84
-    public function getLanguage()
85
-    {
86
-        return $this->_language;
87
-    }
88
-    /**
89
-     * getGenerator
90
-     *
91
-     * @return string
92
-     */
93
-    public function getGenerator()
94
-    {
95
-        return $this->_generator;
96
-    }
97
-    /**
98
-     * getCopyright
99
-     *
100
-     * @return string
101
-     */
102
-    public function getCopyright()
103
-    {
104
-        return $this->_copyright;
105
-    }
106
-    /**
107
-     * getLastBuildDate
108
-     *
109
-     * @return string
110
-     */
111
-    public function getLastBuildDate()
112
-    {
113
-        return $this->_lastbuilddate;
114
-    }
115
-    /**
116
-     * getImageUrl
117
-     *
118
-     * @return string
119
-     */
120
-    public function getImageUrl()
121
-    {
122
-        return $this->_imageurl;
123
-    }
124
-    /**
125
-     * getLink
126
-     *
127
-     * @return string
128
-     */
129
-    public function getLink()
130
-    {
131
-        return $this->_link;
132
-    }
133
-    /**
134
-     * getTitle
135
-     *
136
-     * @return string
137
-     */
138
-    public function getTitle()
139
-    {
140
-        return $this->_title;
141
-    }
142
-    /**
143
-     * getDescription
144
-     *
145
-     * @return string
146
-     */
147
-    public function getDescription()
148
-    {
149
-        return $this->_description;
150
-    }
151
-    /**
152
-     * getLastFetchDate
153
-     *
154
-     * @return string
155
-     */
156
-    public function getLastFetchDate()
157
-    {
158
-        return $this->_lastfetchdate;
159
-    }
160
-    /**
161
-     * getItems
162
-     *
163
-     * @return string
164
-     */
165
-    public function getItems()
166
-    {
167
-        return $this->_rssarray;
168
-    }
169
-
170
-
171
-    /**
172
-     * 	Parse rss URL
173
-     *
174
-     * 	@param	string	$urlRSS		Url to parse
175
-     * 	@param	int		$maxNb		Max nb of records to get (0 for no limit)
176
-     * 	@param	int		$cachedelay	0=No cache, nb of seconds we accept cache files (cachedir must also be defined)
177
-     * 	@param	string	$cachedir	Directory where to save cache file
178
-     *	@return	int					<0 if KO, >0 if OK
179
-     */
180
-    public function parser($urlRSS, $maxNb=0, $cachedelay=60, $cachedir='')
181
-    {
182
-        global $conf;
183
-
184
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
185
-
186
-        $rss='';
187
-        $str='';    // This will contain content of feed
188
-
189
-        // Check parameters
190
-        if (! dol_is_url($urlRSS))
191
-        {
192
-            $this->error="ErrorBadUrl";
193
-            return -1;
194
-        }
195
-
196
-        $this->_urlRSS = $urlRSS;
197
-        $newpathofdestfile=$cachedir.'/'.dol_hash($this->_urlRSS,3);	// Force md5 hash (does not contains special chars)
198
-        $newmask='0644';
199
-
200
-        //dol_syslog("RssPArser::parser parse url=".$urlRSS." => cache file=".$newpathofdestfile);
201
-        $nowgmt = dol_now();
202
-
203
-        // Search into cache
204
-        $foundintocache=0;
205
-        if ($cachedelay > 0 && $cachedir)
206
-        {
207
-            $filedate=dol_filemtime($newpathofdestfile);
208
-            if ($filedate >= ($nowgmt - $cachedelay))
209
-            {
210
-                //dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
211
-                $foundintocache=1;
212
-
213
-                $this->_lastfetchdate=$filedate;
214
-            }
215
-            else
216
-            {
217
-                dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
218
-            }
219
-        }
220
-
221
-        // Load file into $str
222
-        if ($foundintocache)    // Cache file found and is not too old
223
-        {
224
-            $str = file_get_contents($newpathofdestfile);
225
-        }
226
-        else
227
-        {
228
-            try {
229
-                ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
230
-                ini_set("max_execution_time", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
231
-                ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
232
-
233
-                $opts = array('http'=>array('method'=>"GET"));
234
-                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
235
-                if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
236
-                //var_dump($opts);exit;
237
-                $context = stream_context_create($opts);
238
-
239
-                $str = file_get_contents($this->_urlRSS, false, $context);
240
-            }
241
-            catch (Exception $e) {
242
-                print 'Error retrieving URL '.$this->urlRSS.' - '.$e->getMessage();
243
-            }
244
-        }
245
-
246
-        if ($str !== false)
247
-        {
248
-	        // Convert $str into xml
249
-	        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
250
-	        {
251
-	            //print 'xx'.LIBXML_NOCDATA;
252
-	            libxml_use_internal_errors(false);
253
-	            $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
254
-	        }
255
-	        else
256
-	        {
257
-	            $xmlparser=xml_parser_create('');
258
-	            if (!is_resource($xmlparser)) {
259
-	                $this->error="ErrorFailedToCreateParser"; return -1;
260
-	            }
261
-
262
-	            xml_set_object($xmlparser, $this);
263
-	            xml_set_element_handler($xmlparser, 'feed_start_element', 'feed_end_element');
264
-	            xml_set_character_data_handler($xmlparser, 'feed_cdata');
265
-	            $status = xml_parse($xmlparser, $str);
266
-	            xml_parser_free($xmlparser);
267
-	            $rss=$this;
268
-	            //var_dump($rss->_format);exit;
269
-	        }
270
-        }
271
-
272
-        // If $rss loaded
273
-        if ($rss)
274
-        {
275
-            // Save file into cache
276
-            if (empty($foundintocache) && $cachedir)
277
-            {
278
-                dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
279
-                if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
280
-                $fp = fopen($newpathofdestfile, 'w');
281
-                if ($fp)
282
-                {
283
-                	fwrite($fp, $str);
284
-                	fclose($fp);
285
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
286
-                	@chmod($newpathofdestfile, octdec($newmask));
287
-
288
-	                $this->_lastfetchdate=$nowgmt;
289
-                }
290
-                else
291
-                {
292
-                	print 'Error, failed to open file '.$newpathofdestfile.' for write';
293
-                }
294
-            }
295
-
296
-            unset($str);    // Free memory
297
-
298
-            if (empty($rss->_format))    // If format not detected automatically
299
-            {
300
-                $rss->_format='rss';
301
-                if (empty($rss->channel)) $rss->_format='atom';
302
-            }
303
-
304
-            $items=array();
305
-
306
-            // Save description entries
307
-            if ($rss->_format == 'rss')
308
-            {
309
-                //var_dump($rss);
310
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
311
-                {
312
-                    if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
313
-                    if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
314
-                    if (!empty($rss->channel->copyright))     $this->_copyright = (string) $rss->channel->copyright;
315
-                    if (!empty($rss->channel->lastbuilddate)) $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
316
-                    if (!empty($rss->channel->image->url[0])) $this->_imageurl = (string) $rss->channel->image->url[0];
317
-                    if (!empty($rss->channel->link))		  $this->_link = (string) $rss->channel->link;
318
-                    if (!empty($rss->channel->title))         $this->_title = (string) $rss->channel->title;
319
-                    if (!empty($rss->channel->description))	  $this->_description = (string) $rss->channel->description;
320
-                }
321
-                else
322
-                {
323
-                    //var_dump($rss->channel);
324
-                    if (!empty($rss->channel['language']))      $this->_language = (string) $rss->channel['language'];
325
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
326
-                    if (!empty($rss->channel['copyright']))     $this->_copyright = (string) $rss->channel['copyright'];
327
-                    if (!empty($rss->channel['lastbuilddate'])) $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
328
-                    if (!empty($rss->image['url']))             $this->_imageurl = (string) $rss->image['url'];
329
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
330
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
331
-                    if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
332
-                }
333
-
334
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
335
-                else $items=$rss->items;                                                              // With xmlparse
336
-                //var_dump($items);exit;
337
-            }
338
-            else if ($rss->_format == 'atom')
339
-            {
340
-                //var_dump($rss);
341
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
342
-                {
343
-                    if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
344
-                    if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
345
-                    if (!empty($rss->link->href))    $this->_link = (string) $rss->link->href;
346
-                    if (!empty($rss->title))         $this->_title = (string) $rss->title;
347
-                    if (!empty($rss->description))	 $this->_description = (string) $rss->description;
348
-                }
349
-                else
350
-                {
351
-                    //if (!empty($rss->channel['rss_language']))      $this->_language = (string) $rss->channel['rss_language'];
352
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
353
-                    //if (!empty($rss->channel['rss_copyright']))     $this->_copyright = (string) $rss->channel['rss_copyright'];
354
-                    if (!empty($rss->channel['modified'])) $this->_lastbuilddate = (string) $rss->channel['modified'];
355
-                    //if (!empty($rss->image['rss_url']))             $this->_imageurl = (string) $rss->image['rss_url'];
356
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
357
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
358
-                    //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
359
-                }
360
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
361
-                    $tmprss=xml2php($rss); $items=$tmprss['entry'];
362
-                } // With simplexml
363
-                else $items=$rss->items;                                                              // With xmlparse
364
-                //var_dump($items);exit;
365
-            }
366
-
367
-            $i = 0;
368
-
369
-            // Loop on each record
370
-            if (is_array($items))
371
-            {
372
-                foreach($items as $item)
373
-                {
374
-                    //var_dump($item);exit;
375
-                    if ($rss->_format == 'rss')
376
-                    {
377
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
378
-                        {
379
-                            $itemLink = (string) $item->link;
380
-                            $itemTitle = (string) $item->title;
381
-                            $itemDescription = (string) $item->description;
382
-                            $itemPubDate = (string) $item->pubDate;
383
-                            $itemId = '';
384
-                            $itemAuthor = '';
385
-                        }
386
-                        else
387
-                        {
388
-                            $itemLink = (string) $item['link'];
389
-                            $itemTitle = (string) $item['title'];
390
-                            $itemDescription = (string) $item['description'];
391
-                            $itemPubDate = (string) $item['pubdate'];
392
-                            $itemId = (string) $item['guid'];
393
-                            $itemAuthor = (string) $item['author'];
394
-                        }
395
-
396
-                        // Loop on each category
397
-                        $itemCategory=array();
398
-                        if (is_array($item->category))
399
-                        {
400
-                            foreach ($item->category as $cat)
401
-                            {
402
-                                $itemCategory[] = (string) $cat;
403
-                            }
404
-                        }
405
-                    }
406
-                    else if ($rss->_format == 'atom')
407
-                    {
408
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
409
-                        {
410
-                            $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
411
-                            $itemTitle = (string) $item['title'];
412
-                            $itemDescription = (string) $item['summary'];
413
-                            $itemPubDate = (string) $item['created'];
414
-                            $itemId = (string) $item['id'];
415
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
416
-                        }
417
-                        else
418
-                        {
419
-                            $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
420
-                            $itemTitle = (string) $item['title'];
421
-                            $itemDescription = (string) $item['summary'];
422
-                            $itemPubDate = (string) $item['created'];
423
-                            $itemId = (string) $item['id'];
424
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
425
-                        }
426
-                    }
427
-                    else print 'ErrorBadFeedFormat';
428
-
429
-                    // Add record to result array
430
-                    $this->_rssarray[$i] = array(
431
-    					'link'=>$itemLink,
432
-    					'title'=>$itemTitle,
433
-    					'description'=>$itemDescription,
434
-    					'pubDate'=>$itemPubDate,
435
-    					'category'=>$itemCategory,
436
-    				    'id'=>$itemId,
437
-    				    'author'=>$itemAuthor);
438
-                    //var_dump($this->_rssarray);
439
-
440
-                    $i++;
441
-
442
-                    if ($i > $maxNb)    break;    // We get all records we want
443
-                }
444
-            }
445
-
446
-            return 1;
447
-        }
448
-        else
449
-        {
450
-            $this->error='ErrorFailedToLoadRSSFile';
451
-            return -1;
452
-        }
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * 	Triggered when opened tag is found
459
-     *
460
-     * 	@param	string		$p			Start
461
-     *  @param	string		$element	Tag
462
-     *  @param	array		$attrs		Attributes of tags
463
-     *  @return	void
464
-     */
465
-    function feed_start_element($p, $element, &$attrs)
466
-    {
467
-        $el = $element = strtolower($element);
468
-        $attrs = array_change_key_case($attrs, CASE_LOWER);
469
-
470
-        // check for a namespace, and split if found
471
-        $ns = false;
472
-        if (strpos($element, ':'))
473
-        {
474
-            list($ns, $el) = explode(':', $element, 2);
475
-        }
476
-        if ( $ns and $ns != 'rdf' )
477
-        {
478
-            $this->current_namespace = $ns;
479
-        }
480
-
481
-        // if feed type isn't set, then this is first element of feed identify feed from root element
482
-        if (empty($this->_format))
483
-        {
484
-            if ( $el == 'rdf' ) {
485
-                $this->_format = 'rss';
486
-                $this->feed_version = '1.0';
487
-            }
488
-            elseif ( $el == 'rss' ) {
489
-                $this->_format = 'rss';
490
-                $this->feed_version = $attrs['version'];
491
-            }
492
-            elseif ( $el == 'feed' ) {
493
-                $this->_format = 'atom';
494
-                $this->feed_version = $attrs['version'];
495
-                $this->inchannel = true;
496
-            }
497
-            return;
498
-        }
499
-
500
-        if ( $el == 'channel' )
501
-        {
502
-            $this->inchannel = true;
503
-        }
504
-        elseif ($el == 'item' or $el == 'entry' )
505
-        {
506
-            $this->initem = true;
507
-            if ( isset($attrs['rdf:about']) ) {
508
-                $this->current_item['about'] = $attrs['rdf:about'];
509
-            }
510
-        }
511
-
512
-        // if we're in the default namespace of an RSS feed,
513
-        //  record textinput or image fields
514
-        elseif (
515
-        $this->_format == 'rss' and
516
-        $this->current_namespace == '' and
517
-        $el == 'textinput' )
518
-        {
519
-            $this->intextinput = true;
520
-        }
521
-
522
-        elseif (
523
-        $this->_format == 'rss' and
524
-        $this->current_namespace == '' and
525
-        $el == 'image' )
526
-        {
527
-            $this->inimage = true;
528
-        }
529
-
530
-        // handle atom content constructs
531
-        elseif ( $this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
532
-        {
533
-            // avoid clashing w/ RSS mod_content
534
-            if ($el == 'content' ) {
535
-                $el = 'atom_content';
536
-            }
537
-
538
-            $this->incontent = $el;
539
-
540
-
541
-        }
542
-
543
-        // if inside an Atom content construct (e.g. content or summary) field treat tags as text
544
-        elseif ($this->_format == 'atom' and $this->incontent )
545
-        {
546
-            // if tags are inlined, then flatten
547
-            $attrs_str = join(' ', array_map('map_attrs', array_keys($attrs), array_values($attrs)));
548
-
549
-            $this->append_content("<$element $attrs_str>");
550
-
551
-            array_unshift($this->stack, $el);
552
-        }
553
-
554
-        // Atom support many links per containging element.
555
-        // Magpie treats link elements of type rel='alternate'
556
-        // as being equivalent to RSS's simple link element.
557
-        //
558
-        elseif ($this->_format == 'atom' and $el == 'link' )
559
-        {
560
-            if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
561
-            {
562
-                $link_el = 'link';
563
-            }
564
-            else {
565
-                $link_el = 'link_' . $attrs['rel'];
566
-            }
567
-
568
-            $this->append($link_el, $attrs['href']);
569
-        }
570
-        // set stack[0] to current element
571
-        else {
572
-            array_unshift($this->stack, $el);
573
-        }
574
-    }
575
-
576
-
577
-    /**
578
-     * 	Triggered when CDATA is found
579
-     *
580
-     * 	@param	string	$p		P
581
-     *  @param	string	$text	Tag
582
-     *  @return	void
583
-     */
584
-    function feed_cdata($p, $text)
585
-    {
586
-        if ($this->_format == 'atom' and $this->incontent)
587
-        {
588
-            $this->append_content($text);
589
-        }
590
-        else
591
-        {
592
-            $current_el = join('_', array_reverse($this->stack));
593
-            $this->append($current_el, $text);
594
-        }
595
-    }
596
-
597
-    /**
598
-     * 	Triggered when closed tag is found
599
-     *
600
-     * 	@param	string		$p		P
601
-     *  @param	string		$el		Tag
602
-     *  @return	void
603
-     */
604
-    function feed_end_element($p, $el)
605
-    {
606
-        $el = strtolower($el);
607
-
608
-        if ($el == 'item' or $el == 'entry')
609
-        {
610
-            $this->items[] = $this->current_item;
611
-            $this->current_item = array();
612
-            $this->initem = false;
613
-        }
614
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
615
-        {
616
-            $this->intextinput = false;
617
-        }
618
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
619
-        {
620
-            $this->inimage = false;
621
-        }
622
-        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
623
-        {
624
-            $this->incontent = false;
625
-        }
626
-        elseif ($el == 'channel' or $el == 'feed' )
627
-        {
628
-            $this->inchannel = false;
629
-        }
630
-        elseif ($this->_format == 'atom' and $this->incontent  ) {
631
-            // balance tags properly
632
-            // note:  i don't think this is actually neccessary
633
-            if ( $this->stack[0] == $el )
634
-            {
635
-                $this->append_content("</$el>");
636
-            }
637
-            else {
638
-                $this->append_content("<$el />");
639
-            }
640
-
641
-            array_shift($this->stack);
642
-        }
643
-        else {
644
-            array_shift($this->stack);
645
-        }
646
-
647
-        $this->current_namespace = false;
648
-    }
649
-
650
-
651
-    /**
652
-     * 	To concat 2 string with no warning if an operand is not defined
653
-     *
654
-     * 	@param	string	$str1		Str1
655
-     *  @param	string	$str2		Str2
656
-     *  @return	string				String cancatenated
657
-     */
658
-    function concat(&$str1, $str2="")
659
-    {
660
-        if (!isset($str1) ) {
661
-            $str1="";
662
-        }
663
-        $str1 .= $str2;
664
-    }
665
-
666
-    /**
667
-     * Enter description here ...
668
-     *
669
-     * @param	string	$text		Text
670
-     * @return	void
671
-     */
672
-    function append_content($text)
673
-    {
674
-        if ( $this->initem ) {
675
-            $this->concat($this->current_item[ $this->incontent ], $text);
676
-        }
677
-        elseif ( $this->inchannel ) {
678
-            $this->concat($this->channel[ $this->incontent ], $text);
679
-        }
680
-    }
681
-
682
-    /**
683
-     * 	smart append - field and namespace aware
684
-     *
685
-     * 	@param	string	$el		El
686
-     * 	@param	string	$text	Text
687
-     * 	@return	void
688
-     */
689
-    function append($el, $text)
690
-    {
691
-        if (!$el) {
692
-            return;
693
-        }
694
-        if ( $this->current_namespace )
695
-        {
696
-            if ( $this->initem ) {
697
-                $this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
698
-            }
699
-            elseif ($this->inchannel) {
700
-                $this->concat($this->channel[ $this->current_namespace][ $el ], $text);
701
-            }
702
-            elseif ($this->intextinput) {
703
-                $this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
704
-            }
705
-            elseif ($this->inimage) {
706
-                $this->concat($this->image[ $this->current_namespace ][ $el ], $text);
707
-            }
708
-        }
709
-        else {
710
-            if ( $this->initem ) {
711
-                $this->concat($this->current_item[ $el ], $text);
712
-            }
713
-            elseif ($this->intextinput) {
714
-                $this->concat($this->textinput[ $el ], $text);
715
-            }
716
-            elseif ($this->inimage) {
717
-                $this->concat($this->image[ $el ], $text);
718
-            }
719
-            elseif ($this->inchannel) {
720
-                $this->concat($this->channel[ $el ], $text);
721
-            }
722
-
723
-        }
724
-    }
29
+	var $db;
30
+	var $error;
31
+
32
+	private $_format='';
33
+	private $_urlRSS;
34
+	private $_language;
35
+	private $_generator;
36
+	private $_copyright;
37
+	private $_lastbuilddate;
38
+	private $_imageurl;
39
+	private $_link;
40
+	private $_title;
41
+	private $_description;
42
+	private $_lastfetchdate;    // Last successful fetch
43
+	private $_rssarray=array();
44
+
45
+	// For parsing with xmlparser
46
+	var $stack               = array(); // parser stack
47
+	var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
48
+
49
+
50
+	/**
51
+	 *	Constructor
52
+	 *
53
+	 *  @param		DoliDB		$db      Database handler
54
+	 */
55
+	public function __construct($db)
56
+	{
57
+		$this->db=$db;
58
+	}
59
+
60
+	/**
61
+	 * getFormat
62
+	 *
63
+	 * @return string
64
+	 */
65
+	public function getFormat()
66
+	{
67
+		return $this->_format;
68
+	}
69
+
70
+	/**
71
+	 * getUrlRss
72
+	 *
73
+	 * @return string
74
+	 */
75
+	public function getUrlRss()
76
+	{
77
+		return $this->_urlRSS;
78
+	}
79
+	/**
80
+	 * getLanguage
81
+	 *
82
+	 * @return string
83
+	 */
84
+	public function getLanguage()
85
+	{
86
+		return $this->_language;
87
+	}
88
+	/**
89
+	 * getGenerator
90
+	 *
91
+	 * @return string
92
+	 */
93
+	public function getGenerator()
94
+	{
95
+		return $this->_generator;
96
+	}
97
+	/**
98
+	 * getCopyright
99
+	 *
100
+	 * @return string
101
+	 */
102
+	public function getCopyright()
103
+	{
104
+		return $this->_copyright;
105
+	}
106
+	/**
107
+	 * getLastBuildDate
108
+	 *
109
+	 * @return string
110
+	 */
111
+	public function getLastBuildDate()
112
+	{
113
+		return $this->_lastbuilddate;
114
+	}
115
+	/**
116
+	 * getImageUrl
117
+	 *
118
+	 * @return string
119
+	 */
120
+	public function getImageUrl()
121
+	{
122
+		return $this->_imageurl;
123
+	}
124
+	/**
125
+	 * getLink
126
+	 *
127
+	 * @return string
128
+	 */
129
+	public function getLink()
130
+	{
131
+		return $this->_link;
132
+	}
133
+	/**
134
+	 * getTitle
135
+	 *
136
+	 * @return string
137
+	 */
138
+	public function getTitle()
139
+	{
140
+		return $this->_title;
141
+	}
142
+	/**
143
+	 * getDescription
144
+	 *
145
+	 * @return string
146
+	 */
147
+	public function getDescription()
148
+	{
149
+		return $this->_description;
150
+	}
151
+	/**
152
+	 * getLastFetchDate
153
+	 *
154
+	 * @return string
155
+	 */
156
+	public function getLastFetchDate()
157
+	{
158
+		return $this->_lastfetchdate;
159
+	}
160
+	/**
161
+	 * getItems
162
+	 *
163
+	 * @return string
164
+	 */
165
+	public function getItems()
166
+	{
167
+		return $this->_rssarray;
168
+	}
169
+
170
+
171
+	/**
172
+	 * 	Parse rss URL
173
+	 *
174
+	 * 	@param	string	$urlRSS		Url to parse
175
+	 * 	@param	int		$maxNb		Max nb of records to get (0 for no limit)
176
+	 * 	@param	int		$cachedelay	0=No cache, nb of seconds we accept cache files (cachedir must also be defined)
177
+	 * 	@param	string	$cachedir	Directory where to save cache file
178
+	 *	@return	int					<0 if KO, >0 if OK
179
+	 */
180
+	public function parser($urlRSS, $maxNb=0, $cachedelay=60, $cachedir='')
181
+	{
182
+		global $conf;
183
+
184
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
185
+
186
+		$rss='';
187
+		$str='';    // This will contain content of feed
188
+
189
+		// Check parameters
190
+		if (! dol_is_url($urlRSS))
191
+		{
192
+			$this->error="ErrorBadUrl";
193
+			return -1;
194
+		}
195
+
196
+		$this->_urlRSS = $urlRSS;
197
+		$newpathofdestfile=$cachedir.'/'.dol_hash($this->_urlRSS,3);	// Force md5 hash (does not contains special chars)
198
+		$newmask='0644';
199
+
200
+		//dol_syslog("RssPArser::parser parse url=".$urlRSS." => cache file=".$newpathofdestfile);
201
+		$nowgmt = dol_now();
202
+
203
+		// Search into cache
204
+		$foundintocache=0;
205
+		if ($cachedelay > 0 && $cachedir)
206
+		{
207
+			$filedate=dol_filemtime($newpathofdestfile);
208
+			if ($filedate >= ($nowgmt - $cachedelay))
209
+			{
210
+				//dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
211
+				$foundintocache=1;
212
+
213
+				$this->_lastfetchdate=$filedate;
214
+			}
215
+			else
216
+			{
217
+				dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
218
+			}
219
+		}
220
+
221
+		// Load file into $str
222
+		if ($foundintocache)    // Cache file found and is not too old
223
+		{
224
+			$str = file_get_contents($newpathofdestfile);
225
+		}
226
+		else
227
+		{
228
+			try {
229
+				ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
230
+				ini_set("max_execution_time", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
231
+				ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
232
+
233
+				$opts = array('http'=>array('method'=>"GET"));
234
+				if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
235
+				if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
236
+				//var_dump($opts);exit;
237
+				$context = stream_context_create($opts);
238
+
239
+				$str = file_get_contents($this->_urlRSS, false, $context);
240
+			}
241
+			catch (Exception $e) {
242
+				print 'Error retrieving URL '.$this->urlRSS.' - '.$e->getMessage();
243
+			}
244
+		}
245
+
246
+		if ($str !== false)
247
+		{
248
+			// Convert $str into xml
249
+			if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
250
+			{
251
+				//print 'xx'.LIBXML_NOCDATA;
252
+				libxml_use_internal_errors(false);
253
+				$rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
254
+			}
255
+			else
256
+			{
257
+				$xmlparser=xml_parser_create('');
258
+				if (!is_resource($xmlparser)) {
259
+					$this->error="ErrorFailedToCreateParser"; return -1;
260
+				}
261
+
262
+				xml_set_object($xmlparser, $this);
263
+				xml_set_element_handler($xmlparser, 'feed_start_element', 'feed_end_element');
264
+				xml_set_character_data_handler($xmlparser, 'feed_cdata');
265
+				$status = xml_parse($xmlparser, $str);
266
+				xml_parser_free($xmlparser);
267
+				$rss=$this;
268
+				//var_dump($rss->_format);exit;
269
+			}
270
+		}
271
+
272
+		// If $rss loaded
273
+		if ($rss)
274
+		{
275
+			// Save file into cache
276
+			if (empty($foundintocache) && $cachedir)
277
+			{
278
+				dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
279
+				if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
280
+				$fp = fopen($newpathofdestfile, 'w');
281
+				if ($fp)
282
+				{
283
+					fwrite($fp, $str);
284
+					fclose($fp);
285
+					if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
286
+					@chmod($newpathofdestfile, octdec($newmask));
287
+
288
+					$this->_lastfetchdate=$nowgmt;
289
+				}
290
+				else
291
+				{
292
+					print 'Error, failed to open file '.$newpathofdestfile.' for write';
293
+				}
294
+			}
295
+
296
+			unset($str);    // Free memory
297
+
298
+			if (empty($rss->_format))    // If format not detected automatically
299
+			{
300
+				$rss->_format='rss';
301
+				if (empty($rss->channel)) $rss->_format='atom';
302
+			}
303
+
304
+			$items=array();
305
+
306
+			// Save description entries
307
+			if ($rss->_format == 'rss')
308
+			{
309
+				//var_dump($rss);
310
+				if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
311
+				{
312
+					if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
313
+					if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
314
+					if (!empty($rss->channel->copyright))     $this->_copyright = (string) $rss->channel->copyright;
315
+					if (!empty($rss->channel->lastbuilddate)) $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
316
+					if (!empty($rss->channel->image->url[0])) $this->_imageurl = (string) $rss->channel->image->url[0];
317
+					if (!empty($rss->channel->link))		  $this->_link = (string) $rss->channel->link;
318
+					if (!empty($rss->channel->title))         $this->_title = (string) $rss->channel->title;
319
+					if (!empty($rss->channel->description))	  $this->_description = (string) $rss->channel->description;
320
+				}
321
+				else
322
+				{
323
+					//var_dump($rss->channel);
324
+					if (!empty($rss->channel['language']))      $this->_language = (string) $rss->channel['language'];
325
+					if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
326
+					if (!empty($rss->channel['copyright']))     $this->_copyright = (string) $rss->channel['copyright'];
327
+					if (!empty($rss->channel['lastbuilddate'])) $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
328
+					if (!empty($rss->image['url']))             $this->_imageurl = (string) $rss->image['url'];
329
+					if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
330
+					if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
331
+					if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
332
+				}
333
+
334
+				if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
335
+				else $items=$rss->items;                                                              // With xmlparse
336
+				//var_dump($items);exit;
337
+			}
338
+			else if ($rss->_format == 'atom')
339
+			{
340
+				//var_dump($rss);
341
+				if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
342
+				{
343
+					if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
344
+					if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
345
+					if (!empty($rss->link->href))    $this->_link = (string) $rss->link->href;
346
+					if (!empty($rss->title))         $this->_title = (string) $rss->title;
347
+					if (!empty($rss->description))	 $this->_description = (string) $rss->description;
348
+				}
349
+				else
350
+				{
351
+					//if (!empty($rss->channel['rss_language']))      $this->_language = (string) $rss->channel['rss_language'];
352
+					if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
353
+					//if (!empty($rss->channel['rss_copyright']))     $this->_copyright = (string) $rss->channel['rss_copyright'];
354
+					if (!empty($rss->channel['modified'])) $this->_lastbuilddate = (string) $rss->channel['modified'];
355
+					//if (!empty($rss->image['rss_url']))             $this->_imageurl = (string) $rss->image['rss_url'];
356
+					if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
357
+					if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
358
+					//if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
359
+				}
360
+				if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
361
+					$tmprss=xml2php($rss); $items=$tmprss['entry'];
362
+				} // With simplexml
363
+				else $items=$rss->items;                                                              // With xmlparse
364
+				//var_dump($items);exit;
365
+			}
366
+
367
+			$i = 0;
368
+
369
+			// Loop on each record
370
+			if (is_array($items))
371
+			{
372
+				foreach($items as $item)
373
+				{
374
+					//var_dump($item);exit;
375
+					if ($rss->_format == 'rss')
376
+					{
377
+						if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
378
+						{
379
+							$itemLink = (string) $item->link;
380
+							$itemTitle = (string) $item->title;
381
+							$itemDescription = (string) $item->description;
382
+							$itemPubDate = (string) $item->pubDate;
383
+							$itemId = '';
384
+							$itemAuthor = '';
385
+						}
386
+						else
387
+						{
388
+							$itemLink = (string) $item['link'];
389
+							$itemTitle = (string) $item['title'];
390
+							$itemDescription = (string) $item['description'];
391
+							$itemPubDate = (string) $item['pubdate'];
392
+							$itemId = (string) $item['guid'];
393
+							$itemAuthor = (string) $item['author'];
394
+						}
395
+
396
+						// Loop on each category
397
+						$itemCategory=array();
398
+						if (is_array($item->category))
399
+						{
400
+							foreach ($item->category as $cat)
401
+							{
402
+								$itemCategory[] = (string) $cat;
403
+							}
404
+						}
405
+					}
406
+					else if ($rss->_format == 'atom')
407
+					{
408
+						if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
409
+						{
410
+							$itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
411
+							$itemTitle = (string) $item['title'];
412
+							$itemDescription = (string) $item['summary'];
413
+							$itemPubDate = (string) $item['created'];
414
+							$itemId = (string) $item['id'];
415
+							$itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
416
+						}
417
+						else
418
+						{
419
+							$itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
420
+							$itemTitle = (string) $item['title'];
421
+							$itemDescription = (string) $item['summary'];
422
+							$itemPubDate = (string) $item['created'];
423
+							$itemId = (string) $item['id'];
424
+							$itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
425
+						}
426
+					}
427
+					else print 'ErrorBadFeedFormat';
428
+
429
+					// Add record to result array
430
+					$this->_rssarray[$i] = array(
431
+						'link'=>$itemLink,
432
+						'title'=>$itemTitle,
433
+						'description'=>$itemDescription,
434
+						'pubDate'=>$itemPubDate,
435
+						'category'=>$itemCategory,
436
+						'id'=>$itemId,
437
+						'author'=>$itemAuthor);
438
+					//var_dump($this->_rssarray);
439
+
440
+					$i++;
441
+
442
+					if ($i > $maxNb)    break;    // We get all records we want
443
+				}
444
+			}
445
+
446
+			return 1;
447
+		}
448
+		else
449
+		{
450
+			$this->error='ErrorFailedToLoadRSSFile';
451
+			return -1;
452
+		}
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * 	Triggered when opened tag is found
459
+	 *
460
+	 * 	@param	string		$p			Start
461
+	 *  @param	string		$element	Tag
462
+	 *  @param	array		$attrs		Attributes of tags
463
+	 *  @return	void
464
+	 */
465
+	function feed_start_element($p, $element, &$attrs)
466
+	{
467
+		$el = $element = strtolower($element);
468
+		$attrs = array_change_key_case($attrs, CASE_LOWER);
469
+
470
+		// check for a namespace, and split if found
471
+		$ns = false;
472
+		if (strpos($element, ':'))
473
+		{
474
+			list($ns, $el) = explode(':', $element, 2);
475
+		}
476
+		if ( $ns and $ns != 'rdf' )
477
+		{
478
+			$this->current_namespace = $ns;
479
+		}
480
+
481
+		// if feed type isn't set, then this is first element of feed identify feed from root element
482
+		if (empty($this->_format))
483
+		{
484
+			if ( $el == 'rdf' ) {
485
+				$this->_format = 'rss';
486
+				$this->feed_version = '1.0';
487
+			}
488
+			elseif ( $el == 'rss' ) {
489
+				$this->_format = 'rss';
490
+				$this->feed_version = $attrs['version'];
491
+			}
492
+			elseif ( $el == 'feed' ) {
493
+				$this->_format = 'atom';
494
+				$this->feed_version = $attrs['version'];
495
+				$this->inchannel = true;
496
+			}
497
+			return;
498
+		}
499
+
500
+		if ( $el == 'channel' )
501
+		{
502
+			$this->inchannel = true;
503
+		}
504
+		elseif ($el == 'item' or $el == 'entry' )
505
+		{
506
+			$this->initem = true;
507
+			if ( isset($attrs['rdf:about']) ) {
508
+				$this->current_item['about'] = $attrs['rdf:about'];
509
+			}
510
+		}
511
+
512
+		// if we're in the default namespace of an RSS feed,
513
+		//  record textinput or image fields
514
+		elseif (
515
+		$this->_format == 'rss' and
516
+		$this->current_namespace == '' and
517
+		$el == 'textinput' )
518
+		{
519
+			$this->intextinput = true;
520
+		}
521
+
522
+		elseif (
523
+		$this->_format == 'rss' and
524
+		$this->current_namespace == '' and
525
+		$el == 'image' )
526
+		{
527
+			$this->inimage = true;
528
+		}
529
+
530
+		// handle atom content constructs
531
+		elseif ( $this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
532
+		{
533
+			// avoid clashing w/ RSS mod_content
534
+			if ($el == 'content' ) {
535
+				$el = 'atom_content';
536
+			}
537
+
538
+			$this->incontent = $el;
539
+
540
+
541
+		}
542
+
543
+		// if inside an Atom content construct (e.g. content or summary) field treat tags as text
544
+		elseif ($this->_format == 'atom' and $this->incontent )
545
+		{
546
+			// if tags are inlined, then flatten
547
+			$attrs_str = join(' ', array_map('map_attrs', array_keys($attrs), array_values($attrs)));
548
+
549
+			$this->append_content("<$element $attrs_str>");
550
+
551
+			array_unshift($this->stack, $el);
552
+		}
553
+
554
+		// Atom support many links per containging element.
555
+		// Magpie treats link elements of type rel='alternate'
556
+		// as being equivalent to RSS's simple link element.
557
+		//
558
+		elseif ($this->_format == 'atom' and $el == 'link' )
559
+		{
560
+			if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
561
+			{
562
+				$link_el = 'link';
563
+			}
564
+			else {
565
+				$link_el = 'link_' . $attrs['rel'];
566
+			}
567
+
568
+			$this->append($link_el, $attrs['href']);
569
+		}
570
+		// set stack[0] to current element
571
+		else {
572
+			array_unshift($this->stack, $el);
573
+		}
574
+	}
575
+
576
+
577
+	/**
578
+	 * 	Triggered when CDATA is found
579
+	 *
580
+	 * 	@param	string	$p		P
581
+	 *  @param	string	$text	Tag
582
+	 *  @return	void
583
+	 */
584
+	function feed_cdata($p, $text)
585
+	{
586
+		if ($this->_format == 'atom' and $this->incontent)
587
+		{
588
+			$this->append_content($text);
589
+		}
590
+		else
591
+		{
592
+			$current_el = join('_', array_reverse($this->stack));
593
+			$this->append($current_el, $text);
594
+		}
595
+	}
596
+
597
+	/**
598
+	 * 	Triggered when closed tag is found
599
+	 *
600
+	 * 	@param	string		$p		P
601
+	 *  @param	string		$el		Tag
602
+	 *  @return	void
603
+	 */
604
+	function feed_end_element($p, $el)
605
+	{
606
+		$el = strtolower($el);
607
+
608
+		if ($el == 'item' or $el == 'entry')
609
+		{
610
+			$this->items[] = $this->current_item;
611
+			$this->current_item = array();
612
+			$this->initem = false;
613
+		}
614
+		elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
615
+		{
616
+			$this->intextinput = false;
617
+		}
618
+		elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
619
+		{
620
+			$this->inimage = false;
621
+		}
622
+		elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
623
+		{
624
+			$this->incontent = false;
625
+		}
626
+		elseif ($el == 'channel' or $el == 'feed' )
627
+		{
628
+			$this->inchannel = false;
629
+		}
630
+		elseif ($this->_format == 'atom' and $this->incontent  ) {
631
+			// balance tags properly
632
+			// note:  i don't think this is actually neccessary
633
+			if ( $this->stack[0] == $el )
634
+			{
635
+				$this->append_content("</$el>");
636
+			}
637
+			else {
638
+				$this->append_content("<$el />");
639
+			}
640
+
641
+			array_shift($this->stack);
642
+		}
643
+		else {
644
+			array_shift($this->stack);
645
+		}
646
+
647
+		$this->current_namespace = false;
648
+	}
649
+
650
+
651
+	/**
652
+	 * 	To concat 2 string with no warning if an operand is not defined
653
+	 *
654
+	 * 	@param	string	$str1		Str1
655
+	 *  @param	string	$str2		Str2
656
+	 *  @return	string				String cancatenated
657
+	 */
658
+	function concat(&$str1, $str2="")
659
+	{
660
+		if (!isset($str1) ) {
661
+			$str1="";
662
+		}
663
+		$str1 .= $str2;
664
+	}
665
+
666
+	/**
667
+	 * Enter description here ...
668
+	 *
669
+	 * @param	string	$text		Text
670
+	 * @return	void
671
+	 */
672
+	function append_content($text)
673
+	{
674
+		if ( $this->initem ) {
675
+			$this->concat($this->current_item[ $this->incontent ], $text);
676
+		}
677
+		elseif ( $this->inchannel ) {
678
+			$this->concat($this->channel[ $this->incontent ], $text);
679
+		}
680
+	}
681
+
682
+	/**
683
+	 * 	smart append - field and namespace aware
684
+	 *
685
+	 * 	@param	string	$el		El
686
+	 * 	@param	string	$text	Text
687
+	 * 	@return	void
688
+	 */
689
+	function append($el, $text)
690
+	{
691
+		if (!$el) {
692
+			return;
693
+		}
694
+		if ( $this->current_namespace )
695
+		{
696
+			if ( $this->initem ) {
697
+				$this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
698
+			}
699
+			elseif ($this->inchannel) {
700
+				$this->concat($this->channel[ $this->current_namespace][ $el ], $text);
701
+			}
702
+			elseif ($this->intextinput) {
703
+				$this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
704
+			}
705
+			elseif ($this->inimage) {
706
+				$this->concat($this->image[ $this->current_namespace ][ $el ], $text);
707
+			}
708
+		}
709
+		else {
710
+			if ( $this->initem ) {
711
+				$this->concat($this->current_item[ $el ], $text);
712
+			}
713
+			elseif ($this->intextinput) {
714
+				$this->concat($this->textinput[ $el ], $text);
715
+			}
716
+			elseif ($this->inimage) {
717
+				$this->concat($this->image[ $el ], $text);
718
+			}
719
+			elseif ($this->inchannel) {
720
+				$this->concat($this->channel[ $el ], $text);
721
+			}
722
+
723
+		}
724
+	}
725 725
 
726 726
 }
727 727
 
@@ -734,51 +734,51 @@  discard block
 block discarded – undo
734 734
  */
735 735
 function xml2php($xml)
736 736
 {
737
-    $fils = 0;
738
-    $tab = false;
739
-    $array = array();
740
-    foreach($xml->children() as $key => $value)
741
-    {
742
-        $child = xml2php($value);
743
-
744
-        //To deal with the attributes
745
-        foreach($value->attributes() as $ak=>$av)
746
-        {
747
-            $child[$ak] = (string) $av;
748
-
749
-        }
750
-
751
-        //Let see if the new child is not in the array
752
-        if($tab==false && in_array($key,array_keys($array)))
753
-        {
754
-            //If this element is already in the array we will create an indexed array
755
-            $tmp = $array[$key];
756
-            $array[$key] = NULL;
757
-            $array[$key][] = $tmp;
758
-            $array[$key][] = $child;
759
-            $tab = true;
760
-        }
761
-        elseif($tab == true)
762
-        {
763
-            //Add an element in an existing array
764
-            $array[$key][] = $child;
765
-        }
766
-        else
767
-        {
768
-            //Add a simple element
769
-            $array[$key] = $child;
770
-        }
771
-
772
-        $fils++;
773
-    }
774
-
775
-
776
-    if($fils==0)
777
-    {
778
-        return (string) $xml;
779
-    }
780
-
781
-    return $array;
737
+	$fils = 0;
738
+	$tab = false;
739
+	$array = array();
740
+	foreach($xml->children() as $key => $value)
741
+	{
742
+		$child = xml2php($value);
743
+
744
+		//To deal with the attributes
745
+		foreach($value->attributes() as $ak=>$av)
746
+		{
747
+			$child[$ak] = (string) $av;
748
+
749
+		}
750
+
751
+		//Let see if the new child is not in the array
752
+		if($tab==false && in_array($key,array_keys($array)))
753
+		{
754
+			//If this element is already in the array we will create an indexed array
755
+			$tmp = $array[$key];
756
+			$array[$key] = NULL;
757
+			$array[$key][] = $tmp;
758
+			$array[$key][] = $child;
759
+			$tab = true;
760
+		}
761
+		elseif($tab == true)
762
+		{
763
+			//Add an element in an existing array
764
+			$array[$key][] = $child;
765
+		}
766
+		else
767
+		{
768
+			//Add a simple element
769
+			$array[$key] = $child;
770
+		}
771
+
772
+		$fils++;
773
+	}
774
+
775
+
776
+	if($fils==0)
777
+	{
778
+		return (string) $xml;
779
+	}
780
+
781
+	return $array;
782 782
 
783 783
 }
784 784
 
Please login to merge, or discard this patch.
Spacing   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
     var $db;
30 30
     var $error;
31 31
 
32
-    private $_format='';
32
+    private $_format = '';
33 33
     private $_urlRSS;
34 34
     private $_language;
35 35
     private $_generator;
@@ -39,8 +39,8 @@  discard block
 block discarded – undo
39 39
     private $_link;
40 40
     private $_title;
41 41
     private $_description;
42
-    private $_lastfetchdate;    // Last successful fetch
43
-    private $_rssarray=array();
42
+    private $_lastfetchdate; // Last successful fetch
43
+    private $_rssarray = array();
44 44
 
45 45
     // For parsing with xmlparser
46 46
     var $stack               = array(); // parser stack
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
      */
55 55
     public function __construct($db)
56 56
     {
57
-    	$this->db=$db;
57
+    	$this->db = $db;
58 58
     }
59 59
 
60 60
     /**
@@ -177,40 +177,40 @@  discard block
 block discarded – undo
177 177
      * 	@param	string	$cachedir	Directory where to save cache file
178 178
      *	@return	int					<0 if KO, >0 if OK
179 179
      */
180
-    public function parser($urlRSS, $maxNb=0, $cachedelay=60, $cachedir='')
180
+    public function parser($urlRSS, $maxNb = 0, $cachedelay = 60, $cachedir = '')
181 181
     {
182 182
         global $conf;
183 183
 
184 184
         include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
185 185
 
186
-        $rss='';
187
-        $str='';    // This will contain content of feed
186
+        $rss = '';
187
+        $str = ''; // This will contain content of feed
188 188
 
189 189
         // Check parameters
190
-        if (! dol_is_url($urlRSS))
190
+        if (!dol_is_url($urlRSS))
191 191
         {
192
-            $this->error="ErrorBadUrl";
192
+            $this->error = "ErrorBadUrl";
193 193
             return -1;
194 194
         }
195 195
 
196 196
         $this->_urlRSS = $urlRSS;
197
-        $newpathofdestfile=$cachedir.'/'.dol_hash($this->_urlRSS,3);	// Force md5 hash (does not contains special chars)
198
-        $newmask='0644';
197
+        $newpathofdestfile = $cachedir.'/'.dol_hash($this->_urlRSS, 3); // Force md5 hash (does not contains special chars)
198
+        $newmask = '0644';
199 199
 
200 200
         //dol_syslog("RssPArser::parser parse url=".$urlRSS." => cache file=".$newpathofdestfile);
201 201
         $nowgmt = dol_now();
202 202
 
203 203
         // Search into cache
204
-        $foundintocache=0;
204
+        $foundintocache = 0;
205 205
         if ($cachedelay > 0 && $cachedir)
206 206
         {
207
-            $filedate=dol_filemtime($newpathofdestfile);
207
+            $filedate = dol_filemtime($newpathofdestfile);
208 208
             if ($filedate >= ($nowgmt - $cachedelay))
209 209
             {
210 210
                 //dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
211
-                $foundintocache=1;
211
+                $foundintocache = 1;
212 212
 
213
-                $this->_lastfetchdate=$filedate;
213
+                $this->_lastfetchdate = $filedate;
214 214
             }
215 215
             else
216 216
             {
@@ -226,13 +226,13 @@  discard block
 block discarded – undo
226 226
         else
227 227
         {
228 228
             try {
229
-                ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
229
+                ini_set("user_agent", "Dolibarr ERP-CRM RSS reader");
230 230
                 ini_set("max_execution_time", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
231 231
                 ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
232 232
 
233 233
                 $opts = array('http'=>array('method'=>"GET"));
234
-                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
235
-                if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
234
+                if (!empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout'] = $conf->global->MAIN_USE_CONNECT_TIMEOUT;
235
+                if (!empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy'] = 'tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
236 236
                 //var_dump($opts);exit;
237 237
                 $context = stream_context_create($opts);
238 238
 
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
         if ($str !== false)
247 247
         {
248 248
 	        // Convert $str into xml
249
-	        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
249
+	        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
250 250
 	        {
251 251
 	            //print 'xx'.LIBXML_NOCDATA;
252 252
 	            libxml_use_internal_errors(false);
@@ -254,9 +254,9 @@  discard block
 block discarded – undo
254 254
 	        }
255 255
 	        else
256 256
 	        {
257
-	            $xmlparser=xml_parser_create('');
257
+	            $xmlparser = xml_parser_create('');
258 258
 	            if (!is_resource($xmlparser)) {
259
-	                $this->error="ErrorFailedToCreateParser"; return -1;
259
+	                $this->error = "ErrorFailedToCreateParser"; return -1;
260 260
 	            }
261 261
 
262 262
 	            xml_set_object($xmlparser, $this);
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 	            xml_set_character_data_handler($xmlparser, 'feed_cdata');
265 265
 	            $status = xml_parse($xmlparser, $str);
266 266
 	            xml_parser_free($xmlparser);
267
-	            $rss=$this;
267
+	            $rss = $this;
268 268
 	            //var_dump($rss->_format);exit;
269 269
 	        }
270 270
         }
@@ -276,16 +276,16 @@  discard block
 block discarded – undo
276 276
             if (empty($foundintocache) && $cachedir)
277 277
             {
278 278
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
279
-                if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
279
+                if (!dol_is_dir($cachedir)) dol_mkdir($cachedir);
280 280
                 $fp = fopen($newpathofdestfile, 'w');
281 281
                 if ($fp)
282 282
                 {
283 283
                 	fwrite($fp, $str);
284 284
                 	fclose($fp);
285
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
285
+                	if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
286 286
                 	@chmod($newpathofdestfile, octdec($newmask));
287 287
 
288
-	                $this->_lastfetchdate=$nowgmt;
288
+	                $this->_lastfetchdate = $nowgmt;
289 289
                 }
290 290
                 else
291 291
                 {
@@ -293,21 +293,21 @@  discard block
 block discarded – undo
293 293
                 }
294 294
             }
295 295
 
296
-            unset($str);    // Free memory
296
+            unset($str); // Free memory
297 297
 
298 298
             if (empty($rss->_format))    // If format not detected automatically
299 299
             {
300
-                $rss->_format='rss';
301
-                if (empty($rss->channel)) $rss->_format='atom';
300
+                $rss->_format = 'rss';
301
+                if (empty($rss->channel)) $rss->_format = 'atom';
302 302
             }
303 303
 
304
-            $items=array();
304
+            $items = array();
305 305
 
306 306
             // Save description entries
307 307
             if ($rss->_format == 'rss')
308 308
             {
309 309
                 //var_dump($rss);
310
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
310
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
311 311
                 {
312 312
                     if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
313 313
                     if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
@@ -331,14 +331,14 @@  discard block
 block discarded – undo
331 331
                     if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
332 332
                 }
333 333
 
334
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
335
-                else $items=$rss->items;                                                              // With xmlparse
334
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items = $rss->channel->item; // With simplexml
335
+                else $items = $rss->items; // With xmlparse
336 336
                 //var_dump($items);exit;
337 337
             }
338 338
             else if ($rss->_format == 'atom')
339 339
             {
340 340
                 //var_dump($rss);
341
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
341
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
342 342
                 {
343 343
                     if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
344 344
                     if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
@@ -357,10 +357,10 @@  discard block
 block discarded – undo
357 357
                     if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
358 358
                     //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
359 359
                 }
360
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
361
-                    $tmprss=xml2php($rss); $items=$tmprss['entry'];
360
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
361
+                    $tmprss = xml2php($rss); $items = $tmprss['entry'];
362 362
                 } // With simplexml
363
-                else $items=$rss->items;                                                              // With xmlparse
363
+                else $items = $rss->items; // With xmlparse
364 364
                 //var_dump($items);exit;
365 365
             }
366 366
 
@@ -369,12 +369,12 @@  discard block
 block discarded – undo
369 369
             // Loop on each record
370 370
             if (is_array($items))
371 371
             {
372
-                foreach($items as $item)
372
+                foreach ($items as $item)
373 373
                 {
374 374
                     //var_dump($item);exit;
375 375
                     if ($rss->_format == 'rss')
376 376
                     {
377
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
377
+                        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
378 378
                         {
379 379
                             $itemLink = (string) $item->link;
380 380
                             $itemTitle = (string) $item->title;
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
                         }
395 395
 
396 396
                         // Loop on each category
397
-                        $itemCategory=array();
397
+                        $itemCategory = array();
398 398
                         if (is_array($item->category))
399 399
                         {
400 400
                             foreach ($item->category as $cat)
@@ -405,14 +405,14 @@  discard block
 block discarded – undo
405 405
                     }
406 406
                     else if ($rss->_format == 'atom')
407 407
                     {
408
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
408
+                        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
409 409
                         {
410 410
                             $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
411 411
                             $itemTitle = (string) $item['title'];
412 412
                             $itemDescription = (string) $item['summary'];
413 413
                             $itemPubDate = (string) $item['created'];
414 414
                             $itemId = (string) $item['id'];
415
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
415
+                            $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
416 416
                         }
417 417
                         else
418 418
                         {
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
                             $itemDescription = (string) $item['summary'];
422 422
                             $itemPubDate = (string) $item['created'];
423 423
                             $itemId = (string) $item['id'];
424
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
424
+                            $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
425 425
                         }
426 426
                     }
427 427
                     else print 'ErrorBadFeedFormat';
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 
440 440
                     $i++;
441 441
 
442
-                    if ($i > $maxNb)    break;    // We get all records we want
442
+                    if ($i > $maxNb)    break; // We get all records we want
443 443
                 }
444 444
             }
445 445
 
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
         }
448 448
         else
449 449
         {
450
-            $this->error='ErrorFailedToLoadRSSFile';
450
+            $this->error = 'ErrorFailedToLoadRSSFile';
451 451
             return -1;
452 452
         }
453 453
     }
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
         {
474 474
             list($ns, $el) = explode(':', $element, 2);
475 475
         }
476
-        if ( $ns and $ns != 'rdf' )
476
+        if ($ns and $ns != 'rdf')
477 477
         {
478 478
             $this->current_namespace = $ns;
479 479
         }
@@ -481,15 +481,15 @@  discard block
 block discarded – undo
481 481
         // if feed type isn't set, then this is first element of feed identify feed from root element
482 482
         if (empty($this->_format))
483 483
         {
484
-            if ( $el == 'rdf' ) {
484
+            if ($el == 'rdf') {
485 485
                 $this->_format = 'rss';
486 486
                 $this->feed_version = '1.0';
487 487
             }
488
-            elseif ( $el == 'rss' ) {
488
+            elseif ($el == 'rss') {
489 489
                 $this->_format = 'rss';
490 490
                 $this->feed_version = $attrs['version'];
491 491
             }
492
-            elseif ( $el == 'feed' ) {
492
+            elseif ($el == 'feed') {
493 493
                 $this->_format = 'atom';
494 494
                 $this->feed_version = $attrs['version'];
495 495
                 $this->inchannel = true;
@@ -497,14 +497,14 @@  discard block
 block discarded – undo
497 497
             return;
498 498
         }
499 499
 
500
-        if ( $el == 'channel' )
500
+        if ($el == 'channel')
501 501
         {
502 502
             $this->inchannel = true;
503 503
         }
504
-        elseif ($el == 'item' or $el == 'entry' )
504
+        elseif ($el == 'item' or $el == 'entry')
505 505
         {
506 506
             $this->initem = true;
507
-            if ( isset($attrs['rdf:about']) ) {
507
+            if (isset($attrs['rdf:about'])) {
508 508
                 $this->current_item['about'] = $attrs['rdf:about'];
509 509
             }
510 510
         }
@@ -528,10 +528,10 @@  discard block
 block discarded – undo
528 528
         }
529 529
 
530 530
         // handle atom content constructs
531
-        elseif ( $this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
531
+        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
532 532
         {
533 533
             // avoid clashing w/ RSS mod_content
534
-            if ($el == 'content' ) {
534
+            if ($el == 'content') {
535 535
                 $el = 'atom_content';
536 536
             }
537 537
 
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
         }
542 542
 
543 543
         // if inside an Atom content construct (e.g. content or summary) field treat tags as text
544
-        elseif ($this->_format == 'atom' and $this->incontent )
544
+        elseif ($this->_format == 'atom' and $this->incontent)
545 545
         {
546 546
             // if tags are inlined, then flatten
547 547
             $attrs_str = join(' ', array_map('map_attrs', array_keys($attrs), array_values($attrs)));
@@ -555,14 +555,14 @@  discard block
 block discarded – undo
555 555
         // Magpie treats link elements of type rel='alternate'
556 556
         // as being equivalent to RSS's simple link element.
557 557
         //
558
-        elseif ($this->_format == 'atom' and $el == 'link' )
558
+        elseif ($this->_format == 'atom' and $el == 'link')
559 559
         {
560
-            if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
560
+            if (isset($attrs['rel']) && $attrs['rel'] == 'alternate')
561 561
             {
562 562
                 $link_el = 'link';
563 563
             }
564 564
             else {
565
-                $link_el = 'link_' . $attrs['rel'];
565
+                $link_el = 'link_'.$attrs['rel'];
566 566
             }
567 567
 
568 568
             $this->append($link_el, $attrs['href']);
@@ -611,26 +611,26 @@  discard block
 block discarded – undo
611 611
             $this->current_item = array();
612 612
             $this->initem = false;
613 613
         }
614
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
614
+        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput')
615 615
         {
616 616
             $this->intextinput = false;
617 617
         }
618
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
618
+        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image')
619 619
         {
620 620
             $this->inimage = false;
621 621
         }
622
-        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
622
+        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
623 623
         {
624 624
             $this->incontent = false;
625 625
         }
626
-        elseif ($el == 'channel' or $el == 'feed' )
626
+        elseif ($el == 'channel' or $el == 'feed')
627 627
         {
628 628
             $this->inchannel = false;
629 629
         }
630
-        elseif ($this->_format == 'atom' and $this->incontent  ) {
630
+        elseif ($this->_format == 'atom' and $this->incontent) {
631 631
             // balance tags properly
632 632
             // note:  i don't think this is actually neccessary
633
-            if ( $this->stack[0] == $el )
633
+            if ($this->stack[0] == $el)
634 634
             {
635 635
                 $this->append_content("</$el>");
636 636
             }
@@ -655,10 +655,10 @@  discard block
 block discarded – undo
655 655
      *  @param	string	$str2		Str2
656 656
      *  @return	string				String cancatenated
657 657
      */
658
-    function concat(&$str1, $str2="")
658
+    function concat(&$str1, $str2 = "")
659 659
     {
660
-        if (!isset($str1) ) {
661
-            $str1="";
660
+        if (!isset($str1)) {
661
+            $str1 = "";
662 662
         }
663 663
         $str1 .= $str2;
664 664
     }
@@ -671,11 +671,11 @@  discard block
 block discarded – undo
671 671
      */
672 672
     function append_content($text)
673 673
     {
674
-        if ( $this->initem ) {
675
-            $this->concat($this->current_item[ $this->incontent ], $text);
674
+        if ($this->initem) {
675
+            $this->concat($this->current_item[$this->incontent], $text);
676 676
         }
677
-        elseif ( $this->inchannel ) {
678
-            $this->concat($this->channel[ $this->incontent ], $text);
677
+        elseif ($this->inchannel) {
678
+            $this->concat($this->channel[$this->incontent], $text);
679 679
         }
680 680
     }
681 681
 
@@ -691,33 +691,33 @@  discard block
 block discarded – undo
691 691
         if (!$el) {
692 692
             return;
693 693
         }
694
-        if ( $this->current_namespace )
694
+        if ($this->current_namespace)
695 695
         {
696
-            if ( $this->initem ) {
697
-                $this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
696
+            if ($this->initem) {
697
+                $this->concat($this->current_item[$this->current_namespace][$el], $text);
698 698
             }
699 699
             elseif ($this->inchannel) {
700
-                $this->concat($this->channel[ $this->current_namespace][ $el ], $text);
700
+                $this->concat($this->channel[$this->current_namespace][$el], $text);
701 701
             }
702 702
             elseif ($this->intextinput) {
703
-                $this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
703
+                $this->concat($this->textinput[$this->current_namespace][$el], $text);
704 704
             }
705 705
             elseif ($this->inimage) {
706
-                $this->concat($this->image[ $this->current_namespace ][ $el ], $text);
706
+                $this->concat($this->image[$this->current_namespace][$el], $text);
707 707
             }
708 708
         }
709 709
         else {
710
-            if ( $this->initem ) {
711
-                $this->concat($this->current_item[ $el ], $text);
710
+            if ($this->initem) {
711
+                $this->concat($this->current_item[$el], $text);
712 712
             }
713 713
             elseif ($this->intextinput) {
714
-                $this->concat($this->textinput[ $el ], $text);
714
+                $this->concat($this->textinput[$el], $text);
715 715
             }
716 716
             elseif ($this->inimage) {
717
-                $this->concat($this->image[ $el ], $text);
717
+                $this->concat($this->image[$el], $text);
718 718
             }
719 719
             elseif ($this->inchannel) {
720
-                $this->concat($this->channel[ $el ], $text);
720
+                $this->concat($this->channel[$el], $text);
721 721
             }
722 722
 
723 723
         }
@@ -737,19 +737,19 @@  discard block
 block discarded – undo
737 737
     $fils = 0;
738 738
     $tab = false;
739 739
     $array = array();
740
-    foreach($xml->children() as $key => $value)
740
+    foreach ($xml->children() as $key => $value)
741 741
     {
742 742
         $child = xml2php($value);
743 743
 
744 744
         //To deal with the attributes
745
-        foreach($value->attributes() as $ak=>$av)
745
+        foreach ($value->attributes() as $ak=>$av)
746 746
         {
747 747
             $child[$ak] = (string) $av;
748 748
 
749 749
         }
750 750
 
751 751
         //Let see if the new child is not in the array
752
-        if($tab==false && in_array($key,array_keys($array)))
752
+        if ($tab == false && in_array($key, array_keys($array)))
753 753
         {
754 754
             //If this element is already in the array we will create an indexed array
755 755
             $tmp = $array[$key];
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
             $array[$key][] = $child;
759 759
             $tab = true;
760 760
         }
761
-        elseif($tab == true)
761
+        elseif ($tab == true)
762 762
         {
763 763
             //Add an element in an existing array
764 764
             $array[$key][] = $child;
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
     }
774 774
 
775 775
 
776
-    if($fils==0)
776
+    if ($fils == 0)
777 777
     {
778 778
         return (string) $xml;
779 779
     }
Please login to merge, or discard this patch.
Braces   +148 added lines, -107 removed lines patch added patch discarded remove patch
@@ -211,19 +211,19 @@  discard block
 block discarded – undo
211 211
                 $foundintocache=1;
212 212
 
213 213
                 $this->_lastfetchdate=$filedate;
214
-            }
215
-            else
214
+            } else
216 215
             {
217 216
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
218 217
             }
219 218
         }
220 219
 
221 220
         // Load file into $str
222
-        if ($foundintocache)    // Cache file found and is not too old
221
+        if ($foundintocache) {
222
+        	// Cache file found and is not too old
223 223
         {
224 224
             $str = file_get_contents($newpathofdestfile);
225 225
         }
226
-        else
226
+        } else
227 227
         {
228 228
             try {
229 229
                 ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
@@ -231,14 +231,17 @@  discard block
 block discarded – undo
231 231
                 ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
232 232
 
233 233
                 $opts = array('http'=>array('method'=>"GET"));
234
-                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
235
-                if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
234
+                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) {
235
+                	$opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
236
+                }
237
+                if (! empty($conf->global->MAIN_PROXY_USE)) {
238
+                	$opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
239
+                }
236 240
                 //var_dump($opts);exit;
237 241
                 $context = stream_context_create($opts);
238 242
 
239 243
                 $str = file_get_contents($this->_urlRSS, false, $context);
240
-            }
241
-            catch (Exception $e) {
244
+            } catch (Exception $e) {
242 245
                 print 'Error retrieving URL '.$this->urlRSS.' - '.$e->getMessage();
243 246
             }
244 247
         }
@@ -251,8 +254,7 @@  discard block
 block discarded – undo
251 254
 	            //print 'xx'.LIBXML_NOCDATA;
252 255
 	            libxml_use_internal_errors(false);
253 256
 	            $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
254
-	        }
255
-	        else
257
+	        } else
256 258
 	        {
257 259
 	            $xmlparser=xml_parser_create('');
258 260
 	            if (!is_resource($xmlparser)) {
@@ -276,18 +278,21 @@  discard block
 block discarded – undo
276 278
             if (empty($foundintocache) && $cachedir)
277 279
             {
278 280
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
279
-                if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
281
+                if (! dol_is_dir($cachedir)) {
282
+                	dol_mkdir($cachedir);
283
+                }
280 284
                 $fp = fopen($newpathofdestfile, 'w');
281 285
                 if ($fp)
282 286
                 {
283 287
                 	fwrite($fp, $str);
284 288
                 	fclose($fp);
285
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
289
+                	if (! empty($conf->global->MAIN_UMASK)) {
290
+                		$newmask=$conf->global->MAIN_UMASK;
291
+                	}
286 292
                 	@chmod($newpathofdestfile, octdec($newmask));
287 293
 
288 294
 	                $this->_lastfetchdate=$nowgmt;
289
-                }
290
-                else
295
+                } else
291 296
                 {
292 297
                 	print 'Error, failed to open file '.$newpathofdestfile.' for write';
293 298
                 }
@@ -295,10 +300,14 @@  discard block
 block discarded – undo
295 300
 
296 301
             unset($str);    // Free memory
297 302
 
298
-            if (empty($rss->_format))    // If format not detected automatically
303
+            if (empty($rss->_format)) {
304
+            	// If format not detected automatically
299 305
             {
300 306
                 $rss->_format='rss';
301
-                if (empty($rss->channel)) $rss->_format='atom';
307
+            }
308
+                if (empty($rss->channel)) {
309
+                	$rss->_format='atom';
310
+                }
302 311
             }
303 312
 
304 313
             $items=array();
@@ -309,58 +318,114 @@  discard block
 block discarded – undo
309 318
                 //var_dump($rss);
310 319
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
311 320
                 {
312
-                    if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
313
-                    if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
314
-                    if (!empty($rss->channel->copyright))     $this->_copyright = (string) $rss->channel->copyright;
315
-                    if (!empty($rss->channel->lastbuilddate)) $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
316
-                    if (!empty($rss->channel->image->url[0])) $this->_imageurl = (string) $rss->channel->image->url[0];
317
-                    if (!empty($rss->channel->link))		  $this->_link = (string) $rss->channel->link;
318
-                    if (!empty($rss->channel->title))         $this->_title = (string) $rss->channel->title;
319
-                    if (!empty($rss->channel->description))	  $this->_description = (string) $rss->channel->description;
320
-                }
321
-                else
321
+                    if (!empty($rss->channel->language)) {
322
+                    	$this->_language = (string) $rss->channel->language;
323
+                    }
324
+                    if (!empty($rss->channel->generator)) {
325
+                    	$this->_generator = (string) $rss->channel->generator;
326
+                    }
327
+                    if (!empty($rss->channel->copyright)) {
328
+                    	$this->_copyright = (string) $rss->channel->copyright;
329
+                    }
330
+                    if (!empty($rss->channel->lastbuilddate)) {
331
+                    	$this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
332
+                    }
333
+                    if (!empty($rss->channel->image->url[0])) {
334
+                    	$this->_imageurl = (string) $rss->channel->image->url[0];
335
+                    }
336
+                    if (!empty($rss->channel->link)) {
337
+                    	$this->_link = (string) $rss->channel->link;
338
+                    }
339
+                    if (!empty($rss->channel->title)) {
340
+                    	$this->_title = (string) $rss->channel->title;
341
+                    }
342
+                    if (!empty($rss->channel->description)) {
343
+                    	$this->_description = (string) $rss->channel->description;
344
+                    }
345
+                } else
322 346
                 {
323 347
                     //var_dump($rss->channel);
324
-                    if (!empty($rss->channel['language']))      $this->_language = (string) $rss->channel['language'];
325
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
326
-                    if (!empty($rss->channel['copyright']))     $this->_copyright = (string) $rss->channel['copyright'];
327
-                    if (!empty($rss->channel['lastbuilddate'])) $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
328
-                    if (!empty($rss->image['url']))             $this->_imageurl = (string) $rss->image['url'];
329
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
330
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
331
-                    if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
348
+                    if (!empty($rss->channel['language'])) {
349
+                    	$this->_language = (string) $rss->channel['language'];
350
+                    }
351
+                    if (!empty($rss->channel['generator'])) {
352
+                    	$this->_generator = (string) $rss->channel['generator'];
353
+                    }
354
+                    if (!empty($rss->channel['copyright'])) {
355
+                    	$this->_copyright = (string) $rss->channel['copyright'];
356
+                    }
357
+                    if (!empty($rss->channel['lastbuilddate'])) {
358
+                    	$this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
359
+                    }
360
+                    if (!empty($rss->image['url'])) {
361
+                    	$this->_imageurl = (string) $rss->image['url'];
362
+                    }
363
+                    if (!empty($rss->channel['link'])) {
364
+                    	$this->_link = (string) $rss->channel['link'];
365
+                    }
366
+                    if (!empty($rss->channel['title'])) {
367
+                    	$this->_title = (string) $rss->channel['title'];
368
+                    }
369
+                    if (!empty($rss->channel['description'])) {
370
+                    	$this->_description = (string) $rss->channel['description'];
371
+                    }
332 372
                 }
333 373
 
334
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
335
-                else $items=$rss->items;                                                              // With xmlparse
374
+                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
375
+                	$items=$rss->channel->item;
376
+                }
377
+                // With simplexml
378
+                else {
379
+                	$items=$rss->items;
380
+                }
381
+                // With xmlparse
336 382
                 //var_dump($items);exit;
337
-            }
338
-            else if ($rss->_format == 'atom')
383
+            } else if ($rss->_format == 'atom')
339 384
             {
340 385
                 //var_dump($rss);
341 386
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
342 387
                 {
343
-                    if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
344
-                    if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
345
-                    if (!empty($rss->link->href))    $this->_link = (string) $rss->link->href;
346
-                    if (!empty($rss->title))         $this->_title = (string) $rss->title;
347
-                    if (!empty($rss->description))	 $this->_description = (string) $rss->description;
348
-                }
349
-                else
388
+                    if (!empty($rss->generator)) {
389
+                    	$this->_generator = (string) $rss->generator;
390
+                    }
391
+                    if (!empty($rss->lastbuilddate)) {
392
+                    	$this->_lastbuilddate = (string) $rss->modified;
393
+                    }
394
+                    if (!empty($rss->link->href)) {
395
+                    	$this->_link = (string) $rss->link->href;
396
+                    }
397
+                    if (!empty($rss->title)) {
398
+                    	$this->_title = (string) $rss->title;
399
+                    }
400
+                    if (!empty($rss->description)) {
401
+                    	$this->_description = (string) $rss->description;
402
+                    }
403
+                } else
350 404
                 {
351 405
                     //if (!empty($rss->channel['rss_language']))      $this->_language = (string) $rss->channel['rss_language'];
352
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
406
+                    if (!empty($rss->channel['generator'])) {
407
+                    	$this->_generator = (string) $rss->channel['generator'];
408
+                    }
353 409
                     //if (!empty($rss->channel['rss_copyright']))     $this->_copyright = (string) $rss->channel['rss_copyright'];
354
-                    if (!empty($rss->channel['modified'])) $this->_lastbuilddate = (string) $rss->channel['modified'];
410
+                    if (!empty($rss->channel['modified'])) {
411
+                    	$this->_lastbuilddate = (string) $rss->channel['modified'];
412
+                    }
355 413
                     //if (!empty($rss->image['rss_url']))             $this->_imageurl = (string) $rss->image['rss_url'];
356
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
357
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
414
+                    if (!empty($rss->channel['link'])) {
415
+                    	$this->_link = (string) $rss->channel['link'];
416
+                    }
417
+                    if (!empty($rss->channel['title'])) {
418
+                    	$this->_title = (string) $rss->channel['title'];
419
+                    }
358 420
                     //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
359 421
                 }
360 422
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
361 423
                     $tmprss=xml2php($rss); $items=$tmprss['entry'];
362 424
                 } // With simplexml
363
-                else $items=$rss->items;                                                              // With xmlparse
425
+                else {
426
+                	$items=$rss->items;
427
+                }
428
+                // With xmlparse
364 429
                 //var_dump($items);exit;
365 430
             }
366 431
 
@@ -382,8 +447,7 @@  discard block
 block discarded – undo
382 447
                             $itemPubDate = (string) $item->pubDate;
383 448
                             $itemId = '';
384 449
                             $itemAuthor = '';
385
-                        }
386
-                        else
450
+                        } else
387 451
                         {
388 452
                             $itemLink = (string) $item['link'];
389 453
                             $itemTitle = (string) $item['title'];
@@ -402,8 +466,7 @@  discard block
 block discarded – undo
402 466
                                 $itemCategory[] = (string) $cat;
403 467
                             }
404 468
                         }
405
-                    }
406
-                    else if ($rss->_format == 'atom')
469
+                    } else if ($rss->_format == 'atom')
407 470
                     {
408 471
                         if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
409 472
                         {
@@ -413,8 +476,7 @@  discard block
 block discarded – undo
413 476
                             $itemPubDate = (string) $item['created'];
414 477
                             $itemId = (string) $item['id'];
415 478
                             $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
416
-                        }
417
-                        else
479
+                        } else
418 480
                         {
419 481
                             $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
420 482
                             $itemTitle = (string) $item['title'];
@@ -423,8 +485,9 @@  discard block
 block discarded – undo
423 485
                             $itemId = (string) $item['id'];
424 486
                             $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
425 487
                         }
488
+                    } else {
489
+                    	print 'ErrorBadFeedFormat';
426 490
                     }
427
-                    else print 'ErrorBadFeedFormat';
428 491
 
429 492
                     // Add record to result array
430 493
                     $this->_rssarray[$i] = array(
@@ -439,13 +502,15 @@  discard block
 block discarded – undo
439 502
 
440 503
                     $i++;
441 504
 
442
-                    if ($i > $maxNb)    break;    // We get all records we want
505
+                    if ($i > $maxNb) {
506
+                    	break;
507
+                    }
508
+                    // We get all records we want
443 509
                 }
444 510
             }
445 511
 
446 512
             return 1;
447
-        }
448
-        else
513
+        } else
449 514
         {
450 515
             $this->error='ErrorFailedToLoadRSSFile';
451 516
             return -1;
@@ -484,12 +549,10 @@  discard block
 block discarded – undo
484 549
             if ( $el == 'rdf' ) {
485 550
                 $this->_format = 'rss';
486 551
                 $this->feed_version = '1.0';
487
-            }
488
-            elseif ( $el == 'rss' ) {
552
+            } elseif ( $el == 'rss' ) {
489 553
                 $this->_format = 'rss';
490 554
                 $this->feed_version = $attrs['version'];
491
-            }
492
-            elseif ( $el == 'feed' ) {
555
+            } elseif ( $el == 'feed' ) {
493 556
                 $this->_format = 'atom';
494 557
                 $this->feed_version = $attrs['version'];
495 558
                 $this->inchannel = true;
@@ -500,8 +563,7 @@  discard block
 block discarded – undo
500 563
         if ( $el == 'channel' )
501 564
         {
502 565
             $this->inchannel = true;
503
-        }
504
-        elseif ($el == 'item' or $el == 'entry' )
566
+        } elseif ($el == 'item' or $el == 'entry' )
505 567
         {
506 568
             $this->initem = true;
507 569
             if ( isset($attrs['rdf:about']) ) {
@@ -517,9 +579,7 @@  discard block
 block discarded – undo
517 579
         $el == 'textinput' )
518 580
         {
519 581
             $this->intextinput = true;
520
-        }
521
-
522
-        elseif (
582
+        } elseif (
523 583
         $this->_format == 'rss' and
524 584
         $this->current_namespace == '' and
525 585
         $el == 'image' )
@@ -560,8 +620,7 @@  discard block
 block discarded – undo
560 620
             if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
561 621
             {
562 622
                 $link_el = 'link';
563
-            }
564
-            else {
623
+            } else {
565 624
                 $link_el = 'link_' . $attrs['rel'];
566 625
             }
567 626
 
@@ -586,8 +645,7 @@  discard block
 block discarded – undo
586 645
         if ($this->_format == 'atom' and $this->incontent)
587 646
         {
588 647
             $this->append_content($text);
589
-        }
590
-        else
648
+        } else
591 649
         {
592 650
             $current_el = join('_', array_reverse($this->stack));
593 651
             $this->append($current_el, $text);
@@ -610,37 +668,30 @@  discard block
 block discarded – undo
610 668
             $this->items[] = $this->current_item;
611 669
             $this->current_item = array();
612 670
             $this->initem = false;
613
-        }
614
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
671
+        } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
615 672
         {
616 673
             $this->intextinput = false;
617
-        }
618
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
674
+        } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
619 675
         {
620 676
             $this->inimage = false;
621
-        }
622
-        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
677
+        } elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
623 678
         {
624 679
             $this->incontent = false;
625
-        }
626
-        elseif ($el == 'channel' or $el == 'feed' )
680
+        } elseif ($el == 'channel' or $el == 'feed' )
627 681
         {
628 682
             $this->inchannel = false;
629
-        }
630
-        elseif ($this->_format == 'atom' and $this->incontent  ) {
683
+        } elseif ($this->_format == 'atom' and $this->incontent  ) {
631 684
             // balance tags properly
632 685
             // note:  i don't think this is actually neccessary
633 686
             if ( $this->stack[0] == $el )
634 687
             {
635 688
                 $this->append_content("</$el>");
636
-            }
637
-            else {
689
+            } else {
638 690
                 $this->append_content("<$el />");
639 691
             }
640 692
 
641 693
             array_shift($this->stack);
642
-        }
643
-        else {
694
+        } else {
644 695
             array_shift($this->stack);
645 696
         }
646 697
 
@@ -673,8 +724,7 @@  discard block
 block discarded – undo
673 724
     {
674 725
         if ( $this->initem ) {
675 726
             $this->concat($this->current_item[ $this->incontent ], $text);
676
-        }
677
-        elseif ( $this->inchannel ) {
727
+        } elseif ( $this->inchannel ) {
678 728
             $this->concat($this->channel[ $this->incontent ], $text);
679 729
         }
680 730
     }
@@ -695,28 +745,21 @@  discard block
 block discarded – undo
695 745
         {
696 746
             if ( $this->initem ) {
697 747
                 $this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
698
-            }
699
-            elseif ($this->inchannel) {
748
+            } elseif ($this->inchannel) {
700 749
                 $this->concat($this->channel[ $this->current_namespace][ $el ], $text);
701
-            }
702
-            elseif ($this->intextinput) {
750
+            } elseif ($this->intextinput) {
703 751
                 $this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
704
-            }
705
-            elseif ($this->inimage) {
752
+            } elseif ($this->inimage) {
706 753
                 $this->concat($this->image[ $this->current_namespace ][ $el ], $text);
707 754
             }
708
-        }
709
-        else {
755
+        } else {
710 756
             if ( $this->initem ) {
711 757
                 $this->concat($this->current_item[ $el ], $text);
712
-            }
713
-            elseif ($this->intextinput) {
758
+            } elseif ($this->intextinput) {
714 759
                 $this->concat($this->textinput[ $el ], $text);
715
-            }
716
-            elseif ($this->inimage) {
760
+            } elseif ($this->inimage) {
717 761
                 $this->concat($this->image[ $el ], $text);
718
-            }
719
-            elseif ($this->inchannel) {
762
+            } elseif ($this->inchannel) {
720 763
                 $this->concat($this->channel[ $el ], $text);
721 764
             }
722 765
 
@@ -757,13 +800,11 @@  discard block
 block discarded – undo
757 800
             $array[$key][] = $tmp;
758 801
             $array[$key][] = $child;
759 802
             $tab = true;
760
-        }
761
-        elseif($tab == true)
803
+        } elseif($tab == true)
762 804
         {
763 805
             //Add an element in an existing array
764 806
             $array[$key][] = $child;
765
-        }
766
-        else
807
+        } else
767 808
         {
768 809
             //Add a simple element
769 810
             $array[$key] = $child;
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   +178 added lines, -178 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;
@@ -873,7 +873,7 @@  discard block
 block discarded – undo
873 873
 	{
874 874
 		$sql = "DROP TABLE ".$table;
875 875
 
876
-		if (! $this->query($sql))
876
+		if (!$this->query($sql))
877 877
 			return -1;
878 878
 		else
879 879
 			return 1;
@@ -886,9 +886,9 @@  discard block
 block discarded – undo
886 886
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
887 887
 	 *	@return	false|resource|true	Resource
888 888
 	 */
889
-	function DDLDescTable($table,$field="")
889
+	function DDLDescTable($table, $field = "")
890 890
 	{
891
-		$sql="DESC ".$table." ".$field;
891
+		$sql = "DESC ".$table." ".$field;
892 892
 
893 893
 		dol_syslog($sql);
894 894
 		$this->_results = $this->query($sql);
@@ -904,28 +904,28 @@  discard block
 block discarded – undo
904 904
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
905 905
 	 *	@return	int							<0 if KO, >0 if OK
906 906
 	 */
907
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
907
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
908 908
 	{
909 909
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
910 910
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
911
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
911
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
912 912
 		$sql .= $field_desc['type'];
913
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
913
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
914 914
 		$sql  .= "(".$field_desc['value'].")";
915
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
915
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
916 916
 		$sql  .= " ".$field_desc['attribute'];
917
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
917
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
918 918
 		$sql  .= " ".$field_desc['null'];
919
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
920
-		if(preg_match("/null/i",$field_desc['default']))
919
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
920
+		if (preg_match("/null/i", $field_desc['default']))
921 921
 		$sql  .= " default ".$field_desc['default'];
922 922
 		else
923 923
 		$sql  .= " default '".$field_desc['default']."'";
924
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
924
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
925 925
 		$sql  .= " ".$field_desc['extra'];
926 926
 		$sql .= " ".$field_position;
927 927
 
928
-		if(! $this -> query($sql))
928
+		if (!$this -> query($sql))
929 929
 		return -1;
930 930
 		else
931 931
 		return 1;
@@ -939,16 +939,16 @@  discard block
 block discarded – undo
939 939
 	 *	@param	string	$field_desc 		Array with description of field format
940 940
 	 *	@return	int							<0 if KO, >0 if OK
941 941
 	 */
942
-	function DDLUpdateField($table,$field_name,$field_desc)
942
+	function DDLUpdateField($table, $field_name, $field_desc)
943 943
 	{
944 944
 		$sql = "ALTER TABLE ".$table;
945 945
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
946 946
 		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
947
-			$sql.="(".$field_desc['value'].")";
947
+			$sql .= "(".$field_desc['value'].")";
948 948
 		}
949 949
 
950
-		dol_syslog($sql,LOG_DEBUG);
951
-		if (! $this->query($sql))
950
+		dol_syslog($sql, LOG_DEBUG);
951
+		if (!$this->query($sql))
952 952
 		return -1;
953 953
 		else
954 954
 		return 1;
@@ -961,13 +961,13 @@  discard block
 block discarded – undo
961 961
 	 *	@param	string	$field_name 	Name of field to drop
962 962
 	 *	@return	int						<0 if KO, >0 if OK
963 963
 	 */
964
-	function DDLDropField($table,$field_name)
964
+	function DDLDropField($table, $field_name)
965 965
 	{
966
-		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
967
-		dol_syslog($sql,LOG_DEBUG);
968
-		if (! $this->query($sql))
966
+		$sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
967
+		dol_syslog($sql, LOG_DEBUG);
968
+		if (!$this->query($sql))
969 969
 		{
970
-			$this->error=$this->lasterror();
970
+			$this->error = $this->lasterror();
971 971
 			return -1;
972 972
 		}
973 973
 		else return 1;
@@ -982,12 +982,12 @@  discard block
 block discarded – undo
982 982
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
983 983
 	 *	@return	int									<0 if KO, >=0 if OK
984 984
 	 */
985
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
985
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
986 986
 	{
987 987
 	    $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
988
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
989
-        $resql=$this->query($sql);
990
-        if (! $resql)
988
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
989
+        $resql = $this->query($sql);
990
+        if (!$resql)
991 991
         {
992 992
             if ($this->lasterrno != '15025')
993 993
             {
@@ -999,9 +999,9 @@  discard block
 block discarded – undo
999 999
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1000 1000
             }
1001 1001
         }
1002
-        $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1003
-        $ressql=$this->query($sql);
1004
-        if (! $ressql)
1002
+        $sql = "SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
1003
+        $ressql = $this->query($sql);
1004
+        if (!$ressql)
1005 1005
         {
1006 1006
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1007 1007
             return -1;
@@ -1011,9 +1011,9 @@  discard block
 block discarded – undo
1011 1011
             if ($num)
1012 1012
             {
1013 1013
                 $this->select_db($dolibarr_main_db_name);
1014
-                $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1014
+                $sql = "CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
1015 1015
                 $this->query($sql);
1016
-                $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1016
+                $sql = "ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
1017 1017
                 $this->query($sql);
1018 1018
             }
1019 1019
         }
@@ -1053,12 +1053,12 @@  discard block
 block discarded – undo
1053 1053
 	 */
1054 1054
 	function getDefaultCollationDatabase()
1055 1055
 	{
1056
-		$resql=$this->query("SELECT SERVERPROPERTY('collation')");
1056
+		$resql = $this->query("SELECT SERVERPROPERTY('collation')");
1057 1057
 		if (!$resql)
1058 1058
 		{
1059 1059
 			return $this->forcecollate;
1060 1060
 		}
1061
-		$liste=$this->fetch_array($resql);
1061
+		$liste = $this->fetch_array($resql);
1062 1062
 		return $liste['computed'];
1063 1063
 	}
1064 1064
 
@@ -1107,13 +1107,13 @@  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 getServerParametersValues($filter='')
1110
+	function getServerParametersValues($filter = '')
1111 1111
 	{
1112 1112
 		// FIXME: Dummy method
1113 1113
 		// TODO: Implement
1114 1114
 		// May help: SELECT SERVERPROPERTY
1115 1115
 
1116
-		$result=array();
1116
+		$result = array();
1117 1117
 		return $result;
1118 1118
 	}
1119 1119
 
@@ -1123,7 +1123,7 @@  discard block
 block discarded – undo
1123 1123
 	 * @param	string	$filter		Filter list on a particular value
1124 1124
 	 * @return  array				Array of key-values (key=>value)
1125 1125
 	 */
1126
-	function getServerStatusValues($filter='')
1126
+	function getServerStatusValues($filter = '')
1127 1127
 	{
1128 1128
 		// FIXME: Dummy method
1129 1129
 		// TODO: Implement
@@ -1150,23 +1150,23 @@  discard block
 block discarded – undo
1150 1150
 	 * @param      mixed   $fields     String for one field or array of string for multiple field
1151 1151
 	 * @return false|object
1152 1152
 	 */
1153
-	function GetFieldInformation($table,$fields) {
1154
-	    $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1153
+	function GetFieldInformation($table, $fields) {
1154
+	    $sql = "SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
1155 1155
 	    if (is_array($fields))
1156 1156
 	    {
1157
-	        $where=" IN ('".implode("','",$fields)."')";
1157
+	        $where = " IN ('".implode("','", $fields)."')";
1158 1158
 	    }
1159 1159
 	    else
1160 1160
 	    {
1161
-	        $where="='".$this->escape($fields)."'";
1161
+	        $where = "='".$this->escape($fields)."'";
1162 1162
 	    }
1163
-	    $result=array();
1164
-	    $ret=mssql_query($sql.$where,$this->db);
1163
+	    $result = array();
1164
+	    $ret = mssql_query($sql.$where, $this->db);
1165 1165
 	    if ($ret)
1166 1166
 	    {
1167
-	        while($obj=mssql_fetch_object($ret))
1167
+	        while ($obj = mssql_fetch_object($ret))
1168 1168
 	        {
1169
-	            $result[]=$obj;
1169
+	            $result[] = $obj;
1170 1170
 	        }
1171 1171
 	    }
1172 1172
 	    else
Please login to merge, or discard this patch.
Braces   +107 added lines, -93 removed lines patch added patch discarded remove patch
@@ -90,8 +90,7 @@  discard block
 block discarded – undo
90 90
 			// (La base Dolibarr a ete forcee en this->forcecharset a l'install)
91 91
 			$this->connected = true;
92 92
 			$this->ok = true;
93
-		}
94
-		else
93
+		} else
95 94
 		{
96 95
 			// host, login ou password incorrect
97 96
 			$this->connected = false;
@@ -108,8 +107,7 @@  discard block
 block discarded – undo
108 107
 				$this->database_selected = true;
109 108
 				$this->database_name = $name;
110 109
 				$this->ok = true;
111
-			}
112
-			else
110
+			} else
113 111
 			{
114 112
 				$this->database_selected = false;
115 113
 				$this->database_name = '';
@@ -117,8 +115,7 @@  discard block
 block discarded – undo
117 115
 				$this->error=$this->error();
118 116
 				dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
119 117
 			}
120
-		}
121
-		else
118
+		} else
122 119
 		{
123 120
 			// Pas de selection de base demandee, ok ou ko
124 121
 			$this->database_selected = false;
@@ -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
 	/**
@@ -873,10 +881,11 @@  discard block
 block discarded – undo
873 881
 	{
874 882
 		$sql = "DROP TABLE ".$table;
875 883
 
876
-		if (! $this->query($sql))
877
-			return -1;
878
-		else
879
-			return 1;
884
+		if (! $this->query($sql)) {
885
+					return -1;
886
+		} else {
887
+					return 1;
888
+		}
880 889
 	}
881 890
 
882 891
 	/**
@@ -910,25 +919,31 @@  discard block
 block discarded – undo
910 919
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
911 920
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
912 921
 		$sql .= $field_desc['type'];
913
-		if( preg_match("/^[^\s]/i",$field_desc['value']))
914
-		$sql  .= "(".$field_desc['value'].")";
915
-		if( preg_match("/^[^\s]/i",$field_desc['attribute']))
916
-		$sql  .= " ".$field_desc['attribute'];
917
-		if( preg_match("/^[^\s]/i",$field_desc['null']))
918
-		$sql  .= " ".$field_desc['null'];
919
-		if( preg_match("/^[^\s]/i",$field_desc['default']))
920
-		if(preg_match("/null/i",$field_desc['default']))
922
+		if( preg_match("/^[^\s]/i",$field_desc['value'])) {
923
+				$sql  .= "(".$field_desc['value'].")";
924
+		}
925
+		if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
926
+				$sql  .= " ".$field_desc['attribute'];
927
+		}
928
+		if( preg_match("/^[^\s]/i",$field_desc['null'])) {
929
+				$sql  .= " ".$field_desc['null'];
930
+		}
931
+		if( preg_match("/^[^\s]/i",$field_desc['default'])) {
932
+				if(preg_match("/null/i",$field_desc['default']))
921 933
 		$sql  .= " default ".$field_desc['default'];
922
-		else
923
-		$sql  .= " default '".$field_desc['default']."'";
924
-		if( preg_match("/^[^\s]/i",$field_desc['extra']))
925
-		$sql  .= " ".$field_desc['extra'];
934
+		} else {
935
+				$sql  .= " default '".$field_desc['default']."'";
936
+		}
937
+		if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
938
+				$sql  .= " ".$field_desc['extra'];
939
+		}
926 940
 		$sql .= " ".$field_position;
927 941
 
928
-		if(! $this -> query($sql))
929
-		return -1;
930
-		else
931
-		return 1;
942
+		if(! $this -> query($sql)) {
943
+				return -1;
944
+		} else {
945
+				return 1;
946
+		}
932 947
 	}
933 948
 
934 949
 	/**
@@ -948,10 +963,11 @@  discard block
 block discarded – undo
948 963
 		}
949 964
 
950 965
 		dol_syslog($sql,LOG_DEBUG);
951
-		if (! $this->query($sql))
952
-		return -1;
953
-		else
954
-		return 1;
966
+		if (! $this->query($sql)) {
967
+				return -1;
968
+		} else {
969
+				return 1;
970
+		}
955 971
 	}
956 972
 
957 973
 	/**
@@ -969,8 +985,9 @@  discard block
 block discarded – undo
969 985
 		{
970 986
 			$this->error=$this->lasterror();
971 987
 			return -1;
988
+		} else {
989
+			return 1;
972 990
 		}
973
-		else return 1;
974 991
 	}
975 992
 
976 993
 	/**
@@ -992,8 +1009,7 @@  discard block
 block discarded – undo
992 1009
             if ($this->lasterrno != '15025')
993 1010
             {
994 1011
 	            return -1;
995
-            }
996
-            else
1012
+            } else
997 1013
 			{
998 1014
             	// If user already exists, we continue to set permissions
999 1015
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -1005,8 +1021,7 @@  discard block
 block discarded – undo
1005 1021
         {
1006 1022
             dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1007 1023
             return -1;
1008
-        }
1009
-        else
1024
+        } else
1010 1025
         {
1011 1026
             if ($num)
1012 1027
             {
@@ -1155,8 +1170,7 @@  discard block
 block discarded – undo
1155 1170
 	    if (is_array($fields))
1156 1171
 	    {
1157 1172
 	        $where=" IN ('".implode("','",$fields)."')";
1158
-	    }
1159
-	    else
1173
+	    } else
1160 1174
 	    {
1161 1175
 	        $where="='".$this->escape($fields)."'";
1162 1176
 	    }
@@ -1168,9 +1182,9 @@  discard block
 block discarded – undo
1168 1182
 	        {
1169 1183
 	            $result[]=$obj;
1170 1184
 	        }
1185
+	    } else {
1186
+	    	        return false;
1171 1187
 	    }
1172
-	    else
1173
-	        return false;
1174 1188
 
1175 1189
 	    return $result;
1176 1190
 	}
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.
Spacing   +180 added lines, -180 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,16 +110,16 @@  discard block
 block discarded – undo
110 110
                 $this->ok = true;
111 111
 
112 112
                 // If client is old latin, we force utf8
113
-                $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
113
+                $clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
114
+                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
115 115
 
116 116
 				if ($this->db->character_set_name() != $clientmustbe) {
117
-					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
117
+					$this->db->set_charset($clientmustbe); // This set charset, but with a bad collation
118 118
 
119 119
 					$collation = $conf->db->dolibarr_main_db_collation;
120
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
120
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
121 121
 
122
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
122
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
123 123
 				}
124 124
             }
125 125
             else
@@ -127,8 +127,8 @@  discard block
 block discarded – undo
127 127
                 $this->database_selected = false;
128 128
                 $this->database_name = '';
129 129
                 $this->ok = false;
130
-                $this->error=$this->error();
131
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
130
+                $this->error = $this->error();
131
+                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error, LOG_ERR);
132 132
             }
133 133
         }
134 134
         else
@@ -139,16 +139,16 @@  discard block
 block discarded – undo
139 139
             if ($this->connected)
140 140
             {
141 141
             	// If client is old latin, we force utf8
142
-            	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
142
+            	$clientmustbe = empty($conf->db->dolibarr_main_db_character_set) ? 'utf8' : $conf->db->dolibarr_main_db_character_set;
143
+            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe = 'utf8';
144 144
 
145 145
 				if ($this->db->character_set_name() != $clientmustbe) {
146
-					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
146
+					$this->db->set_charset($clientmustbe); // This set utf8_general_ci
147 147
 
148 148
 					$collation = $conf->db->dolibarr_main_db_collation;
149
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
149
+					if (preg_match('/latin1/', $collation)) $collation = 'utf8_unicode_ci';
150 150
 
151
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
151
+					if (!preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
152 152
 				}
153 153
 			}
154 154
         }
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
      *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
163 163
      *  @return    string   		SQL request line converted
164 164
      */
165
-    static function convertSQLFromMysql($line,$type='ddl')
165
+    static function convertSQLFromMysql($line, $type = 'ddl')
166 166
     {
167 167
         return $line;
168 168
     }
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 	 */
194 194
 	function connect($host, $login, $passwd, $name, $port = 0)
195 195
 	{
196
-		dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
196
+		dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
197 197
 
198 198
 		// Can also be
199 199
 		// mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
@@ -232,8 +232,8 @@  discard block
 block discarded – undo
232 232
     {
233 233
         if ($this->db)
234 234
         {
235
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
236
-            $this->connected=false;
235
+	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
236
+            $this->connected = false;
237 237
             return $this->db->close();
238 238
         }
239 239
         return false;
@@ -248,15 +248,15 @@  discard block
 block discarded – undo
248 248
      *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
249 249
      *	@return	bool|mysqli_result		Resultset of answer
250 250
      */
251
-    function query($query,$usesavepoint=0,$type='auto')
251
+    function query($query, $usesavepoint = 0, $type = 'auto')
252 252
     {
253 253
     	global $conf;
254 254
 
255 255
         $query = trim($query);
256 256
 
257
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
257
+	    if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
258 258
 
259
-        if (! $this->database_name)
259
+        if (!$this->database_name)
260 260
         {
261 261
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
262 262
             $ret = $this->db->query($query);
@@ -266,19 +266,19 @@  discard block
 block discarded – undo
266 266
             $ret = $this->db->query($query);
267 267
         }
268 268
 
269
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
269
+        if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query))
270 270
         {
271 271
             // Si requete utilisateur, on la sauvegarde ainsi que son resultset
272
-            if (! $ret)
272
+            if (!$ret)
273 273
             {
274 274
                 $this->lastqueryerror = $query;
275 275
                 $this->lasterror = $this->error();
276 276
                 $this->lasterrno = $this->errno();
277 277
 
278
-				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) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
279 279
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
280 280
             }
281
-            $this->lastquery=$query;
281
+            $this->lastquery = $query;
282 282
             $this->_results = $ret;
283 283
         }
284 284
 
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
     function fetch_object($resultset)
295 295
     {
296 296
         // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
297
-        if (! is_object($resultset)) { $resultset=$this->_results; }
297
+        if (!is_object($resultset)) { $resultset = $this->_results; }
298 298
 		return $resultset->fetch_object();
299 299
     }
300 300
 
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
     function fetch_array($resultset)
309 309
     {
310 310
         // If resultset not provided, we take the last used by connexion
311
-        if (! is_object($resultset)) { $resultset=$this->_results; }
311
+        if (!is_object($resultset)) { $resultset = $this->_results; }
312 312
         return $resultset->fetch_array();
313 313
     }
314 314
 
@@ -321,9 +321,9 @@  discard block
 block discarded – undo
321 321
     function fetch_row($resultset)
322 322
     {
323 323
         // If resultset not provided, we take the last used by connexion
324
-        if (! is_bool($resultset))
324
+        if (!is_bool($resultset))
325 325
         {
326
-            if (! is_object($resultset)) { $resultset=$this->_results; }
326
+            if (!is_object($resultset)) { $resultset = $this->_results; }
327 327
             return $resultset->fetch_row();
328 328
         }
329 329
         else
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
     function num_rows($resultset)
344 344
     {
345 345
         // If resultset not provided, we take the last used by connexion
346
-        if (! is_object($resultset)) { $resultset=$this->_results; }
346
+        if (!is_object($resultset)) { $resultset = $this->_results; }
347 347
         return $resultset->num_rows;
348 348
     }
349 349
 
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
     function affected_rows($resultset)
358 358
     {
359 359
         // If resultset not provided, we take the last used by connexion
360
-        if (! is_object($resultset)) { $resultset=$this->_results; }
360
+        if (!is_object($resultset)) { $resultset = $this->_results; }
361 361
         // mysql necessite un link de base pour cette fonction contrairement
362 362
         // a pqsql qui prend un resultset
363 363
         return $this->db->affected_rows;
@@ -370,10 +370,10 @@  discard block
 block discarded – undo
370 370
      *	@param  mysqli_result	$resultset	Curseur de la requete voulue
371 371
      *	@return	void
372 372
      */
373
-    function free($resultset=null)
373
+    function free($resultset = null)
374 374
     {
375 375
         // If resultset not provided, we take the last used by connexion
376
-        if (! is_object($resultset)) { $resultset=$this->_results; }
376
+        if (!is_object($resultset)) { $resultset = $this->_results; }
377 377
         // Si resultset en est un, on libere la memoire
378 378
         if (is_object($resultset)) $resultset->free_result();
379 379
     }
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
      */
397 397
     function errno()
398 398
     {
399
-        if (! $this->connected) {
399
+        if (!$this->connected) {
400 400
             // Si il y a eu echec de connexion, $this->db n'est pas valide.
401 401
             return 'DB_ERROR_FAILED_TO_CONNECT';
402 402
         } else {
@@ -428,15 +428,15 @@  discard block
 block discarded – undo
428 428
             1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
429 429
             1216 => 'DB_ERROR_NO_PARENT',
430 430
             1217 => 'DB_ERROR_CHILD_EXISTS',
431
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
431
+            1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
432 432
             1451 => 'DB_ERROR_CHILD_EXISTS'
433 433
             );
434 434
 
435 435
             if (isset($errorcode_map[$this->db->errno])) {
436 436
                 return $errorcode_map[$this->db->errno];
437 437
             }
438
-            $errno=$this->db->errno;
439
-            return ($errno?'DB_ERROR_'.$errno:'0');
438
+            $errno = $this->db->errno;
439
+            return ($errno ? 'DB_ERROR_'.$errno : '0');
440 440
         }
441 441
     }
442 442
 
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
      */
448 448
     function error()
449 449
     {
450
-        if (! $this->connected) {
450
+        if (!$this->connected) {
451 451
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
452 452
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
453 453
         }
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 	 * @param	string	$fieldid	Field name
464 464
 	 * @return  int|string			Id of row
465 465
      */
466
-    function last_insert_id($tab,$fieldid='rowid')
466
+    function last_insert_id($tab, $fieldid = 'rowid')
467 467
     {
468 468
         return $this->db->insert_id;
469 469
     }
@@ -477,17 +477,17 @@  discard block
 block discarded – undo
477 477
      * 	@return	string					XXX(field) or XXX('value') or field or 'value'
478 478
      *
479 479
      */
480
-    function encrypt($fieldorvalue, $withQuotes=0)
480
+    function encrypt($fieldorvalue, $withQuotes = 0)
481 481
     {
482 482
         global $conf;
483 483
 
484 484
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
485
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
485
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
486 486
 
487 487
         //Encryption key
488
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
488
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
489 489
 
490
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
490
+        $return = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
491 491
 
492 492
         if ($cryptType && !empty($cryptKey))
493 493
         {
@@ -515,10 +515,10 @@  discard block
 block discarded – undo
515 515
         global $conf;
516 516
 
517 517
         // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
518
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
518
+        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
519 519
 
520 520
         //Encryption key
521
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
521
+        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
522 522
 
523 523
         $return = $value;
524 524
 
@@ -545,10 +545,10 @@  discard block
 block discarded – undo
545 545
      */
546 546
     function DDLGetConnectId()
547 547
     {
548
-        $resql=$this->query('SELECT CONNECTION_ID()');
548
+        $resql = $this->query('SELECT CONNECTION_ID()');
549 549
         if ($resql)
550 550
         {
551
-            $row=$this->fetch_row($resql);
551
+            $row = $this->fetch_row($resql);
552 552
             return $row[0];
553 553
         }
554 554
         else return '?';
@@ -565,23 +565,23 @@  discard block
 block discarded – undo
565 565
 	 * 	@param	string	$owner			Username of database owner
566 566
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
567 567
      */
568
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
568
+    function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
569 569
     {
570
-        if (empty($charset))   $charset=$this->forcecharset;
571
-        if (empty($collation)) $collation=$this->forcecollate;
570
+        if (empty($charset))   $charset = $this->forcecharset;
571
+        if (empty($collation)) $collation = $this->forcecollate;
572 572
 
573 573
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
574 574
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
575
-		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
575
+		$sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
576 576
 
577
-        dol_syslog($sql,LOG_DEBUG);
578
-        $ret=$this->query($sql);
579
-        if (! $ret)
577
+        dol_syslog($sql, LOG_DEBUG);
578
+        $ret = $this->query($sql);
579
+        if (!$ret)
580 580
         {
581 581
             // We try again for compatibility with Mysql < 4.1.1
582 582
             $sql = "CREATE DATABASE `".$this->escape($database)."`";
583
-            dol_syslog($sql,LOG_DEBUG);
584
-            $ret=$this->query($sql);
583
+            dol_syslog($sql, LOG_DEBUG);
584
+            $ret = $this->query($sql);
585 585
         }
586 586
         return $ret;
587 587
     }
@@ -593,18 +593,18 @@  discard block
 block discarded – undo
593 593
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
594 594
 	 *  @return	array					List of tables in an array
595 595
      */
596
-    function DDLListTables($database, $table='')
596
+    function DDLListTables($database, $table = '')
597 597
     {
598
-        $listtables=array();
598
+        $listtables = array();
599 599
 
600 600
         $like = '';
601 601
         if ($table) $like = "LIKE '".$table."'";
602
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
602
+        $sql = "SHOW TABLES FROM ".$database." ".$like.";";
603 603
         //print $sql;
604 604
         $result = $this->query($sql);
605 605
         if ($result)
606 606
         {
607
-            while($row = $this->fetch_row($result))
607
+            while ($row = $this->fetch_row($result))
608 608
             {
609 609
                 $listtables[] = $row[0];
610 610
             }
@@ -620,15 +620,15 @@  discard block
 block discarded – undo
620 620
      */
621 621
     function DDLInfoTable($table)
622 622
     {
623
-        $infotables=array();
623
+        $infotables = array();
624 624
 
625
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
625
+        $sql = "SHOW FULL COLUMNS FROM ".$table.";";
626 626
 
627
-        dol_syslog($sql,LOG_DEBUG);
627
+        dol_syslog($sql, LOG_DEBUG);
628 628
         $result = $this->query($sql);
629 629
         if ($result)
630 630
         {
631
-            while($row = $this->fetch_row($result))
631
+            while ($row = $this->fetch_row($result))
632 632
             {
633 633
                 $infotables[] = $row;
634 634
             }
@@ -648,71 +648,71 @@  discard block
 block discarded – undo
648 648
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
649 649
 	 *	@return	    int						<0 if KO, >=0 if OK
650 650
      */
651
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
651
+    function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
652 652
     {
653 653
 	    // FIXME: $fulltext_keys parameter is unused
654 654
 
655 655
         // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
656 656
         // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
657 657
         $sql = "CREATE TABLE ".$table."(";
658
-        $i=0;
659
-        foreach($fields as $field_name => $field_desc)
658
+        $i = 0;
659
+        foreach ($fields as $field_name => $field_desc)
660 660
         {
661 661
         	$sqlfields[$i] = $field_name." ";
662
-			$sqlfields[$i]  .= $field_desc['type'];
663
-			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
662
+			$sqlfields[$i] .= $field_desc['type'];
663
+			if (preg_match("/^[^\s]/i", $field_desc['value'])) {
664 664
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
665 665
 			}
666
-			if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
666
+			if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
667 667
 				$sqlfields[$i]  .= " ".$field_desc['attribute'];
668 668
 			}
669
-			if( preg_match("/^[^\s]/i",$field_desc['default']))
669
+			if (preg_match("/^[^\s]/i", $field_desc['default']))
670 670
 			{
671
-				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
671
+				if ((preg_match("/null/i", $field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i", $field_desc['default']))) {
672 672
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
673 673
 				}
674 674
 				else {
675 675
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
676 676
 				}
677 677
 			}
678
-			if( preg_match("/^[^\s]/i",$field_desc['null'])) {
678
+			if (preg_match("/^[^\s]/i", $field_desc['null'])) {
679 679
 				$sqlfields[$i]  .= " ".$field_desc['null'];
680 680
 			}
681
-			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
681
+			if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
682 682
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
683 683
 			}
684 684
             $i++;
685 685
         }
686
-        if($primary_key != "")
686
+        if ($primary_key != "")
687 687
         $pk = "primary key(".$primary_key.")";
688 688
 
689
-        if(is_array($unique_keys)) {
689
+        if (is_array($unique_keys)) {
690 690
             $i = 0;
691
-            foreach($unique_keys as $key => $value)
691
+            foreach ($unique_keys as $key => $value)
692 692
             {
693 693
                 $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
694 694
                 $i++;
695 695
             }
696 696
         }
697
-        if(is_array($keys))
697
+        if (is_array($keys))
698 698
         {
699 699
             $i = 0;
700
-            foreach($keys as $key => $value)
700
+            foreach ($keys as $key => $value)
701 701
             {
702 702
                 $sqlk[$i] = "KEY ".$key." (".$value.")";
703 703
                 $i++;
704 704
             }
705 705
         }
706
-        $sql .= implode(',',$sqlfields);
707
-        if($primary_key != "")
706
+        $sql .= implode(',', $sqlfields);
707
+        if ($primary_key != "")
708 708
         $sql .= ",".$pk;
709
-        if($unique_keys != "")
710
-        $sql .= ",".implode(',',$sqluq);
711
-        if(is_array($keys))
712
-        $sql .= ",".implode(',',$sqlk);
713
-        $sql .=") engine=".$type;
709
+        if ($unique_keys != "")
710
+        $sql .= ",".implode(',', $sqluq);
711
+        if (is_array($keys))
712
+        $sql .= ",".implode(',', $sqlk);
713
+        $sql .= ") engine=".$type;
714 714
 
715
-        if(! $this->query($sql))
715
+        if (!$this->query($sql))
716 716
         return -1;
717 717
         else
718 718
         return 1;
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
     {
729 729
     	$sql = "DROP TABLE ".$table;
730 730
 
731
-		if (! $this->query($sql))
731
+		if (!$this->query($sql))
732 732
  			return -1;
733 733
     	else
734 734
     		return 1;
@@ -741,11 +741,11 @@  discard block
 block discarded – undo
741 741
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
742 742
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
743 743
      */
744
-    function DDLDescTable($table,$field="")
744
+    function DDLDescTable($table, $field = "")
745 745
     {
746
-        $sql="DESC ".$table." ".$field;
746
+        $sql = "DESC ".$table." ".$field;
747 747
 
748
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
748
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
749 749
         $this->_results = $this->query($sql);
750 750
         return $this->_results;
751 751
     }
@@ -759,34 +759,34 @@  discard block
 block discarded – undo
759 759
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
760 760
 	 *	@return	int							<0 if KO, >0 if OK
761 761
      */
762
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
762
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
763 763
     {
764 764
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
765 765
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
766
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
767
-        $sql.= $field_desc['type'];
768
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
769
-            if (! in_array($field_desc['type'],array('date','datetime')))
766
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
767
+        $sql .= $field_desc['type'];
768
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
769
+            if (!in_array($field_desc['type'], array('date', 'datetime')))
770 770
             {
771
-                $sql.= "(".$field_desc['value'].")";
771
+                $sql .= "(".$field_desc['value'].")";
772 772
             }
773
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
774
-        $sql.= " ".$field_desc['attribute'];
775
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
776
-        $sql.= " ".$field_desc['null'];
777
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
773
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
774
+        $sql .= " ".$field_desc['attribute'];
775
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
776
+        $sql .= " ".$field_desc['null'];
777
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
778 778
         {
779
-            if(preg_match("/null/i",$field_desc['default']))
780
-            $sql.= " default ".$field_desc['default'];
779
+            if (preg_match("/null/i", $field_desc['default']))
780
+            $sql .= " default ".$field_desc['default'];
781 781
             else
782
-            $sql.= " default '".$field_desc['default']."'";
782
+            $sql .= " default '".$field_desc['default']."'";
783 783
         }
784
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
785
-        $sql.= " ".$field_desc['extra'];
786
-        $sql.= " ".$field_position;
784
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
785
+        $sql .= " ".$field_desc['extra'];
786
+        $sql .= " ".$field_position;
787 787
 
788
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
789
-        if($this->query($sql)) {
788
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
789
+        if ($this->query($sql)) {
790 790
             return 1;
791 791
         }
792 792
         return -1;
@@ -800,38 +800,38 @@  discard block
 block discarded – undo
800 800
 	 *	@param	string	$field_desc 		Array with description of field format
801 801
 	 *	@return	int							<0 if KO, >0 if OK
802 802
      */
803
-    function DDLUpdateField($table,$field_name,$field_desc)
803
+    function DDLUpdateField($table, $field_name, $field_desc)
804 804
     {
805 805
         $sql = "ALTER TABLE ".$table;
806 806
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
807 807
         if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
808
-        	$sql.="(".$field_desc['value'].")";
808
+        	$sql .= "(".$field_desc['value'].")";
809 809
         }
810 810
         if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
811 811
         {
812 812
         	// 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
813 813
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
814 814
         	{
815
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
815
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
816 816
         		$this->query($sqlbis);
817 817
         	}
818 818
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
819 819
         	{
820
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
820
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
821 821
         		$this->query($sqlbis);
822 822
         	}
823 823
 
824
-        	$sql.=" NOT NULL";
824
+        	$sql .= " NOT NULL";
825 825
         }
826 826
 
827 827
         if ($field_desc['default'] != '')
828 828
         {
829
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
830
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
829
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
830
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
831 831
         }
832 832
 
833
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
834
-        if (! $this->query($sql))
833
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
834
+        if (!$this->query($sql))
835 835
         return -1;
836 836
         else
837 837
         return 1;
@@ -844,14 +844,14 @@  discard block
 block discarded – undo
844 844
 	 *	@param	string	$field_name 	Name of field to drop
845 845
 	 *	@return	int						<0 if KO, >0 if OK
846 846
      */
847
-    function DDLDropField($table,$field_name)
847
+    function DDLDropField($table, $field_name)
848 848
     {
849
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
850
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
849
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
850
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
851 851
         if ($this->query($sql)) {
852 852
             return 1;
853 853
         }
854
-	    $this->error=$this->lasterror();
854
+	    $this->error = $this->lasterror();
855 855
 	    return -1;
856 856
     }
857 857
 
@@ -865,12 +865,12 @@  discard block
 block discarded – undo
865 865
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
866 866
 	 *	@return	int									<0 if KO, >=0 if OK
867 867
      */
868
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
868
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
869 869
     {
870 870
         $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
871
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
872
-        $resql=$this->query($sql);
873
-        if (! $resql)
871
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
872
+        $resql = $this->query($sql);
873
+        if (!$resql)
874 874
         {
875 875
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
876 876
             {
@@ -883,18 +883,18 @@  discard block
 block discarded – undo
883 883
             }
884 884
         }
885 885
         $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)."'";
886
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
887
-        $resql=$this->query($sql);
888
-        if (! $resql)
886
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
887
+        $resql = $this->query($sql);
888
+        if (!$resql)
889 889
         {
890 890
             return -1;
891 891
         }
892 892
 
893
-        $sql="FLUSH Privileges";
893
+        $sql = "FLUSH Privileges";
894 894
 
895 895
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
896
-        $resql=$this->query($sql);
897
-        if (! $resql)
896
+        $resql = $this->query($sql);
897
+        if (!$resql)
898 898
         {
899 899
             return -1;
900 900
         }
@@ -910,13 +910,13 @@  discard block
 block discarded – undo
910 910
      */
911 911
     function getDefaultCharacterSetDatabase()
912 912
     {
913
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
913
+        $resql = $this->query('SHOW VARIABLES LIKE \'character_set_database\'');
914 914
         if (!$resql)
915 915
         {
916 916
             // version Mysql < 4.1.1
917 917
             return $this->forcecharset;
918 918
         }
919
-        $liste=$this->fetch_array($resql);
919
+        $liste = $this->fetch_array($resql);
920 920
         $tmpval = $liste['Value'];
921 921
 
922 922
         return $tmpval;
@@ -929,12 +929,12 @@  discard block
 block discarded – undo
929 929
      */
930 930
     function getListOfCharacterSet()
931 931
     {
932
-        $resql=$this->query('SHOW CHARSET');
932
+        $resql = $this->query('SHOW CHARSET');
933 933
         $liste = array();
934 934
         if ($resql)
935 935
         {
936 936
             $i = 0;
937
-            while ($obj = $this->fetch_object($resql) )
937
+            while ($obj = $this->fetch_object($resql))
938 938
             {
939 939
                 $liste[$i]['charset'] = $obj->Charset;
940 940
                 $liste[$i]['description'] = $obj->Description;
@@ -956,13 +956,13 @@  discard block
 block discarded – undo
956 956
      */
957 957
     function getDefaultCollationDatabase()
958 958
     {
959
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
959
+        $resql = $this->query('SHOW VARIABLES LIKE \'collation_database\'');
960 960
         if (!$resql)
961 961
         {
962 962
             // version Mysql < 4.1.1
963 963
             return $this->forcecollate;
964 964
         }
965
-        $liste=$this->fetch_array($resql);
965
+        $liste = $this->fetch_array($resql);
966 966
         $tmpval = $liste['Value'];
967 967
 
968 968
         return $tmpval;
@@ -975,12 +975,12 @@  discard block
 block discarded – undo
975 975
      */
976 976
     function getListOfCollation()
977 977
     {
978
-        $resql=$this->query('SHOW COLLATION');
978
+        $resql = $this->query('SHOW COLLATION');
979 979
         $liste = array();
980 980
         if ($resql)
981 981
         {
982 982
             $i = 0;
983
-            while ($obj = $this->fetch_object($resql) )
983
+            while ($obj = $this->fetch_object($resql))
984 984
             {
985 985
                 $liste[$i]['collation'] = $obj->Collation;
986 986
                 $i++;
@@ -1000,14 +1000,14 @@  discard block
 block discarded – undo
1000 1000
      */
1001 1001
     function getPathOfDump()
1002 1002
     {
1003
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1003
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1004 1004
 
1005
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1005
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1006 1006
         if ($resql)
1007 1007
         {
1008
-            $liste=$this->fetch_array($resql);
1009
-            $basedir=$liste['Value'];
1010
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1008
+            $liste = $this->fetch_array($resql);
1009
+            $basedir = $liste['Value'];
1010
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1011 1011
         }
1012 1012
         return $fullpathofdump;
1013 1013
     }
@@ -1019,14 +1019,14 @@  discard block
 block discarded – undo
1019 1019
      */
1020 1020
     function getPathOfRestore()
1021 1021
     {
1022
-        $fullpathofimport='/pathtomysql/mysql';
1022
+        $fullpathofimport = '/pathtomysql/mysql';
1023 1023
 
1024
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1024
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1025 1025
         if ($resql)
1026 1026
         {
1027
-            $liste=$this->fetch_array($resql);
1028
-            $basedir=$liste['Value'];
1029
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1027
+            $liste = $this->fetch_array($resql);
1028
+            $basedir = $liste['Value'];
1029
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1030 1030
         }
1031 1031
         return $fullpathofimport;
1032 1032
     }
@@ -1037,16 +1037,16 @@  discard block
 block discarded – undo
1037 1037
      * @param	string	$filter		Filter list on a particular value
1038 1038
 	 * @return	array				Array of key-values (key=>value)
1039 1039
      */
1040
-    function getServerParametersValues($filter='')
1040
+    function getServerParametersValues($filter = '')
1041 1041
     {
1042
-        $result=array();
1042
+        $result = array();
1043 1043
 
1044
-        $sql='SHOW VARIABLES';
1045
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1046
-        $resql=$this->query($sql);
1044
+        $sql = 'SHOW VARIABLES';
1045
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1046
+        $resql = $this->query($sql);
1047 1047
         if ($resql)
1048 1048
         {
1049
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1049
+        	while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1050 1050
         }
1051 1051
 
1052 1052
         return $result;
@@ -1058,16 +1058,16 @@  discard block
 block discarded – undo
1058 1058
      * @param	string	$filter		Filter list on a particular value
1059 1059
 	 * @return  array				Array of key-values (key=>value)
1060 1060
      */
1061
-    function getServerStatusValues($filter='')
1061
+    function getServerStatusValues($filter = '')
1062 1062
     {
1063
-        $result=array();
1063
+        $result = array();
1064 1064
 
1065
-        $sql='SHOW STATUS';
1066
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1067
-        $resql=$this->query($sql);
1065
+        $sql = 'SHOW STATUS';
1066
+        if ($filter) $sql .= " LIKE '".$this->escape($filter)."'";
1067
+        $resql = $this->query($sql);
1068 1068
         if ($resql)
1069 1069
         {
1070
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1070
+            while ($obj = $this->fetch_object($resql)) $result[$obj->Variable_name] = $obj->Value;
1071 1071
         }
1072 1072
 
1073 1073
         return $result;
Please login to merge, or discard this patch.
Braces   +120 added lines, -74 removed lines patch added patch discarded remove patch
@@ -59,8 +59,12 @@  discard block
 block discarded – undo
59 59
         global $conf,$langs;
60 60
 
61 61
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
62
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
63
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
62
+        if (! empty($conf->db->character_set)) {
63
+        	$this->forcecharset=$conf->db->character_set;
64
+        }
65
+        if (! empty($conf->db->dolibarr_main_db_collation)) {
66
+        	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
67
+        }
64 68
 
65 69
         $this->database_user=$user;
66 70
         $this->database_host=$host;
@@ -111,18 +115,23 @@  discard block
 block discarded – undo
111 115
 
112 116
                 // If client is old latin, we force utf8
113 117
                 $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
118
+                if (preg_match('/latin1/', $clientmustbe)) {
119
+                	$clientmustbe='utf8';
120
+                }
115 121
 
116 122
 				if ($this->db->character_set_name() != $clientmustbe) {
117 123
 					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
118 124
 
119 125
 					$collation = $conf->db->dolibarr_main_db_collation;
120
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
126
+					if (preg_match('/latin1/', $collation)) {
127
+						$collation='utf8_unicode_ci';
128
+					}
121 129
 
122
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
130
+					if (! preg_match('/general/', $collation)) {
131
+						$this->db->query("SET collation_connection = ".$collation);
132
+					}
123 133
 				}
124
-            }
125
-            else
134
+            } else
126 135
             {
127 136
                 $this->database_selected = false;
128 137
                 $this->database_name = '';
@@ -130,8 +139,7 @@  discard block
 block discarded – undo
130 139
                 $this->error=$this->error();
131 140
                 dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
132 141
             }
133
-        }
134
-        else
142
+        } else
135 143
         {
136 144
             // Pas de selection de base demandee, ok ou ko
137 145
             $this->database_selected = false;
@@ -140,15 +148,21 @@  discard block
 block discarded – undo
140 148
             {
141 149
             	// If client is old latin, we force utf8
142 150
             	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
151
+            	if (preg_match('/latin1/', $clientmustbe)) {
152
+            		$clientmustbe='utf8';
153
+            	}
144 154
 
145 155
 				if ($this->db->character_set_name() != $clientmustbe) {
146 156
 					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
147 157
 
148 158
 					$collation = $conf->db->dolibarr_main_db_collation;
149
-					if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
159
+					if (preg_match('/latin1/', $collation)) {
160
+						$collation='utf8_unicode_ci';
161
+					}
150 162
 
151
-					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
163
+					if (! preg_match('/general/', $collation)) {
164
+						$this->db->query("SET collation_connection = ".$collation);
165
+					}
152 166
 				}
153 167
 			}
154 168
         }
@@ -232,7 +246,9 @@  discard block
 block discarded – undo
232 246
     {
233 247
         if ($this->db)
234 248
         {
235
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
249
+	        if ($this->transaction_opened > 0) {
250
+	        	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
251
+	        }
236 252
             $this->connected=false;
237 253
             return $this->db->close();
238 254
         }
@@ -254,14 +270,15 @@  discard block
 block discarded – undo
254 270
 
255 271
         $query = trim($query);
256 272
 
257
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
273
+	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
274
+	    	dol_syslog('sql='.$query, LOG_DEBUG);
275
+	    }
258 276
 
259 277
         if (! $this->database_name)
260 278
         {
261 279
             // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
262 280
             $ret = $this->db->query($query);
263
-        }
264
-        else
281
+        } else
265 282
         {
266 283
             $ret = $this->db->query($query);
267 284
         }
@@ -275,7 +292,10 @@  discard block
 block discarded – undo
275 292
                 $this->lasterror = $this->error();
276 293
                 $this->lasterrno = $this->errno();
277 294
 
278
-				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
295
+				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
296
+					dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
297
+				}
298
+				// Log of request was not yet done previously
279 299
                 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
280 300
             }
281 301
             $this->lastquery=$query;
@@ -325,8 +345,7 @@  discard block
 block discarded – undo
325 345
         {
326 346
             if (! is_object($resultset)) { $resultset=$this->_results; }
327 347
             return $resultset->fetch_row();
328
-        }
329
-        else
348
+        } else
330 349
         {
331 350
             // si le curseur est un booleen on retourne la valeur 0
332 351
             return 0;
@@ -375,7 +394,9 @@  discard block
 block discarded – undo
375 394
         // If resultset not provided, we take the last used by connexion
376 395
         if (! is_object($resultset)) { $resultset=$this->_results; }
377 396
         // Si resultset en est un, on libere la memoire
378
-        if (is_object($resultset)) $resultset->free_result();
397
+        if (is_object($resultset)) {
398
+        	$resultset->free_result();
399
+        }
379 400
     }
380 401
 
381 402
     /**
@@ -450,8 +471,7 @@  discard block
 block discarded – undo
450 471
         if (! $this->connected) {
451 472
             // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
452 473
             return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
453
-        }
454
-        else {
474
+        } else {
455 475
             return $this->db->error;
456 476
         }
457 477
     }
@@ -494,8 +514,7 @@  discard block
 block discarded – undo
494 514
             if ($cryptType == 2)
495 515
             {
496 516
                 $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
497
-            }
498
-            else if ($cryptType == 1)
517
+            } else if ($cryptType == 1)
499 518
             {
500 519
                 $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
501 520
             }
@@ -527,8 +546,7 @@  discard block
 block discarded – undo
527 546
             if ($cryptType == 2)
528 547
             {
529 548
                 $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
530
-            }
531
-            else if ($cryptType == 1)
549
+            } else if ($cryptType == 1)
532 550
             {
533 551
                 $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
534 552
             }
@@ -550,8 +568,9 @@  discard block
 block discarded – undo
550 568
         {
551 569
             $row=$this->fetch_row($resql);
552 570
             return $row[0];
571
+        } else {
572
+        	return '?';
553 573
         }
554
-        else return '?';
555 574
     }
556 575
 
557 576
     /**
@@ -567,8 +586,12 @@  discard block
 block discarded – undo
567 586
      */
568 587
     function DDLCreateDb($database,$charset='',$collation='',$owner='')
569 588
     {
570
-        if (empty($charset))   $charset=$this->forcecharset;
571
-        if (empty($collation)) $collation=$this->forcecollate;
589
+        if (empty($charset)) {
590
+        	$charset=$this->forcecharset;
591
+        }
592
+        if (empty($collation)) {
593
+        	$collation=$this->forcecollate;
594
+        }
572 595
 
573 596
         // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
574 597
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
@@ -598,7 +621,9 @@  discard block
 block discarded – undo
598 621
         $listtables=array();
599 622
 
600 623
         $like = '';
601
-        if ($table) $like = "LIKE '".$table."'";
624
+        if ($table) {
625
+        	$like = "LIKE '".$table."'";
626
+        }
602 627
         $sql="SHOW TABLES FROM ".$database." ".$like.";";
603 628
         //print $sql;
604 629
         $result = $this->query($sql);
@@ -670,8 +695,7 @@  discard block
 block discarded – undo
670 695
 			{
671 696
 				if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
672 697
 					$sqlfields[$i]  .= " default ".$field_desc['default'];
673
-				}
674
-				else {
698
+				} else {
675 699
 					$sqlfields[$i]  .= " default '".$field_desc['default']."'";
676 700
 				}
677 701
 			}
@@ -683,8 +707,9 @@  discard block
 block discarded – undo
683 707
 			}
684 708
             $i++;
685 709
         }
686
-        if($primary_key != "")
687
-        $pk = "primary key(".$primary_key.")";
710
+        if($primary_key != "") {
711
+                $pk = "primary key(".$primary_key.")";
712
+        }
688 713
 
689 714
         if(is_array($unique_keys)) {
690 715
             $i = 0;
@@ -704,18 +729,22 @@  discard block
 block discarded – undo
704 729
             }
705 730
         }
706 731
         $sql .= implode(',',$sqlfields);
707
-        if($primary_key != "")
708
-        $sql .= ",".$pk;
709
-        if($unique_keys != "")
710
-        $sql .= ",".implode(',',$sqluq);
711
-        if(is_array($keys))
712
-        $sql .= ",".implode(',',$sqlk);
732
+        if($primary_key != "") {
733
+                $sql .= ",".$pk;
734
+        }
735
+        if($unique_keys != "") {
736
+                $sql .= ",".implode(',',$sqluq);
737
+        }
738
+        if(is_array($keys)) {
739
+                $sql .= ",".implode(',',$sqlk);
740
+        }
713 741
         $sql .=") engine=".$type;
714 742
 
715
-        if(! $this->query($sql))
716
-        return -1;
717
-        else
718
-        return 1;
743
+        if(! $this->query($sql)) {
744
+                return -1;
745
+        } else {
746
+                return 1;
747
+        }
719 748
     }
720 749
 
721 750
     /**
@@ -728,10 +757,11 @@  discard block
 block discarded – undo
728 757
     {
729 758
     	$sql = "DROP TABLE ".$table;
730 759
 
731
-		if (! $this->query($sql))
732
- 			return -1;
733
-    	else
734
-    		return 1;
760
+		if (! $this->query($sql)) {
761
+		 			return -1;
762
+		} else {
763
+    	    		return 1;
764
+    	}
735 765
     }
736 766
 
737 767
     /**
@@ -765,24 +795,29 @@  discard block
 block discarded – undo
765 795
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
766 796
         $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
767 797
         $sql.= $field_desc['type'];
768
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
769
-            if (! in_array($field_desc['type'],array('date','datetime')))
798
+        if(preg_match("/^[^\s]/i",$field_desc['value'])) {
799
+                    if (! in_array($field_desc['type'],array('date','datetime')))
770 800
             {
771 801
                 $sql.= "(".$field_desc['value'].")";
802
+        }
772 803
             }
773
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
774
-        $sql.= " ".$field_desc['attribute'];
775
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
776
-        $sql.= " ".$field_desc['null'];
804
+        if(preg_match("/^[^\s]/i",$field_desc['attribute'])) {
805
+                $sql.= " ".$field_desc['attribute'];
806
+        }
807
+        if(preg_match("/^[^\s]/i",$field_desc['null'])) {
808
+                $sql.= " ".$field_desc['null'];
809
+        }
777 810
         if(preg_match("/^[^\s]/i",$field_desc['default']))
778 811
         {
779
-            if(preg_match("/null/i",$field_desc['default']))
780
-            $sql.= " default ".$field_desc['default'];
781
-            else
782
-            $sql.= " default '".$field_desc['default']."'";
812
+            if(preg_match("/null/i",$field_desc['default'])) {
813
+                        $sql.= " default ".$field_desc['default'];
814
+            } else {
815
+                        $sql.= " default '".$field_desc['default']."'";
816
+            }
817
+        }
818
+        if(preg_match("/^[^\s]/i",$field_desc['extra'])) {
819
+                $sql.= " ".$field_desc['extra'];
783 820
         }
784
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
785
-        $sql.= " ".$field_desc['extra'];
786 821
         $sql.= " ".$field_position;
787 822
 
788 823
         dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
@@ -814,8 +849,7 @@  discard block
 block discarded – undo
814 849
         	{
815 850
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
816 851
         		$this->query($sqlbis);
817
-        	}
818
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
852
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
819 853
         	{
820 854
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
821 855
         		$this->query($sqlbis);
@@ -826,15 +860,20 @@  discard block
 block discarded – undo
826 860
 
827 861
         if ($field_desc['default'] != '')
828 862
         {
829
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
830
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
863
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
864
+				$sql.=" DEFAULT ".$this->escape($field_desc['default']);
865
+			} elseif ($field_desc['type'] == 'text') {
866
+        		$sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
867
+        	}
868
+        	// Default not supported on text fields
831 869
         }
832 870
 
833 871
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
834
-        if (! $this->query($sql))
835
-        return -1;
836
-        else
837
-        return 1;
872
+        if (! $this->query($sql)) {
873
+                return -1;
874
+        } else {
875
+                return 1;
876
+        }
838 877
     }
839 878
 
840 879
     /**
@@ -875,8 +914,7 @@  discard block
 block discarded – undo
875 914
             if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
876 915
             {
877 916
             	return -1;
878
-            }
879
-            else
917
+            } else
880 918
 			{
881 919
             	// If user already exists, we continue to set permissions
882 920
             	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
@@ -1042,11 +1080,15 @@  discard block
 block discarded – undo
1042 1080
         $result=array();
1043 1081
 
1044 1082
         $sql='SHOW VARIABLES';
1045
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1083
+        if ($filter) {
1084
+        	$sql.=" LIKE '".$this->escape($filter)."'";
1085
+        }
1046 1086
         $resql=$this->query($sql);
1047 1087
         if ($resql)
1048 1088
         {
1049
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1089
+        	while($obj=$this->fetch_object($resql)) {
1090
+        		$result[$obj->Variable_name]=$obj->Value;
1091
+        	}
1050 1092
         }
1051 1093
 
1052 1094
         return $result;
@@ -1063,11 +1105,15 @@  discard block
 block discarded – undo
1063 1105
         $result=array();
1064 1106
 
1065 1107
         $sql='SHOW STATUS';
1066
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1108
+        if ($filter) {
1109
+        	$sql.=" LIKE '".$this->escape($filter)."'";
1110
+        }
1067 1111
         $resql=$this->query($sql);
1068 1112
         if ($resql)
1069 1113
         {
1070
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1114
+            while($obj=$this->fetch_object($resql)) {
1115
+            	$result[$obj->Variable_name]=$obj->Value;
1116
+            }
1071 1117
         }
1072 1118
 
1073 1119
         return $result;
Please login to merge, or discard this patch.
Indentation   +840 added lines, -840 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,17 +101,17 @@  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 is old latin, we force utf8
113
-                $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114
-                if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
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 is old latin, we force utf8
113
+				$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114
+				if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
115 115
 
116 116
 				if ($this->db->character_set_name() != $clientmustbe) {
117 117
 					$this->db->set_charset($clientmustbe);	// This set charset, but with a bad collation
@@ -121,26 +121,26 @@  discard block
 block discarded – undo
121 121
 
122 122
 					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
123 123
 				}
124
-            }
125
-            else
126
-            {
127
-                $this->database_selected = false;
128
-                $this->database_name = '';
129
-                $this->ok = false;
130
-                $this->error=$this->error();
131
-                dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
132
-            }
133
-        }
134
-        else
135
-        {
136
-            // Pas de selection de base demandee, ok ou ko
137
-            $this->database_selected = false;
138
-
139
-            if ($this->connected)
140
-            {
141
-            	// If client is old latin, we force utf8
142
-            	$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
-            	if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
124
+			}
125
+			else
126
+			{
127
+				$this->database_selected = false;
128
+				$this->database_name = '';
129
+				$this->ok = false;
130
+				$this->error=$this->error();
131
+				dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
132
+			}
133
+		}
134
+		else
135
+		{
136
+			// Pas de selection de base demandee, ok ou ko
137
+			$this->database_selected = false;
138
+
139
+			if ($this->connected)
140
+			{
141
+				// If client is old latin, we force utf8
142
+				$clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143
+				if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
144 144
 
145 145
 				if ($this->db->character_set_name() != $clientmustbe) {
146 146
 					$this->db->set_charset($clientmustbe);	// This set utf8_general_ci
@@ -151,21 +151,21 @@  discard block
 block discarded – undo
151 151
 					if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
152 152
 				}
153 153
 			}
154
-        }
155
-    }
156
-
157
-
158
-    /**
159
-     *  Convert a SQL request in Mysql syntax to native syntax
160
-     *
161
-     *  @param     string	$line   SQL request line to convert
162
-     *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
163
-     *  @return    string   		SQL request line converted
164
-     */
165
-    static function convertSQLFromMysql($line,$type='ddl')
166
-    {
167
-        return $line;
168
-    }
154
+		}
155
+	}
156
+
157
+
158
+	/**
159
+	 *  Convert a SQL request in Mysql syntax to native syntax
160
+	 *
161
+	 *  @param     string	$line   SQL request line to convert
162
+	 *  @param     string	$type	Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
163
+	 *  @return    string   		SQL request line converted
164
+	 */
165
+	static function convertSQLFromMysql($line,$type='ddl')
166
+	{
167
+		return $line;
168
+	}
169 169
 
170 170
 	/**
171 171
 	 *	Select a database
@@ -173,11 +173,11 @@  discard block
 block discarded – undo
173 173
 	 *	@param	    string	$database	Name of database
174 174
 	 *	@return	    boolean  		    true if OK, false if KO
175 175
 	 */
176
-    function select_db($database)
177
-    {
178
-        dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
179
-	    return $this->db->select_db($database);
180
-    }
176
+	function select_db($database)
177
+	{
178
+		dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
179
+		return $this->db->select_db($database);
180
+	}
181 181
 
182 182
 
183 183
 	/**
@@ -201,360 +201,360 @@  discard block
 block discarded – undo
201 201
 		return new mysqli($host, $login, $passwd, $name, $port);
202 202
 	}
203 203
 
204
-    /**
204
+	/**
205 205
 	 *	Return version of database server
206 206
 	 *
207 207
 	 *	@return	        string      Version string
208
-     */
209
-    function getVersion()
210
-    {
211
-        return $this->db->server_info;
212
-    }
213
-
214
-    /**
215
-     *	Return version of database client driver
216
-     *
217
-     *	@return	        string      Version string
218
-     */
208
+	 */
209
+	function getVersion()
210
+	{
211
+		return $this->db->server_info;
212
+	}
213
+
214
+	/**
215
+	 *	Return version of database client driver
216
+	 *
217
+	 *	@return	        string      Version string
218
+	 */
219 219
 	function getDriverInfo()
220 220
 	{
221 221
 		return $this->db->client_info;
222 222
 	}
223 223
 
224 224
 
225
-    /**
226
-     *  Close database connexion
227
-     *
228
-     *  @return     bool     True if disconnect successfull, false otherwise
229
-     *  @see        connect
230
-     */
231
-    function close()
232
-    {
233
-        if ($this->db)
234
-        {
235
-	        if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
236
-            $this->connected=false;
237
-            return $this->db->close();
238
-        }
239
-        return false;
240
-    }
241
-
242
-    /**
243
-     * 	Execute a SQL request and return the resultset
244
-     *
245
-     * 	@param	string	$query			SQL query string
246
-     * 	@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).
247
-     * 									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.
248
-     *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
249
-     *	@return	bool|mysqli_result		Resultset of answer
250
-     */
251
-    function query($query,$usesavepoint=0,$type='auto')
252
-    {
253
-    	global $conf;
254
-
255
-        $query = trim($query);
256
-
257
-	    if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
258
-
259
-        if (! $this->database_name)
260
-        {
261
-            // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
262
-            $ret = $this->db->query($query);
263
-        }
264
-        else
265
-        {
266
-            $ret = $this->db->query($query);
267
-        }
268
-
269
-        if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
270
-        {
271
-            // Si requete utilisateur, on la sauvegarde ainsi que son resultset
272
-            if (! $ret)
273
-            {
274
-                $this->lastqueryerror = $query;
275
-                $this->lasterror = $this->error();
276
-                $this->lasterrno = $this->errno();
225
+	/**
226
+	 *  Close database connexion
227
+	 *
228
+	 *  @return     bool     True if disconnect successfull, false otherwise
229
+	 *  @see        connect
230
+	 */
231
+	function close()
232
+	{
233
+		if ($this->db)
234
+		{
235
+			if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
236
+			$this->connected=false;
237
+			return $this->db->close();
238
+		}
239
+		return false;
240
+	}
241
+
242
+	/**
243
+	 * 	Execute a SQL request and return the resultset
244
+	 *
245
+	 * 	@param	string	$query			SQL query string
246
+	 * 	@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).
247
+	 * 									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.
248
+	 *  @param  string	$type           Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
249
+	 *	@return	bool|mysqli_result		Resultset of answer
250
+	 */
251
+	function query($query,$usesavepoint=0,$type='auto')
252
+	{
253
+		global $conf;
254
+
255
+		$query = trim($query);
256
+
257
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
258
+
259
+		if (! $this->database_name)
260
+		{
261
+			// Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
262
+			$ret = $this->db->query($query);
263
+		}
264
+		else
265
+		{
266
+			$ret = $this->db->query($query);
267
+		}
268
+
269
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
270
+		{
271
+			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
272
+			if (! $ret)
273
+			{
274
+				$this->lastqueryerror = $query;
275
+				$this->lasterror = $this->error();
276
+				$this->lasterrno = $this->errno();
277 277
 
278 278
 				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
279
-                dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
280
-            }
281
-            $this->lastquery=$query;
282
-            $this->_results = $ret;
283
-        }
284
-
285
-        return $ret;
286
-    }
287
-
288
-    /**
289
-     *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
290
-     *
291
-     *	@param	mysqli_result	$resultset	Curseur de la requete voulue
292
-     *	@return	object|null					Object result line or null if KO or end of cursor
293
-     */
294
-    function fetch_object($resultset)
295
-    {
296
-        // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
297
-        if (! is_object($resultset)) { $resultset=$this->_results; }
279
+				dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
280
+			}
281
+			$this->lastquery=$query;
282
+			$this->_results = $ret;
283
+		}
284
+
285
+		return $ret;
286
+	}
287
+
288
+	/**
289
+	 *	Renvoie la ligne courante (comme un objet) pour le curseur resultset
290
+	 *
291
+	 *	@param	mysqli_result	$resultset	Curseur de la requete voulue
292
+	 *	@return	object|null					Object result line or null if KO or end of cursor
293
+	 */
294
+	function fetch_object($resultset)
295
+	{
296
+		// Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
297
+		if (! is_object($resultset)) { $resultset=$this->_results; }
298 298
 		return $resultset->fetch_object();
299
-    }
300
-
301
-
302
-    /**
303
-     *	Return datas as an array
304
-     *
305
-     *	@param	mysqli_result	$resultset	Resultset of request
306
-     *	@return	array|null					Array or null if KO or end of cursor
307
-     */
308
-    function fetch_array($resultset)
309
-    {
310
-        // If resultset not provided, we take the last used by connexion
311
-        if (! is_object($resultset)) { $resultset=$this->_results; }
312
-        return $resultset->fetch_array();
313
-    }
314
-
315
-    /**
316
-     *	Return datas as an array
317
-     *
318
-     *	@param	mysqli_result	$resultset	Resultset of request
319
-     *	@return	array|null|0				Array or null if KO or end of cursor or 0 if resultset is bool
320
-     */
321
-    function fetch_row($resultset)
322
-    {
323
-        // If resultset not provided, we take the last used by connexion
324
-        if (! is_bool($resultset))
325
-        {
326
-            if (! is_object($resultset)) { $resultset=$this->_results; }
327
-            return $resultset->fetch_row();
328
-        }
329
-        else
330
-        {
331
-            // si le curseur est un booleen on retourne la valeur 0
332
-            return 0;
333
-        }
334
-    }
335
-
336
-    /**
337
-     *	Return number of lines for result of a SELECT
338
-     *
339
-     *	@param	mysqli_result	$resultset  Resulset of requests
340
-     *	@return	int				Nb of lines
341
-     *	@see    affected_rows
342
-     */
343
-    function num_rows($resultset)
344
-    {
345
-        // If resultset not provided, we take the last used by connexion
346
-        if (! is_object($resultset)) { $resultset=$this->_results; }
347
-        return $resultset->num_rows;
348
-    }
349
-
350
-    /**
351
-     *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
352
-     *
353
-     *	@param	mysqli_result	$resultset	Curseur de la requete voulue
354
-     *	@return int							Nombre de lignes
355
-     *	@see    num_rows
356
-     */
357
-    function affected_rows($resultset)
358
-    {
359
-        // If resultset not provided, we take the last used by connexion
360
-        if (! is_object($resultset)) { $resultset=$this->_results; }
361
-        // mysql necessite un link de base pour cette fonction contrairement
362
-        // a pqsql qui prend un resultset
363
-        return $this->db->affected_rows;
364
-    }
365
-
366
-
367
-    /**
368
-     *	Libere le dernier resultset utilise sur cette connexion
369
-     *
370
-     *	@param  mysqli_result	$resultset	Curseur de la requete voulue
371
-     *	@return	void
372
-     */
373
-    function free($resultset=null)
374
-    {
375
-        // If resultset not provided, we take the last used by connexion
376
-        if (! is_object($resultset)) { $resultset=$this->_results; }
377
-        // Si resultset en est un, on libere la memoire
378
-        if (is_object($resultset)) $resultset->free_result();
379
-    }
380
-
381
-    /**
382
-     *	Escape a string to insert data
383
-     *
384
-     *	@param	string	$stringtoencode		String to escape
385
-     *	@return	string						String escaped
386
-     */
387
-    function escape($stringtoencode)
388
-    {
389
-        return $this->db->real_escape_string($stringtoencode);
390
-    }
391
-
392
-    /**
393
-     *	Return generic error code of last operation.
394
-     *
395
-     *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
396
-     */
397
-    function errno()
398
-    {
399
-        if (! $this->connected) {
400
-            // Si il y a eu echec de connexion, $this->db n'est pas valide.
401
-            return 'DB_ERROR_FAILED_TO_CONNECT';
402
-        } else {
403
-            // Constants to convert a MySql error code to a generic Dolibarr error code
404
-            $errorcode_map = array(
405
-            1004 => 'DB_ERROR_CANNOT_CREATE',
406
-            1005 => 'DB_ERROR_CANNOT_CREATE',
407
-            1006 => 'DB_ERROR_CANNOT_CREATE',
408
-            1007 => 'DB_ERROR_ALREADY_EXISTS',
409
-            1008 => 'DB_ERROR_CANNOT_DROP',
410
-            1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
411
-            1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
412
-            1044 => 'DB_ERROR_ACCESSDENIED',
413
-            1046 => 'DB_ERROR_NODBSELECTED',
414
-            1048 => 'DB_ERROR_CONSTRAINT',
415
-            1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
416
-            1051 => 'DB_ERROR_NOSUCHTABLE',
417
-            1054 => 'DB_ERROR_NOSUCHFIELD',
418
-            1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
419
-            1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
420
-            1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
421
-            1064 => 'DB_ERROR_SYNTAX',
422
-            1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
423
-            1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
424
-            1091 => 'DB_ERROR_NOSUCHFIELD',
425
-            1100 => 'DB_ERROR_NOT_LOCKED',
426
-            1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
427
-            1146 => 'DB_ERROR_NOSUCHTABLE',
428
-            1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
429
-            1216 => 'DB_ERROR_NO_PARENT',
430
-            1217 => 'DB_ERROR_CHILD_EXISTS',
431
-            1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
432
-            1451 => 'DB_ERROR_CHILD_EXISTS'
433
-            );
434
-
435
-            if (isset($errorcode_map[$this->db->errno])) {
436
-                return $errorcode_map[$this->db->errno];
437
-            }
438
-            $errno=$this->db->errno;
439
-            return ($errno?'DB_ERROR_'.$errno:'0');
440
-        }
441
-    }
442
-
443
-    /**
299
+	}
300
+
301
+
302
+	/**
303
+	 *	Return datas as an array
304
+	 *
305
+	 *	@param	mysqli_result	$resultset	Resultset of request
306
+	 *	@return	array|null					Array or null if KO or end of cursor
307
+	 */
308
+	function fetch_array($resultset)
309
+	{
310
+		// If resultset not provided, we take the last used by connexion
311
+		if (! is_object($resultset)) { $resultset=$this->_results; }
312
+		return $resultset->fetch_array();
313
+	}
314
+
315
+	/**
316
+	 *	Return datas as an array
317
+	 *
318
+	 *	@param	mysqli_result	$resultset	Resultset of request
319
+	 *	@return	array|null|0				Array or null if KO or end of cursor or 0 if resultset is bool
320
+	 */
321
+	function fetch_row($resultset)
322
+	{
323
+		// If resultset not provided, we take the last used by connexion
324
+		if (! is_bool($resultset))
325
+		{
326
+			if (! is_object($resultset)) { $resultset=$this->_results; }
327
+			return $resultset->fetch_row();
328
+		}
329
+		else
330
+		{
331
+			// si le curseur est un booleen on retourne la valeur 0
332
+			return 0;
333
+		}
334
+	}
335
+
336
+	/**
337
+	 *	Return number of lines for result of a SELECT
338
+	 *
339
+	 *	@param	mysqli_result	$resultset  Resulset of requests
340
+	 *	@return	int				Nb of lines
341
+	 *	@see    affected_rows
342
+	 */
343
+	function num_rows($resultset)
344
+	{
345
+		// If resultset not provided, we take the last used by connexion
346
+		if (! is_object($resultset)) { $resultset=$this->_results; }
347
+		return $resultset->num_rows;
348
+	}
349
+
350
+	/**
351
+	 *	Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
352
+	 *
353
+	 *	@param	mysqli_result	$resultset	Curseur de la requete voulue
354
+	 *	@return int							Nombre de lignes
355
+	 *	@see    num_rows
356
+	 */
357
+	function affected_rows($resultset)
358
+	{
359
+		// If resultset not provided, we take the last used by connexion
360
+		if (! is_object($resultset)) { $resultset=$this->_results; }
361
+		// mysql necessite un link de base pour cette fonction contrairement
362
+		// a pqsql qui prend un resultset
363
+		return $this->db->affected_rows;
364
+	}
365
+
366
+
367
+	/**
368
+	 *	Libere le dernier resultset utilise sur cette connexion
369
+	 *
370
+	 *	@param  mysqli_result	$resultset	Curseur de la requete voulue
371
+	 *	@return	void
372
+	 */
373
+	function free($resultset=null)
374
+	{
375
+		// If resultset not provided, we take the last used by connexion
376
+		if (! is_object($resultset)) { $resultset=$this->_results; }
377
+		// Si resultset en est un, on libere la memoire
378
+		if (is_object($resultset)) $resultset->free_result();
379
+	}
380
+
381
+	/**
382
+	 *	Escape a string to insert data
383
+	 *
384
+	 *	@param	string	$stringtoencode		String to escape
385
+	 *	@return	string						String escaped
386
+	 */
387
+	function escape($stringtoencode)
388
+	{
389
+		return $this->db->real_escape_string($stringtoencode);
390
+	}
391
+
392
+	/**
393
+	 *	Return generic error code of last operation.
394
+	 *
395
+	 *	@return	string		Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
396
+	 */
397
+	function errno()
398
+	{
399
+		if (! $this->connected) {
400
+			// Si il y a eu echec de connexion, $this->db n'est pas valide.
401
+			return 'DB_ERROR_FAILED_TO_CONNECT';
402
+		} else {
403
+			// Constants to convert a MySql error code to a generic Dolibarr error code
404
+			$errorcode_map = array(
405
+			1004 => 'DB_ERROR_CANNOT_CREATE',
406
+			1005 => 'DB_ERROR_CANNOT_CREATE',
407
+			1006 => 'DB_ERROR_CANNOT_CREATE',
408
+			1007 => 'DB_ERROR_ALREADY_EXISTS',
409
+			1008 => 'DB_ERROR_CANNOT_DROP',
410
+			1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
411
+			1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
412
+			1044 => 'DB_ERROR_ACCESSDENIED',
413
+			1046 => 'DB_ERROR_NODBSELECTED',
414
+			1048 => 'DB_ERROR_CONSTRAINT',
415
+			1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
416
+			1051 => 'DB_ERROR_NOSUCHTABLE',
417
+			1054 => 'DB_ERROR_NOSUCHFIELD',
418
+			1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
419
+			1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
420
+			1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
421
+			1064 => 'DB_ERROR_SYNTAX',
422
+			1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
423
+			1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
424
+			1091 => 'DB_ERROR_NOSUCHFIELD',
425
+			1100 => 'DB_ERROR_NOT_LOCKED',
426
+			1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
427
+			1146 => 'DB_ERROR_NOSUCHTABLE',
428
+			1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
429
+			1216 => 'DB_ERROR_NO_PARENT',
430
+			1217 => 'DB_ERROR_CHILD_EXISTS',
431
+			1396 => 'DB_ERROR_USER_ALREADY_EXISTS',    // When creating user already existing
432
+			1451 => 'DB_ERROR_CHILD_EXISTS'
433
+			);
434
+
435
+			if (isset($errorcode_map[$this->db->errno])) {
436
+				return $errorcode_map[$this->db->errno];
437
+			}
438
+			$errno=$this->db->errno;
439
+			return ($errno?'DB_ERROR_'.$errno:'0');
440
+		}
441
+	}
442
+
443
+	/**
444 444
 	 *	Return description of last error
445 445
 	 *
446 446
 	 *	@return	string		Error text
447
-     */
448
-    function error()
449
-    {
450
-        if (! $this->connected) {
451
-            // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
452
-            return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
453
-        }
454
-        else {
455
-            return $this->db->error;
456
-        }
457
-    }
458
-
459
-    /**
447
+	 */
448
+	function error()
449
+	{
450
+		if (! $this->connected) {
451
+			// Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
452
+			return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
453
+		}
454
+		else {
455
+			return $this->db->error;
456
+		}
457
+	}
458
+
459
+	/**
460 460
 	 * Get last ID after an insert INSERT
461 461
 	 *
462 462
 	 * @param   string	$tab    	Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
463 463
 	 * @param	string	$fieldid	Field name
464 464
 	 * @return  int|string			Id of row
465
-     */
466
-    function last_insert_id($tab,$fieldid='rowid')
467
-    {
468
-        return $this->db->insert_id;
469
-    }
470
-
471
-    /**
472
-     *	Encrypt sensitive data in database
473
-     *  Warning: This function includes the escape, so it must use direct value
474
-     *
475
-     *	@param	string	$fieldorvalue	Field name or value to encrypt
476
-     * 	@param	int		$withQuotes		Return string with quotes
477
-     * 	@return	string					XXX(field) or XXX('value') or field or 'value'
478
-     *
479
-     */
480
-    function encrypt($fieldorvalue, $withQuotes=0)
481
-    {
482
-        global $conf;
483
-
484
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
485
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
486
-
487
-        //Encryption key
488
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
489
-
490
-        $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
491
-
492
-        if ($cryptType && !empty($cryptKey))
493
-        {
494
-            if ($cryptType == 2)
495
-            {
496
-                $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
497
-            }
498
-            else if ($cryptType == 1)
499
-            {
500
-                $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
501
-            }
502
-        }
503
-
504
-        return $return;
505
-    }
506
-
507
-    /**
508
-     *	Decrypt sensitive data in database
509
-     *
510
-     *	@param	string	$value			Value to decrypt
511
-     * 	@return	string					Decrypted value if used
512
-     */
513
-    function decrypt($value)
514
-    {
515
-        global $conf;
516
-
517
-        // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
518
-        $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
519
-
520
-        //Encryption key
521
-        $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
522
-
523
-        $return = $value;
524
-
525
-        if ($cryptType && !empty($cryptKey))
526
-        {
527
-            if ($cryptType == 2)
528
-            {
529
-                $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
530
-            }
531
-            else if ($cryptType == 1)
532
-            {
533
-                $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
534
-            }
535
-        }
536
-
537
-        return $return;
538
-    }
539
-
540
-
541
-    /**
465
+	 */
466
+	function last_insert_id($tab,$fieldid='rowid')
467
+	{
468
+		return $this->db->insert_id;
469
+	}
470
+
471
+	/**
472
+	 *	Encrypt sensitive data in database
473
+	 *  Warning: This function includes the escape, so it must use direct value
474
+	 *
475
+	 *	@param	string	$fieldorvalue	Field name or value to encrypt
476
+	 * 	@param	int		$withQuotes		Return string with quotes
477
+	 * 	@return	string					XXX(field) or XXX('value') or field or 'value'
478
+	 *
479
+	 */
480
+	function encrypt($fieldorvalue, $withQuotes=0)
481
+	{
482
+		global $conf;
483
+
484
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
485
+		$cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
486
+
487
+		//Encryption key
488
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
489
+
490
+		$return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
491
+
492
+		if ($cryptType && !empty($cryptKey))
493
+		{
494
+			if ($cryptType == 2)
495
+			{
496
+				$return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
497
+			}
498
+			else if ($cryptType == 1)
499
+			{
500
+				$return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
501
+			}
502
+		}
503
+
504
+		return $return;
505
+	}
506
+
507
+	/**
508
+	 *	Decrypt sensitive data in database
509
+	 *
510
+	 *	@param	string	$value			Value to decrypt
511
+	 * 	@return	string					Decrypted value if used
512
+	 */
513
+	function decrypt($value)
514
+	{
515
+		global $conf;
516
+
517
+		// Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
518
+		$cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
519
+
520
+		//Encryption key
521
+		$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
522
+
523
+		$return = $value;
524
+
525
+		if ($cryptType && !empty($cryptKey))
526
+		{
527
+			if ($cryptType == 2)
528
+			{
529
+				$return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
530
+			}
531
+			else if ($cryptType == 1)
532
+			{
533
+				$return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
534
+			}
535
+		}
536
+
537
+		return $return;
538
+	}
539
+
540
+
541
+	/**
542 542
 	 * Return connexion ID
543 543
 	 *
544 544
 	 * @return	        string      Id connexion
545
-     */
546
-    function DDLGetConnectId()
547
-    {
548
-        $resql=$this->query('SELECT CONNECTION_ID()');
549
-        if ($resql)
550
-        {
551
-            $row=$this->fetch_row($resql);
552
-            return $row[0];
553
-        }
554
-        else return '?';
555
-    }
556
-
557
-    /**
545
+	 */
546
+	function DDLGetConnectId()
547
+	{
548
+		$resql=$this->query('SELECT CONNECTION_ID()');
549
+		if ($resql)
550
+		{
551
+			$row=$this->fetch_row($resql);
552
+			return $row[0];
553
+		}
554
+		else return '?';
555
+	}
556
+
557
+	/**
558 558
 	 *	Create a new database
559 559
 	 *	Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
560 560
 	 *	We force to create database with charset this->forcecharset and collate this->forcecollate
@@ -564,79 +564,79 @@  discard block
 block discarded – undo
564 564
 	 * 	@param	string	$collation		Charset used to sort data
565 565
 	 * 	@param	string	$owner			Username of database owner
566 566
 	 * 	@return	bool|mysqli_result		resource defined if OK, null if KO
567
-     */
568
-    function DDLCreateDb($database,$charset='',$collation='',$owner='')
569
-    {
570
-        if (empty($charset))   $charset=$this->forcecharset;
571
-        if (empty($collation)) $collation=$this->forcecollate;
567
+	 */
568
+	function DDLCreateDb($database,$charset='',$collation='',$owner='')
569
+	{
570
+		if (empty($charset))   $charset=$this->forcecharset;
571
+		if (empty($collation)) $collation=$this->forcecollate;
572 572
 
573
-        // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
573
+		// ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
574 574
 		$sql = "CREATE DATABASE `".$this->escape($database)."`";
575 575
 		$sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
576 576
 
577
-        dol_syslog($sql,LOG_DEBUG);
578
-        $ret=$this->query($sql);
579
-        if (! $ret)
580
-        {
581
-            // We try again for compatibility with Mysql < 4.1.1
582
-            $sql = "CREATE DATABASE `".$this->escape($database)."`";
583
-            dol_syslog($sql,LOG_DEBUG);
584
-            $ret=$this->query($sql);
585
-        }
586
-        return $ret;
587
-    }
588
-
589
-    /**
577
+		dol_syslog($sql,LOG_DEBUG);
578
+		$ret=$this->query($sql);
579
+		if (! $ret)
580
+		{
581
+			// We try again for compatibility with Mysql < 4.1.1
582
+			$sql = "CREATE DATABASE `".$this->escape($database)."`";
583
+			dol_syslog($sql,LOG_DEBUG);
584
+			$ret=$this->query($sql);
585
+		}
586
+		return $ret;
587
+	}
588
+
589
+	/**
590 590
 	 *  List tables into a database
591 591
 	 *
592 592
 	 *  @param	string		$database	Name of database
593 593
 	 *  @param	string		$table		Nmae of table filter ('xxx%')
594 594
 	 *  @return	array					List of tables in an array
595
-     */
596
-    function DDLListTables($database, $table='')
597
-    {
598
-        $listtables=array();
599
-
600
-        $like = '';
601
-        if ($table) $like = "LIKE '".$table."'";
602
-        $sql="SHOW TABLES FROM ".$database." ".$like.";";
603
-        //print $sql;
604
-        $result = $this->query($sql);
605
-        if ($result)
606
-        {
607
-            while($row = $this->fetch_row($result))
608
-            {
609
-                $listtables[] = $row[0];
610
-            }
611
-        }
612
-        return $listtables;
613
-    }
614
-
615
-    /**
595
+	 */
596
+	function DDLListTables($database, $table='')
597
+	{
598
+		$listtables=array();
599
+
600
+		$like = '';
601
+		if ($table) $like = "LIKE '".$table."'";
602
+		$sql="SHOW TABLES FROM ".$database." ".$like.";";
603
+		//print $sql;
604
+		$result = $this->query($sql);
605
+		if ($result)
606
+		{
607
+			while($row = $this->fetch_row($result))
608
+			{
609
+				$listtables[] = $row[0];
610
+			}
611
+		}
612
+		return $listtables;
613
+	}
614
+
615
+	/**
616 616
 	 *	List information of columns into a table.
617 617
 	 *
618 618
 	 *	@param	string	$table		Name of table
619 619
 	 *	@return	array				Tableau des informations des champs de la table
620
-     */
621
-    function DDLInfoTable($table)
622
-    {
623
-        $infotables=array();
624
-
625
-        $sql="SHOW FULL COLUMNS FROM ".$table.";";
626
-
627
-        dol_syslog($sql,LOG_DEBUG);
628
-        $result = $this->query($sql);
629
-        if ($result)
630
-        {
631
-            while($row = $this->fetch_row($result))
632
-            {
633
-                $infotables[] = $row;
634
-            }
635
-        }
636
-        return $infotables;
637
-    }
638
-
639
-    /**
620
+	 */
621
+	function DDLInfoTable($table)
622
+	{
623
+		$infotables=array();
624
+
625
+		$sql="SHOW FULL COLUMNS FROM ".$table.";";
626
+
627
+		dol_syslog($sql,LOG_DEBUG);
628
+		$result = $this->query($sql);
629
+		if ($result)
630
+		{
631
+			while($row = $this->fetch_row($result))
632
+			{
633
+				$infotables[] = $row;
634
+			}
635
+		}
636
+		return $infotables;
637
+	}
638
+
639
+	/**
640 640
 	 *	Create a table into database
641 641
 	 *
642 642
 	 *	@param	    string	$table 			Name of table
@@ -647,18 +647,18 @@  discard block
 block discarded – undo
647 647
 	 *	@param	    array	$fulltext_keys	Tableau des Nom de champs qui seront indexes en fulltext
648 648
 	 *	@param	    array	$keys 			Tableau des champs cles noms => valeur
649 649
 	 *	@return	    int						<0 if KO, >=0 if OK
650
-     */
651
-    function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
652
-    {
653
-	    // FIXME: $fulltext_keys parameter is unused
654
-
655
-        // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
656
-        // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
657
-        $sql = "CREATE TABLE ".$table."(";
658
-        $i=0;
659
-        foreach($fields as $field_name => $field_desc)
660
-        {
661
-        	$sqlfields[$i] = $field_name." ";
650
+	 */
651
+	function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
652
+	{
653
+		// FIXME: $fulltext_keys parameter is unused
654
+
655
+		// cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
656
+		// ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
657
+		$sql = "CREATE TABLE ".$table."(";
658
+		$i=0;
659
+		foreach($fields as $field_name => $field_desc)
660
+		{
661
+			$sqlfields[$i] = $field_name." ";
662 662
 			$sqlfields[$i]  .= $field_desc['type'];
663 663
 			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
664 664
 				$sqlfields[$i]  .= "(".$field_desc['value'].")";
@@ -681,76 +681,76 @@  discard block
 block discarded – undo
681 681
 			if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
682 682
 				$sqlfields[$i]  .= " ".$field_desc['extra'];
683 683
 			}
684
-            $i++;
685
-        }
686
-        if($primary_key != "")
687
-        $pk = "primary key(".$primary_key.")";
688
-
689
-        if(is_array($unique_keys)) {
690
-            $i = 0;
691
-            foreach($unique_keys as $key => $value)
692
-            {
693
-                $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
694
-                $i++;
695
-            }
696
-        }
697
-        if(is_array($keys))
698
-        {
699
-            $i = 0;
700
-            foreach($keys as $key => $value)
701
-            {
702
-                $sqlk[$i] = "KEY ".$key." (".$value.")";
703
-                $i++;
704
-            }
705
-        }
706
-        $sql .= implode(',',$sqlfields);
707
-        if($primary_key != "")
708
-        $sql .= ",".$pk;
709
-        if($unique_keys != "")
710
-        $sql .= ",".implode(',',$sqluq);
711
-        if(is_array($keys))
712
-        $sql .= ",".implode(',',$sqlk);
713
-        $sql .=") engine=".$type;
714
-
715
-        if(! $this->query($sql))
716
-        return -1;
717
-        else
718
-        return 1;
719
-    }
720
-
721
-    /**
722
-     *	Drop a table into database
723
-     *
724
-     *	@param	    string	$table 			Name of table
725
-     *	@return	    int						<0 if KO, >=0 if OK
726
-     */
727
-    function DDLDropTable($table)
728
-    {
729
-    	$sql = "DROP TABLE ".$table;
684
+			$i++;
685
+		}
686
+		if($primary_key != "")
687
+		$pk = "primary key(".$primary_key.")";
688
+
689
+		if(is_array($unique_keys)) {
690
+			$i = 0;
691
+			foreach($unique_keys as $key => $value)
692
+			{
693
+				$sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
694
+				$i++;
695
+			}
696
+		}
697
+		if(is_array($keys))
698
+		{
699
+			$i = 0;
700
+			foreach($keys as $key => $value)
701
+			{
702
+				$sqlk[$i] = "KEY ".$key." (".$value.")";
703
+				$i++;
704
+			}
705
+		}
706
+		$sql .= implode(',',$sqlfields);
707
+		if($primary_key != "")
708
+		$sql .= ",".$pk;
709
+		if($unique_keys != "")
710
+		$sql .= ",".implode(',',$sqluq);
711
+		if(is_array($keys))
712
+		$sql .= ",".implode(',',$sqlk);
713
+		$sql .=") engine=".$type;
714
+
715
+		if(! $this->query($sql))
716
+		return -1;
717
+		else
718
+		return 1;
719
+	}
720
+
721
+	/**
722
+	 *	Drop a table into database
723
+	 *
724
+	 *	@param	    string	$table 			Name of table
725
+	 *	@return	    int						<0 if KO, >=0 if OK
726
+	 */
727
+	function DDLDropTable($table)
728
+	{
729
+		$sql = "DROP TABLE ".$table;
730 730
 
731 731
 		if (! $this->query($sql))
732 732
  			return -1;
733
-    	else
734
-    		return 1;
735
-    }
733
+		else
734
+			return 1;
735
+	}
736 736
 
737
-    /**
737
+	/**
738 738
 	 *	Return a pointer of line with description of a table or field
739 739
 	 *
740 740
 	 *	@param	string		$table	Name of table
741 741
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
742 742
 	 *	@return	bool|mysqli_result	Resultset x (x->Field, x->Type, ...)
743
-     */
744
-    function DDLDescTable($table,$field="")
745
-    {
746
-        $sql="DESC ".$table." ".$field;
743
+	 */
744
+	function DDLDescTable($table,$field="")
745
+	{
746
+		$sql="DESC ".$table." ".$field;
747 747
 
748
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
749
-        $this->_results = $this->query($sql);
750
-        return $this->_results;
751
-    }
748
+		dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
749
+		$this->_results = $this->query($sql);
750
+		return $this->_results;
751
+	}
752 752
 
753
-    /**
753
+	/**
754 754
 	 *	Create a new field into table
755 755
 	 *
756 756
 	 *	@param	string	$table 				Name of table
@@ -758,105 +758,105 @@  discard block
 block discarded – undo
758 758
 	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
759 759
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
760 760
 	 *	@return	int							<0 if KO, >0 if OK
761
-     */
762
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
763
-    {
764
-        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
765
-        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
766
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
767
-        $sql.= $field_desc['type'];
768
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
769
-            if (! in_array($field_desc['type'],array('date','datetime')))
770
-            {
771
-                $sql.= "(".$field_desc['value'].")";
772
-            }
773
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
774
-        $sql.= " ".$field_desc['attribute'];
775
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
776
-        $sql.= " ".$field_desc['null'];
777
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
778
-        {
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
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
785
-        $sql.= " ".$field_desc['extra'];
786
-        $sql.= " ".$field_position;
787
-
788
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
789
-        if($this->query($sql)) {
790
-            return 1;
791
-        }
792
-        return -1;
793
-    }
794
-
795
-    /**
761
+	 */
762
+	function DDLAddField($table,$field_name,$field_desc,$field_position="")
763
+	{
764
+		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
765
+		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
766
+		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
767
+		$sql.= $field_desc['type'];
768
+		if(preg_match("/^[^\s]/i",$field_desc['value']))
769
+			if (! in_array($field_desc['type'],array('date','datetime')))
770
+			{
771
+				$sql.= "(".$field_desc['value'].")";
772
+			}
773
+		if(preg_match("/^[^\s]/i",$field_desc['attribute']))
774
+		$sql.= " ".$field_desc['attribute'];
775
+		if(preg_match("/^[^\s]/i",$field_desc['null']))
776
+		$sql.= " ".$field_desc['null'];
777
+		if(preg_match("/^[^\s]/i",$field_desc['default']))
778
+		{
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
+		if(preg_match("/^[^\s]/i",$field_desc['extra']))
785
+		$sql.= " ".$field_desc['extra'];
786
+		$sql.= " ".$field_position;
787
+
788
+		dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
789
+		if($this->query($sql)) {
790
+			return 1;
791
+		}
792
+		return -1;
793
+	}
794
+
795
+	/**
796 796
 	 *	Update format of a field into a table
797 797
 	 *
798 798
 	 *	@param	string	$table 				Name of table
799 799
 	 *	@param	string	$field_name 		Name of field to modify
800 800
 	 *	@param	string	$field_desc 		Array with description of field format
801 801
 	 *	@return	int							<0 if KO, >0 if OK
802
-     */
803
-    function DDLUpdateField($table,$field_name,$field_desc)
804
-    {
805
-        $sql = "ALTER TABLE ".$table;
806
-        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
807
-        if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
808
-        	$sql.="(".$field_desc['value'].")";
809
-        }
810
-        if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
811
-        {
812
-        	// 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
813
-        	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
814
-        	{
815
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
816
-        		$this->query($sqlbis);
817
-        	}
818
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
819
-        	{
820
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
821
-        		$this->query($sqlbis);
822
-        	}
823
-
824
-        	$sql.=" NOT NULL";
825
-        }
826
-
827
-        if ($field_desc['default'] != '')
828
-        {
802
+	 */
803
+	function DDLUpdateField($table,$field_name,$field_desc)
804
+	{
805
+		$sql = "ALTER TABLE ".$table;
806
+		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
807
+		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
808
+			$sql.="(".$field_desc['value'].")";
809
+		}
810
+		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
811
+		{
812
+			// 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
813
+			if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
814
+			{
815
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
816
+				$this->query($sqlbis);
817
+			}
818
+			elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
819
+			{
820
+				$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
821
+				$this->query($sqlbis);
822
+			}
823
+
824
+			$sql.=" NOT NULL";
825
+		}
826
+
827
+		if ($field_desc['default'] != '')
828
+		{
829 829
 			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
830
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
831
-        }
830
+			elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
831
+		}
832 832
 
833
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
834
-        if (! $this->query($sql))
835
-        return -1;
836
-        else
837
-        return 1;
838
-    }
833
+		dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
834
+		if (! $this->query($sql))
835
+		return -1;
836
+		else
837
+		return 1;
838
+	}
839 839
 
840
-    /**
840
+	/**
841 841
 	 *	Drop a field from table
842 842
 	 *
843 843
 	 *	@param	string	$table 			Name of table
844 844
 	 *	@param	string	$field_name 	Name of field to drop
845 845
 	 *	@return	int						<0 if KO, >0 if OK
846
-     */
847
-    function DDLDropField($table,$field_name)
848
-    {
849
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
850
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
851
-        if ($this->query($sql)) {
852
-            return 1;
853
-        }
854
-	    $this->error=$this->lasterror();
855
-	    return -1;
856
-    }
857
-
858
-
859
-    /**
846
+	 */
847
+	function DDLDropField($table,$field_name)
848
+	{
849
+		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
850
+		dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
851
+		if ($this->query($sql)) {
852
+			return 1;
853
+		}
854
+		$this->error=$this->lasterror();
855
+		return -1;
856
+	}
857
+
858
+
859
+	/**
860 860
 	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
861 861
 	 *
862 862
 	 *	@param	string	$dolibarr_main_db_host 		Ip server or '%'
@@ -864,214 +864,214 @@  discard block
 block discarded – undo
864 864
 	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
865 865
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
866 866
 	 *	@return	int									<0 if KO, >=0 if OK
867
-     */
868
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
869
-    {
870
-        $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
871
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
872
-        $resql=$this->query($sql);
873
-        if (! $resql)
874
-        {
875
-            if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
876
-            {
877
-            	return -1;
878
-            }
879
-            else
867
+	 */
868
+	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
869
+	{
870
+		$sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
871
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
872
+		$resql=$this->query($sql);
873
+		if (! $resql)
874
+		{
875
+			if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
876
+			{
877
+				return -1;
878
+			}
879
+			else
880
+			{
881
+				// If user already exists, we continue to set permissions
882
+				dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
883
+			}
884
+		}
885
+		$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)."'";
886
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
887
+		$resql=$this->query($sql);
888
+		if (! $resql)
889
+		{
890
+			return -1;
891
+		}
892
+
893
+		$sql="FLUSH Privileges";
894
+
895
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
896
+		$resql=$this->query($sql);
897
+		if (! $resql)
898
+		{
899
+			return -1;
900
+		}
901
+
902
+		return 1;
903
+	}
904
+
905
+	/**
906
+	 *	Return charset used to store data in current database
907
+	 *  Note: if we are connected to databasename, it is same result than using SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = "databasename";)
908
+	 *
909
+	 *	@return		string		Charset
910
+	 *  @see getDefaultCollationDatabase
911
+	 */
912
+	function getDefaultCharacterSetDatabase()
913
+	{
914
+		$resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
915
+		if (!$resql)
916
+		{
917
+			// version Mysql < 4.1.1
918
+			return $this->forcecharset;
919
+		}
920
+		$liste=$this->fetch_array($resql);
921
+		$tmpval = $liste['Value'];
922
+
923
+		return $tmpval;
924
+	}
925
+
926
+	/**
927
+	 *	Return list of available charset that can be used to store data in database
928
+	 *
929
+	 *	@return		array|null		List of Charset
930
+	 */
931
+	function getListOfCharacterSet()
932
+	{
933
+		$resql=$this->query('SHOW CHARSET');
934
+		$liste = array();
935
+		if ($resql)
936
+		{
937
+			$i = 0;
938
+			while ($obj = $this->fetch_object($resql) )
939
+			{
940
+				$liste[$i]['charset'] = $obj->Charset;
941
+				$liste[$i]['description'] = $obj->Description;
942
+				$i++;
943
+			}
944
+			$this->free($resql);
945
+		} else {
946
+			// version Mysql < 4.1.1
947
+			return null;
948
+		}
949
+		return $liste;
950
+	}
951
+
952
+	/**
953
+	 *	Return collation used in current database
954
+	 *
955
+	 *	@return		string		Collation value
956
+	 *  @see getDefaultCharacterSetDatabase
957
+	 */
958
+	function getDefaultCollationDatabase()
959
+	{
960
+		$resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
961
+		if (!$resql)
962
+		{
963
+			// version Mysql < 4.1.1
964
+			return $this->forcecollate;
965
+		}
966
+		$liste=$this->fetch_array($resql);
967
+		$tmpval = $liste['Value'];
968
+
969
+		return $tmpval;
970
+	}
971
+
972
+	/**
973
+	 *	Return list of available collation that can be used for database
974
+	 *
975
+	 *	@return		array|null		Liste of Collation
976
+	 */
977
+	function getListOfCollation()
978
+	{
979
+		$resql=$this->query('SHOW COLLATION');
980
+		$liste = array();
981
+		if ($resql)
982
+		{
983
+			$i = 0;
984
+			while ($obj = $this->fetch_object($resql) )
880 985
 			{
881
-            	// If user already exists, we continue to set permissions
882
-            	dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
883
-            }
884
-        }
885
-        $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)."'";
886
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
887
-        $resql=$this->query($sql);
888
-        if (! $resql)
889
-        {
890
-            return -1;
891
-        }
892
-
893
-        $sql="FLUSH Privileges";
894
-
895
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
896
-        $resql=$this->query($sql);
897
-        if (! $resql)
898
-        {
899
-            return -1;
900
-        }
901
-
902
-        return 1;
903
-    }
904
-
905
-    /**
906
-     *	Return charset used to store data in current database
907
-     *  Note: if we are connected to databasename, it is same result than using SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = "databasename";)
908
-     *
909
-     *	@return		string		Charset
910
-     *  @see getDefaultCollationDatabase
911
-     */
912
-    function getDefaultCharacterSetDatabase()
913
-    {
914
-        $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
915
-        if (!$resql)
916
-        {
917
-            // version Mysql < 4.1.1
918
-            return $this->forcecharset;
919
-        }
920
-        $liste=$this->fetch_array($resql);
921
-        $tmpval = $liste['Value'];
922
-
923
-        return $tmpval;
924
-    }
925
-
926
-    /**
927
-     *	Return list of available charset that can be used to store data in database
928
-     *
929
-     *	@return		array|null		List of Charset
930
-     */
931
-    function getListOfCharacterSet()
932
-    {
933
-        $resql=$this->query('SHOW CHARSET');
934
-        $liste = array();
935
-        if ($resql)
936
-        {
937
-            $i = 0;
938
-            while ($obj = $this->fetch_object($resql) )
939
-            {
940
-                $liste[$i]['charset'] = $obj->Charset;
941
-                $liste[$i]['description'] = $obj->Description;
942
-                $i++;
943
-            }
944
-            $this->free($resql);
945
-        } else {
946
-            // version Mysql < 4.1.1
947
-            return null;
948
-        }
949
-        return $liste;
950
-    }
951
-
952
-    /**
953
-     *	Return collation used in current database
954
-     *
955
-     *	@return		string		Collation value
956
-     *  @see getDefaultCharacterSetDatabase
957
-     */
958
-    function getDefaultCollationDatabase()
959
-    {
960
-        $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
961
-        if (!$resql)
962
-        {
963
-            // version Mysql < 4.1.1
964
-            return $this->forcecollate;
965
-        }
966
-        $liste=$this->fetch_array($resql);
967
-        $tmpval = $liste['Value'];
968
-
969
-        return $tmpval;
970
-    }
971
-
972
-    /**
973
-     *	Return list of available collation that can be used for database
974
-     *
975
-     *	@return		array|null		Liste of Collation
976
-     */
977
-    function getListOfCollation()
978
-    {
979
-        $resql=$this->query('SHOW COLLATION');
980
-        $liste = array();
981
-        if ($resql)
982
-        {
983
-            $i = 0;
984
-            while ($obj = $this->fetch_object($resql) )
985
-            {
986
-                $liste[$i]['collation'] = $obj->Collation;
987
-                $i++;
988
-            }
989
-            $this->free($resql);
990
-        } else {
991
-            // version Mysql < 4.1.1
992
-            return null;
993
-        }
994
-        return $liste;
995
-    }
996
-
997
-    /**
986
+				$liste[$i]['collation'] = $obj->Collation;
987
+				$i++;
988
+			}
989
+			$this->free($resql);
990
+		} else {
991
+			// version Mysql < 4.1.1
992
+			return null;
993
+		}
994
+		return $liste;
995
+	}
996
+
997
+	/**
998 998
 	 *	Return full path of dump program
999 999
 	 *
1000 1000
 	 *	@return		string		Full path of dump program
1001
-     */
1002
-    function getPathOfDump()
1003
-    {
1004
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1005
-
1006
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1007
-        if ($resql)
1008
-        {
1009
-            $liste=$this->fetch_array($resql);
1010
-            $basedir=$liste['Value'];
1011
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1012
-        }
1013
-        return $fullpathofdump;
1014
-    }
1015
-
1016
-    /**
1017
-     *	Return full path of restore program
1018
-     *
1019
-     *	@return		string		Full path of restore program
1020
-     */
1021
-    function getPathOfRestore()
1022
-    {
1023
-        $fullpathofimport='/pathtomysql/mysql';
1024
-
1025
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1026
-        if ($resql)
1027
-        {
1028
-            $liste=$this->fetch_array($resql);
1029
-            $basedir=$liste['Value'];
1030
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1031
-        }
1032
-        return $fullpathofimport;
1033
-    }
1034
-
1035
-    /**
1036
-     * Return value of server parameters
1037
-     *
1038
-     * @param	string	$filter		Filter list on a particular value
1001
+	 */
1002
+	function getPathOfDump()
1003
+	{
1004
+		$fullpathofdump='/pathtomysqldump/mysqldump';
1005
+
1006
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1007
+		if ($resql)
1008
+		{
1009
+			$liste=$this->fetch_array($resql);
1010
+			$basedir=$liste['Value'];
1011
+			$fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1012
+		}
1013
+		return $fullpathofdump;
1014
+	}
1015
+
1016
+	/**
1017
+	 *	Return full path of restore program
1018
+	 *
1019
+	 *	@return		string		Full path of restore program
1020
+	 */
1021
+	function getPathOfRestore()
1022
+	{
1023
+		$fullpathofimport='/pathtomysql/mysql';
1024
+
1025
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1026
+		if ($resql)
1027
+		{
1028
+			$liste=$this->fetch_array($resql);
1029
+			$basedir=$liste['Value'];
1030
+			$fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1031
+		}
1032
+		return $fullpathofimport;
1033
+	}
1034
+
1035
+	/**
1036
+	 * Return value of server parameters
1037
+	 *
1038
+	 * @param	string	$filter		Filter list on a particular value
1039 1039
 	 * @return	array				Array of key-values (key=>value)
1040
-     */
1041
-    function getServerParametersValues($filter='')
1042
-    {
1043
-        $result=array();
1044
-
1045
-        $sql='SHOW VARIABLES';
1046
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1047
-        $resql=$this->query($sql);
1048
-        if ($resql)
1049
-        {
1050
-        	while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1051
-        }
1052
-
1053
-        return $result;
1054
-    }
1055
-
1056
-    /**
1057
-     * Return value of server status (current indicators on memory, cache...)
1058
-     *
1059
-     * @param	string	$filter		Filter list on a particular value
1040
+	 */
1041
+	function getServerParametersValues($filter='')
1042
+	{
1043
+		$result=array();
1044
+
1045
+		$sql='SHOW VARIABLES';
1046
+		if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1047
+		$resql=$this->query($sql);
1048
+		if ($resql)
1049
+		{
1050
+			while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1051
+		}
1052
+
1053
+		return $result;
1054
+	}
1055
+
1056
+	/**
1057
+	 * Return value of server status (current indicators on memory, cache...)
1058
+	 *
1059
+	 * @param	string	$filter		Filter list on a particular value
1060 1060
 	 * @return  array				Array of key-values (key=>value)
1061
-     */
1062
-    function getServerStatusValues($filter='')
1063
-    {
1064
-        $result=array();
1065
-
1066
-        $sql='SHOW STATUS';
1067
-        if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1068
-        $resql=$this->query($sql);
1069
-        if ($resql)
1070
-        {
1071
-            while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1072
-        }
1073
-
1074
-        return $result;
1075
-    }
1061
+	 */
1062
+	function getServerStatusValues($filter='')
1063
+	{
1064
+		$result=array();
1065
+
1066
+		$sql='SHOW STATUS';
1067
+		if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1068
+		$resql=$this->query($sql);
1069
+		if ($resql)
1070
+		{
1071
+			while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1072
+		}
1073
+
1074
+		return $result;
1075
+	}
1076 1076
 }
1077 1077
 
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.
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   +263 added lines, -263 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;
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
 	{
1010 1010
 		$sql = "DROP TABLE ".$table;
1011 1011
 
1012
-		if (! $this->query($sql))
1012
+		if (!$this->query($sql))
1013 1013
 			return -1;
1014 1014
 		else
1015 1015
 			return 1;
@@ -1024,14 +1024,14 @@  discard block
 block discarded – undo
1024 1024
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1025 1025
 	 *	@return	int									<0 if KO, >=0 if OK
1026 1026
 	 */
1027
-	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1027
+	function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1028 1028
 	{
1029 1029
 		// Note: using ' on user does not works with pgsql
1030 1030
 		$sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1031 1031
 
1032
-		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1033
-		$resql=$this->query($sql);
1034
-		if (! $resql)
1032
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1033
+		$resql = $this->query($sql);
1034
+		if (!$resql)
1035 1035
 		{
1036 1036
 			return -1;
1037 1037
 		}
@@ -1046,13 +1046,13 @@  discard block
 block discarded – undo
1046 1046
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
1047 1047
 	 *	@return	false|resource		Resultset x (x->attname)
1048 1048
 	 */
1049
-	function DDLDescTable($table,$field="")
1049
+	function DDLDescTable($table, $field = "")
1050 1050
 	{
1051
-		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1052
-		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1053
-		if ($field) $sql.= " AND attname = '".$field."'";
1051
+		$sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1052
+		$sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1053
+		if ($field) $sql .= " AND attname = '".$field."'";
1054 1054
 
1055
-		dol_syslog($sql,LOG_DEBUG);
1055
+		dol_syslog($sql, LOG_DEBUG);
1056 1056
 		$this->_results = $this->query($sql);
1057 1057
 		return $this->_results;
1058 1058
 	}
@@ -1066,32 +1066,32 @@  discard block
 block discarded – undo
1066 1066
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
1067 1067
 	 *	@return	int							<0 if KO, >0 if OK
1068 1068
 	 */
1069
-	function DDLAddField($table,$field_name,$field_desc,$field_position="")
1069
+	function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1070 1070
 	{
1071 1071
 		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1072 1072
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1073
-		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1073
+		$sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
1074 1074
 		$sql .= $field_desc['type'];
1075
-		if(preg_match("/^[^\s]/i",$field_desc['value']))
1076
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1075
+		if (preg_match("/^[^\s]/i", $field_desc['value']))
1076
+		    if (!in_array($field_desc['type'], array('int', 'date', 'datetime')))
1077 1077
 		    {
1078
-		        $sql.= "(".$field_desc['value'].")";
1078
+		        $sql .= "(".$field_desc['value'].")";
1079 1079
 		    }
1080
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1080
+		if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1081 1081
 		$sql .= " ".$field_desc['attribute'];
1082
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1082
+		if (preg_match("/^[^\s]/i", $field_desc['null']))
1083 1083
 		$sql .= " ".$field_desc['null'];
1084
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1085
-		if (preg_match("/null/i",$field_desc['default']))
1084
+		if (preg_match("/^[^\s]/i", $field_desc['default']))
1085
+		if (preg_match("/null/i", $field_desc['default']))
1086 1086
 		$sql .= " default ".$field_desc['default'];
1087 1087
 		else
1088 1088
 		$sql .= " default '".$field_desc['default']."'";
1089
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1089
+		if (preg_match("/^[^\s]/i", $field_desc['extra']))
1090 1090
 		$sql .= " ".$field_desc['extra'];
1091 1091
 		$sql .= " ".$field_position;
1092 1092
 
1093
-		dol_syslog($sql,LOG_DEBUG);
1094
-		if(! $this -> query($sql))
1093
+		dol_syslog($sql, LOG_DEBUG);
1094
+		if (!$this -> query($sql))
1095 1095
 			return -1;
1096 1096
 		return 1;
1097 1097
 	}
@@ -1104,12 +1104,12 @@  discard block
 block discarded – undo
1104 1104
 	 *	@param	string	$field_desc 		Array with description of field format
1105 1105
 	 *	@return	int							<0 if KO, >0 if OK
1106 1106
 	 */
1107
-	function DDLUpdateField($table,$field_name,$field_desc)
1107
+	function DDLUpdateField($table, $field_name, $field_desc)
1108 1108
 	{
1109 1109
 		$sql = "ALTER TABLE ".$table;
1110 1110
 		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1111 1111
 		if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1112
-			$sql.="(".$field_desc['value'].")";
1112
+			$sql .= "(".$field_desc['value'].")";
1113 1113
 		}
1114 1114
 
1115 1115
 		if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
@@ -1117,24 +1117,24 @@  discard block
 block discarded – undo
1117 1117
         	// 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
1118 1118
         	if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
1119 1119
         	{
1120
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1120
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1121 1121
         		$this->query($sqlbis);
1122 1122
         	}
1123 1123
         	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1124 1124
         	{
1125
-        		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1125
+        		$sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1126 1126
         		$this->query($sqlbis);
1127 1127
         	}
1128 1128
 		}
1129 1129
 
1130 1130
 		if ($field_desc['default'] != '')
1131 1131
 		{
1132
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1133
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1132
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql .= " DEFAULT ".$this->escape($field_desc['default']);
1133
+        	elseif ($field_desc['type'] == 'text') $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
1134 1134
 		}
1135 1135
 
1136
-		dol_syslog($sql,LOG_DEBUG);
1137
-		if (! $this->query($sql))
1136
+		dol_syslog($sql, LOG_DEBUG);
1137
+		if (!$this->query($sql))
1138 1138
 			return -1;
1139 1139
 		return 1;
1140 1140
 	}
@@ -1146,13 +1146,13 @@  discard block
 block discarded – undo
1146 1146
 	 *	@param	string	$field_name 	Name of field to drop
1147 1147
 	 *	@return	int						<0 if KO, >0 if OK
1148 1148
 	 */
1149
-	function DDLDropField($table,$field_name)
1149
+	function DDLDropField($table, $field_name)
1150 1150
 	{
1151
-		$sql= "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1152
-		dol_syslog($sql,LOG_DEBUG);
1153
-		if (! $this->query($sql))
1151
+		$sql = "ALTER TABLE ".$table." DROP COLUMN ".$field_name;
1152
+		dol_syslog($sql, LOG_DEBUG);
1153
+		if (!$this->query($sql))
1154 1154
 		{
1155
-			$this->error=$this->lasterror();
1155
+			$this->error = $this->lasterror();
1156 1156
 			return -1;
1157 1157
 		}
1158 1158
 		return 1;
@@ -1165,10 +1165,10 @@  discard block
 block discarded – undo
1165 1165
 	 */
1166 1166
 	function getDefaultCharacterSetDatabase()
1167 1167
 	{
1168
-		$resql=$this->query('SHOW SERVER_ENCODING');
1168
+		$resql = $this->query('SHOW SERVER_ENCODING');
1169 1169
 		if ($resql)
1170 1170
 		{
1171
-            $liste=$this->fetch_array($resql);
1171
+            $liste = $this->fetch_array($resql);
1172 1172
 		    return $liste['server_encoding'];
1173 1173
 		}
1174 1174
 		else return '';
@@ -1181,7 +1181,7 @@  discard block
 block discarded – undo
1181 1181
 	 */
1182 1182
 	function getListOfCharacterSet()
1183 1183
 	{
1184
-		$resql=$this->query('SHOW SERVER_ENCODING');
1184
+		$resql = $this->query('SHOW SERVER_ENCODING');
1185 1185
 		$liste = array();
1186 1186
 		if ($resql)
1187 1187
 		{
@@ -1206,10 +1206,10 @@  discard block
 block discarded – undo
1206 1206
 	 */
1207 1207
 	function getDefaultCollationDatabase()
1208 1208
 	{
1209
-		$resql=$this->query('SHOW LC_COLLATE');
1209
+		$resql = $this->query('SHOW LC_COLLATE');
1210 1210
 		if ($resql)
1211 1211
 		{
1212
-		    $liste=$this->fetch_array($resql);
1212
+		    $liste = $this->fetch_array($resql);
1213 1213
 			return $liste['lc_collate'];
1214 1214
 		}
1215 1215
 		else return '';
@@ -1222,12 +1222,12 @@  discard block
 block discarded – undo
1222 1222
 	 */
1223 1223
 	function getListOfCollation()
1224 1224
 	{
1225
-		$resql=$this->query('SHOW LC_COLLATE');
1225
+		$resql = $this->query('SHOW LC_COLLATE');
1226 1226
 		$liste = array();
1227 1227
 		if ($resql)
1228 1228
 		{
1229 1229
 			$i = 0;
1230
-			while ($obj = $this->fetch_object($resql) )
1230
+			while ($obj = $this->fetch_object($resql))
1231 1231
 			{
1232 1232
 				$liste[$i]['collation'] = $obj->lc_collate;
1233 1233
 				$i++;
@@ -1246,21 +1246,21 @@  discard block
 block discarded – undo
1246 1246
 	 */
1247 1247
 	function getPathOfDump()
1248 1248
 	{
1249
-		$fullpathofdump='/pathtopgdump/pg_dump';
1249
+		$fullpathofdump = '/pathtopgdump/pg_dump';
1250 1250
 
1251 1251
 		if (file_exists('/usr/bin/pg_dump'))
1252 1252
 		{
1253
-		    $fullpathofdump='/usr/bin/pg_dump';
1253
+		    $fullpathofdump = '/usr/bin/pg_dump';
1254 1254
 		}
1255 1255
 		else
1256 1256
 		{
1257 1257
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1258
-		    $resql=$this->query('SHOW data_directory');
1258
+		    $resql = $this->query('SHOW data_directory');
1259 1259
     		if ($resql)
1260 1260
     		{
1261
-    			$liste=$this->fetch_array($resql);
1262
-    			$basedir=$liste['data_directory'];
1263
-    			$fullpathofdump=preg_replace('/data$/','bin',$basedir).'/pg_dump';
1261
+    			$liste = $this->fetch_array($resql);
1262
+    			$basedir = $liste['data_directory'];
1263
+    			$fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1264 1264
     		}
1265 1265
 		}
1266 1266
 
@@ -1275,23 +1275,23 @@  discard block
 block discarded – undo
1275 1275
 	function getPathOfRestore()
1276 1276
 	{
1277 1277
 		//$tool='pg_restore';
1278
-		$tool='psql';
1278
+		$tool = 'psql';
1279 1279
 
1280
-		$fullpathofdump='/pathtopgrestore/'.$tool;
1280
+		$fullpathofdump = '/pathtopgrestore/'.$tool;
1281 1281
 
1282 1282
         if (file_exists('/usr/bin/'.$tool))
1283 1283
         {
1284
-            $fullpathofdump='/usr/bin/'.$tool;
1284
+            $fullpathofdump = '/usr/bin/'.$tool;
1285 1285
         }
1286 1286
         else
1287 1287
         {
1288 1288
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1289
-            $resql=$this->query('SHOW data_directory');
1289
+            $resql = $this->query('SHOW data_directory');
1290 1290
             if ($resql)
1291 1291
             {
1292
-                $liste=$this->fetch_array($resql);
1293
-                $basedir=$liste['data_directory'];
1294
-                $fullpathofdump=preg_replace('/data$/','bin',$basedir).'/'.$tool;
1292
+                $liste = $this->fetch_array($resql);
1293
+                $basedir = $liste['data_directory'];
1294
+                $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1295 1295
             }
1296 1296
         }
1297 1297
 
@@ -1304,16 +1304,16 @@  discard block
 block discarded – undo
1304 1304
 	 * @param	string	$filter		Filter list on a particular value
1305 1305
 	 * @return	array				Array of key-values (key=>value)
1306 1306
 	 */
1307
-	function getServerParametersValues($filter='')
1307
+	function getServerParametersValues($filter = '')
1308 1308
 	{
1309
-		$result=array();
1309
+		$result = array();
1310 1310
 
1311
-		$resql='select name,setting from pg_settings';
1312
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1313
-		$resql=$this->query($resql);
1311
+		$resql = 'select name,setting from pg_settings';
1312
+		if ($filter) $resql .= " WHERE name = '".$this->escape($filter)."'";
1313
+		$resql = $this->query($resql);
1314 1314
 		if ($resql)
1315 1315
 		{
1316
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1316
+			while ($obj = $this->fetch_object($resql)) $result[$obj->name] = $obj->setting;
1317 1317
 		}
1318 1318
 
1319 1319
 		return $result;
@@ -1325,7 +1325,7 @@  discard block
 block discarded – undo
1325 1325
 	 * @param	string	$filter		Filter list on a particular value
1326 1326
 	 * @return  array				Array of key-values (key=>value)
1327 1327
 	 */
1328
-	function getServerStatusValues($filter='')
1328
+	function getServerStatusValues($filter = '')
1329 1329
 	{
1330 1330
 		/* This is to return current running requests.
1331 1331
 		$sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
Please login to merge, or discard this patch.
Braces   +160 added lines, -93 removed lines patch added patch discarded remove patch
@@ -67,8 +67,12 @@  discard block
 block discarded – undo
67 67
 		global $conf,$langs;
68 68
 
69 69
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
70
-		if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
71
-		if (! empty($conf->db->dolibarr_main_db_collation))	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
70
+		if (! empty($conf->db->character_set)) {
71
+			$this->forcecharset=$conf->db->character_set;
72
+		}
73
+		if (! empty($conf->db->dolibarr_main_db_collation)) {
74
+			$this->forcecollate=$conf->db->dolibarr_main_db_collation;
75
+		}
72 76
 
73 77
 		$this->database_user=$user;
74 78
         $this->database_host=$host;
@@ -104,8 +108,7 @@  discard block
 block discarded – undo
104 108
 		{
105 109
 			$this->connected = true;
106 110
 			$this->ok = true;
107
-		}
108
-		else
111
+		} else
109 112
 		{
110 113
 			// host, login ou password incorrect
111 114
 			$this->connected = false;
@@ -122,8 +125,7 @@  discard block
 block discarded – undo
122 125
 				$this->database_selected = true;
123 126
 				$this->database_name = $name;
124 127
 				$this->ok = true;
125
-			}
126
-			else
128
+			} else
127 129
 			{
128 130
 				$this->database_selected = false;
129 131
 				$this->database_name = '';
@@ -131,8 +133,7 @@  discard block
 block discarded – undo
131 133
 				$this->error=$this->error();
132 134
 				dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error,LOG_ERR);
133 135
 			}
134
-		}
135
-		else
136
+		} else
136 137
 		{
137 138
 			// Pas de selection de base demandee, ok ou ko
138 139
 			$this->database_selected = false;
@@ -172,9 +173,13 @@  discard block
 block discarded – undo
172 173
 
173 174
 		    if ($type == 'auto')
174 175
 		    {
175
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
176
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
177
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
176
+              if (preg_match('/ALTER TABLE/i',$line)) {
177
+              	$type='dml';
178
+              } else if (preg_match('/CREATE TABLE/i',$line)) {
179
+              	$type='dml';
180
+              } else if (preg_match('/DROP TABLE/i',$line)) {
181
+              	$type='dml';
182
+              }
178 183
 		    }
179 184
 
180 185
     		$line=preg_replace('/ as signed\)/i',' as integer)',$line);
@@ -321,10 +326,12 @@  discard block
 block discarded – undo
321 326
 			// DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
322 327
 			if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
323 328
 			{
324
-				if ($reg[1] == $reg[2])	// If same table, we remove second one
329
+				if ($reg[1] == $reg[2]) {
330
+					// If same table, we remove second one
325 331
 				{
326 332
 					$line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
327 333
 				}
334
+				}
328 335
 			}
329 336
 
330 337
 			// Remove () in the tables in FROM if 1 table
@@ -351,7 +358,9 @@  discard block
 block discarded – undo
351 358
 			// By default we do not (should be already done by db->escape function if required
352 359
 			// except for sql insert in data file that are mysql escaped so we removed them to
353 360
 			// be compatible with standard_conforming_strings=on that considers \ as ordinary character).
354
-			if ($unescapeslashquot) $line=preg_replace("/\\\'/","''",$line);
361
+			if ($unescapeslashquot) {
362
+				$line=preg_replace("/\\\'/","''",$line);
363
+			}
355 364
 
356 365
 			//print "type=".$type." newline=".$line."<br>\n";
357 366
 		}
@@ -369,8 +378,11 @@  discard block
 block discarded – undo
369 378
 	 */
370 379
 	function select_db($database)
371 380
 	{
372
-		if ($database == $this->database_name) return true;
373
-		else return false;
381
+		if ($database == $this->database_name) {
382
+			return true;
383
+		} else {
384
+			return false;
385
+		}
374 386
 	}
375 387
 
376 388
 	/**
@@ -397,7 +409,10 @@  discard block
 block discarded – undo
397 409
 		$name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
398 410
 		$port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
399 411
 
400
-		if (! $name) $name="postgres";    // When try to connect using admin user
412
+		if (! $name) {
413
+			$name="postgres";
414
+		}
415
+		// When try to connect using admin user
401 416
 
402 417
 		// try first Unix domain socket (local)
403 418
 		if ((! empty($host) && $host == "socket") && ! defined('NOLOCALSOCKETPGCONNECT'))
@@ -409,8 +424,12 @@  discard block
 block discarded – undo
409 424
 		// if local connection failed or not requested, use TCP/IP
410 425
 		if (! $this->db)
411 426
 		{
412
-		    if (! $host) $host = "localhost";
413
-			if (! $port) $port = 5432;
427
+		    if (! $host) {
428
+		    	$host = "localhost";
429
+		    }
430
+			if (! $port) {
431
+				$port = 5432;
432
+			}
414 433
 
415 434
 			$con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
416 435
 			$this->db = @pg_connect($con_string);
@@ -463,7 +482,9 @@  discard block
 block discarded – undo
463 482
     {
464 483
         if ($this->db)
465 484
         {
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);
485
+          if ($this->transaction_opened > 0) {
486
+          	dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
487
+          }
467 488
           $this->connected=false;
468 489
           return pg_close($this->db);
469 490
         }
@@ -498,8 +519,9 @@  discard block
 block discarded – undo
498 519
 				{
499 520
 					$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 521
 					dol_syslog("Warning: Bad formed request converted into ".$query,LOG_WARNING);
522
+				} else {
523
+					$loop=false;
501 524
 				}
502
-				else $loop=false;
503 525
 			}
504 526
 		}
505 527
 
@@ -508,30 +530,39 @@  discard block
 block discarded – undo
508 530
 			@pg_query($this->db, 'SAVEPOINT mysavepoint');
509 531
 		}
510 532
 
511
-		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
533
+		if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) {
534
+			dol_syslog('sql='.$query, LOG_DEBUG);
535
+		}
512 536
 
513 537
 		$ret = @pg_query($this->db, $query);
514 538
 
515 539
 		//print $query;
516
-		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) // Si requete utilisateur, on la sauvegarde ainsi que son resultset
540
+		if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) {
541
+			// Si requete utilisateur, on la sauvegarde ainsi que son resultset
517 542
 		{
518 543
 			if (! $ret)
519 544
 			{
520 545
 			    if ($this->errno() != 'DB_ERROR_25P02')	// Do not overwrite errors if this is a consecutive error
521 546
 			    {
522 547
     				$this->lastqueryerror = $query;
548
+		}
523 549
     				$this->lasterror = $this->error();
524 550
     				$this->lasterrno = $this->errno();
525 551
 
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
552
+    				if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
553
+    					dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
554
+    				}
555
+    				// Log of request was not yet done previously
527 556
 					dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
528 557
 					dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
529 558
 			    }
530 559
 
531
-				if ($usesavepoint && $this->transaction_opened)	// Warning, after that errno will be erased
560
+				if ($usesavepoint && $this->transaction_opened) {
561
+					// Warning, after that errno will be erased
532 562
 				{
533 563
 					@pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
534 564
 				}
565
+				}
535 566
 			}
536 567
 			$this->lastquery=$query;
537 568
 			$this->_results = $ret;
@@ -621,7 +652,9 @@  discard block
 block discarded – undo
621 652
         // If resultset not provided, we take the last used by connexion
622 653
 		if (! is_resource($resultset)) { $resultset=$this->_results; }
623 654
 		// Si resultset en est un, on libere la memoire
624
-		if (is_resource($resultset)) pg_free_result($resultset);
655
+		if (is_resource($resultset)) {
656
+			pg_free_result($resultset);
657
+		}
625 658
 	}
626 659
 
627 660
 
@@ -635,10 +668,17 @@  discard block
 block discarded – undo
635 668
 	function plimit($limit=0,$offset=0)
636 669
 	{
637 670
 		global $conf;
638
-        if (empty($limit)) return "";
639
-		if ($limit < 0) $limit=$conf->liste_limit;
640
-		if ($offset > 0) return " LIMIT ".$limit." OFFSET ".$offset." ";
641
-		else return " LIMIT $limit ";
671
+        if (empty($limit)) {
672
+        	return "";
673
+        }
674
+		if ($limit < 0) {
675
+			$limit=$conf->liste_limit;
676
+		}
677
+		if ($offset > 0) {
678
+			return " LIMIT ".$limit." OFFSET ".$offset." ";
679
+		} else {
680
+			return " LIMIT $limit ";
681
+		}
642 682
 	}
643 683
 
644 684
 
@@ -688,8 +728,7 @@  discard block
 block discarded – undo
688 728
 		if (! $this->connected) {
689 729
 			// Si il y a eu echec de connexion, $this->db n'est pas valide.
690 730
 			return 'DB_ERROR_FAILED_TO_CONNECT';
691
-		}
692
-		else {
731
+		} else {
693 732
 			// Constants to convert error code to a generic Dolibarr error code
694 733
 			$errorcode_map = array(
695 734
 			1004 => 'DB_ERROR_CANNOT_CREATE',
@@ -844,8 +883,12 @@  discard block
 block discarded – undo
844 883
 	 */
845 884
 	function DDLCreateDb($database,$charset='',$collation='',$owner='')
846 885
 	{
847
-	    if (empty($charset))   $charset=$this->forcecharset;
848
-		if (empty($collation)) $collation=$this->forcecollate;
886
+	    if (empty($charset)) {
887
+	    	$charset=$this->forcecharset;
888
+	    }
889
+		if (empty($collation)) {
890
+			$collation=$this->forcecollate;
891
+		}
849 892
 
850 893
 		// Test charset match LC_TYPE (pgsql error otherwise)
851 894
 		//print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
@@ -868,7 +911,9 @@  discard block
 block discarded – undo
868 911
 		$listtables=array();
869 912
 
870 913
 		$like = '';
871
-		if ($table) $like = " AND table_name LIKE '".$table."'";
914
+		if ($table) {
915
+			$like = " AND table_name LIKE '".$table."'";
916
+		}
872 917
 		$result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$like." ORDER BY table_name");
873 918
         if ($result)
874 919
         {
@@ -944,26 +989,27 @@  discard block
 block discarded – undo
944 989
 		{
945 990
 			$sqlfields[$i] = $field_name." ";
946 991
 			$sqlfields[$i]  .= $field_desc['type'];
947
-			if( preg_match("/^[^\s]/i",$field_desc['value']))
948
-			$sqlfields[$i]  .= "(".$field_desc['value'].")";
949
-			else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
950
-			$sqlfields[$i]  .= " ".$field_desc['attribute'];
951
-			else if( preg_match("/^[^\s]/i",$field_desc['default']))
992
+			if( preg_match("/^[^\s]/i",$field_desc['value'])) {
993
+						$sqlfields[$i]  .= "(".$field_desc['value'].")";
994
+			} else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
995
+						$sqlfields[$i]  .= " ".$field_desc['attribute'];
996
+			} else if( preg_match("/^[^\s]/i",$field_desc['default']))
952 997
 			{
953
-				if(preg_match("/null/i",$field_desc['default']))
954
-				$sqlfields[$i]  .= " default ".$field_desc['default'];
955
-				else
956
-				$sqlfields[$i]  .= " default '".$field_desc['default']."'";
998
+				if(preg_match("/null/i",$field_desc['default'])) {
999
+								$sqlfields[$i]  .= " default ".$field_desc['default'];
1000
+				} else {
1001
+								$sqlfields[$i]  .= " default '".$field_desc['default']."'";
1002
+				}
1003
+			} else if( preg_match("/^[^\s]/i",$field_desc['null'])) {
1004
+						$sqlfields[$i]  .= " ".$field_desc['null'];
1005
+			} else if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
1006
+						$sqlfields[$i]  .= " ".$field_desc['extra'];
957 1007
 			}
958
-			else if( preg_match("/^[^\s]/i",$field_desc['null']))
959
-			$sqlfields[$i]  .= " ".$field_desc['null'];
960
-
961
-			else if( preg_match("/^[^\s]/i",$field_desc['extra']))
962
-			$sqlfields[$i]  .= " ".$field_desc['extra'];
963 1008
 			$i++;
964 1009
 		}
965
-		if($primary_key != "")
966
-		$pk = "primary key(".$primary_key.")";
1010
+		if($primary_key != "") {
1011
+				$pk = "primary key(".$primary_key.")";
1012
+		}
967 1013
 
968 1014
 		if(is_array($unique_keys))
969 1015
 		{
@@ -984,19 +1030,23 @@  discard block
 block discarded – undo
984 1030
 			}
985 1031
 		}
986 1032
 		$sql .= implode(',',$sqlfields);
987
-		if($primary_key != "")
988
-		$sql .= ",".$pk;
989
-		if(is_array($unique_keys))
990
-		$sql .= ",".implode(',',$sqluq);
991
-		if(is_array($keys))
992
-		$sql .= ",".implode(',',$sqlk);
1033
+		if($primary_key != "") {
1034
+				$sql .= ",".$pk;
1035
+		}
1036
+		if(is_array($unique_keys)) {
1037
+				$sql .= ",".implode(',',$sqluq);
1038
+		}
1039
+		if(is_array($keys)) {
1040
+				$sql .= ",".implode(',',$sqlk);
1041
+		}
993 1042
 		$sql .=") type=".$type;
994 1043
 
995 1044
 		dol_syslog($sql,LOG_DEBUG);
996
-		if(! $this->query($sql))
997
-		return -1;
998
-		else
999
-		return 1;
1045
+		if(! $this->query($sql)) {
1046
+				return -1;
1047
+		} else {
1048
+				return 1;
1049
+		}
1000 1050
 	}
1001 1051
 
1002 1052
 	/**
@@ -1009,10 +1059,11 @@  discard block
 block discarded – undo
1009 1059
 	{
1010 1060
 		$sql = "DROP TABLE ".$table;
1011 1061
 
1012
-		if (! $this->query($sql))
1013
-			return -1;
1014
-		else
1015
-			return 1;
1062
+		if (! $this->query($sql)) {
1063
+					return -1;
1064
+		} else {
1065
+					return 1;
1066
+		}
1016 1067
 	}
1017 1068
 
1018 1069
 	/**
@@ -1050,7 +1101,9 @@  discard block
 block discarded – undo
1050 1101
 	{
1051 1102
 		$sql ="SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$table."' AND attrelid = typrelid";
1052 1103
 		$sql.=" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1053
-		if ($field) $sql.= " AND attname = '".$field."'";
1104
+		if ($field) {
1105
+			$sql.= " AND attname = '".$field."'";
1106
+		}
1054 1107
 
1055 1108
 		dol_syslog($sql,LOG_DEBUG);
1056 1109
 		$this->_results = $this->query($sql);
@@ -1072,27 +1125,33 @@  discard block
 block discarded – undo
1072 1125
 		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1073 1126
 		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
1074 1127
 		$sql .= $field_desc['type'];
1075
-		if(preg_match("/^[^\s]/i",$field_desc['value']))
1076
-		    if (! in_array($field_desc['type'],array('int','date','datetime')))
1128
+		if(preg_match("/^[^\s]/i",$field_desc['value'])) {
1129
+				    if (! in_array($field_desc['type'],array('int','date','datetime')))
1077 1130
 		    {
1078 1131
 		        $sql.= "(".$field_desc['value'].")";
1132
+		}
1079 1133
 		    }
1080
-		if (preg_match("/^[^\s]/i",$field_desc['attribute']))
1081
-		$sql .= " ".$field_desc['attribute'];
1082
-		if (preg_match("/^[^\s]/i",$field_desc['null']))
1083
-		$sql .= " ".$field_desc['null'];
1084
-		if (preg_match("/^[^\s]/i",$field_desc['default']))
1085
-		if (preg_match("/null/i",$field_desc['default']))
1134
+		if (preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1135
+				$sql .= " ".$field_desc['attribute'];
1136
+		}
1137
+		if (preg_match("/^[^\s]/i",$field_desc['null'])) {
1138
+				$sql .= " ".$field_desc['null'];
1139
+		}
1140
+		if (preg_match("/^[^\s]/i",$field_desc['default'])) {
1141
+				if (preg_match("/null/i",$field_desc['default']))
1086 1142
 		$sql .= " default ".$field_desc['default'];
1087
-		else
1088
-		$sql .= " default '".$field_desc['default']."'";
1089
-		if (preg_match("/^[^\s]/i",$field_desc['extra']))
1090
-		$sql .= " ".$field_desc['extra'];
1143
+		} else {
1144
+				$sql .= " default '".$field_desc['default']."'";
1145
+		}
1146
+		if (preg_match("/^[^\s]/i",$field_desc['extra'])) {
1147
+				$sql .= " ".$field_desc['extra'];
1148
+		}
1091 1149
 		$sql .= " ".$field_position;
1092 1150
 
1093 1151
 		dol_syslog($sql,LOG_DEBUG);
1094
-		if(! $this -> query($sql))
1095
-			return -1;
1152
+		if(! $this -> query($sql)) {
1153
+					return -1;
1154
+		}
1096 1155
 		return 1;
1097 1156
 	}
1098 1157
 
@@ -1119,8 +1178,7 @@  discard block
 block discarded – undo
1119 1178
         	{
1120 1179
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
1121 1180
         		$this->query($sqlbis);
1122
-        	}
1123
-        	elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1181
+        	} elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
1124 1182
         	{
1125 1183
         		$sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
1126 1184
         		$this->query($sqlbis);
@@ -1129,13 +1187,18 @@  discard block
 block discarded – undo
1129 1187
 
1130 1188
 		if ($field_desc['default'] != '')
1131 1189
 		{
1132
-			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
1133
-        	elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";							// Default not supported on text fields
1190
+			if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
1191
+				$sql.=" DEFAULT ".$this->escape($field_desc['default']);
1192
+			} elseif ($field_desc['type'] == 'text') {
1193
+        		$sql.=" DEFAULT '".$this->escape($field_desc['default'])."'";
1194
+        	}
1195
+        	// Default not supported on text fields
1134 1196
 		}
1135 1197
 
1136 1198
 		dol_syslog($sql,LOG_DEBUG);
1137
-		if (! $this->query($sql))
1138
-			return -1;
1199
+		if (! $this->query($sql)) {
1200
+					return -1;
1201
+		}
1139 1202
 		return 1;
1140 1203
 	}
1141 1204
 
@@ -1170,8 +1233,9 @@  discard block
 block discarded – undo
1170 1233
 		{
1171 1234
             $liste=$this->fetch_array($resql);
1172 1235
 		    return $liste['server_encoding'];
1236
+		} else {
1237
+			return '';
1173 1238
 		}
1174
-		else return '';
1175 1239
 	}
1176 1240
 
1177 1241
 	/**
@@ -1211,8 +1275,9 @@  discard block
 block discarded – undo
1211 1275
 		{
1212 1276
 		    $liste=$this->fetch_array($resql);
1213 1277
 			return $liste['lc_collate'];
1278
+		} else {
1279
+			return '';
1214 1280
 		}
1215
-		else return '';
1216 1281
 	}
1217 1282
 
1218 1283
 	/**
@@ -1251,8 +1316,7 @@  discard block
 block discarded – undo
1251 1316
 		if (file_exists('/usr/bin/pg_dump'))
1252 1317
 		{
1253 1318
 		    $fullpathofdump='/usr/bin/pg_dump';
1254
-		}
1255
-		else
1319
+		} else
1256 1320
 		{
1257 1321
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1258 1322
 		    $resql=$this->query('SHOW data_directory');
@@ -1282,8 +1346,7 @@  discard block
 block discarded – undo
1282 1346
         if (file_exists('/usr/bin/'.$tool))
1283 1347
         {
1284 1348
             $fullpathofdump='/usr/bin/'.$tool;
1285
-        }
1286
-        else
1349
+        } else
1287 1350
         {
1288 1351
             // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1289 1352
             $resql=$this->query('SHOW data_directory');
@@ -1309,11 +1372,15 @@  discard block
 block discarded – undo
1309 1372
 		$result=array();
1310 1373
 
1311 1374
 		$resql='select name,setting from pg_settings';
1312
-		if ($filter) $resql.=" WHERE name = '".$this->escape($filter)."'";
1375
+		if ($filter) {
1376
+			$resql.=" WHERE name = '".$this->escape($filter)."'";
1377
+		}
1313 1378
 		$resql=$this->query($resql);
1314 1379
 		if ($resql)
1315 1380
 		{
1316
-			while ($obj=$this->fetch_object($resql)) $result[$obj->name]=$obj->setting;
1381
+			while ($obj=$this->fetch_object($resql)) {
1382
+				$result[$obj->name]=$obj->setting;
1383
+			}
1317 1384
 		}
1318 1385
 
1319 1386
 		return $result;
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.
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.
Indentation   +1126 added lines, -1126 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
+	}
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
+	}
694 694
 
695
-    /**
696
-     * Get last ID after an insert INSERT
697
-     *
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
+	}
771 741
 
772
-        return $return;
773
-    }
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;
774 759
 
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
+		}
775 771
 
776
-    /**
777
-     * Return connexion ID
778
-     *
772
+		return $return;
773
+	}
774
+
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,383 +878,383 @@  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
-    /**
949
-     *	Drop a table into database
950
-     *
951
-     *	@param	    string	$table 			Name of table
952
-     *	@return	    int						<0 if KO, >=0 if OK
953
-     */
954
-    function DDLDropTable($table)
955
-    {
956
-    	$sql = "DROP TABLE ".$table;
957
-
958
-    	if (! $this->query($sql))
959
-    		return -1;
960
-    	else
961
-    		return 1;
962
-    }
963
-
964
-    /**
948
+	/**
949
+	 *	Drop a table into database
950
+	 *
951
+	 *	@param	    string	$table 			Name of table
952
+	 *	@return	    int						<0 if KO, >=0 if OK
953
+	 */
954
+	function DDLDropTable($table)
955
+	{
956
+		$sql = "DROP TABLE ".$table;
957
+
958
+		if (! $this->query($sql))
959
+			return -1;
960
+		else
961
+			return 1;
962
+	}
963
+
964
+	/**
965 965
 	 *	Return a pointer of line with description of a table or field
966
-     *
966
+	 *
967 967
 	 *	@param	string		$table	Name of table
968 968
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
969 969
 	 *	@return	SQLite3Result		Resource
970
-     */
971
-    function DDLDescTable($table,$field="")
972
-    {
973
-        $sql="DESC ".$table." ".$field;
970
+	 */
971
+	function DDLDescTable($table,$field="")
972
+	{
973
+		$sql="DESC ".$table." ".$field;
974 974
 
975
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
976
-        $this->_results = $this->query($sql);
977
-        return $this->_results;
978
-    }
975
+		dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
976
+		$this->_results = $this->query($sql);
977
+		return $this->_results;
978
+	}
979 979
 
980
-    /**
980
+	/**
981 981
 	 *	Create a new field into table
982
-     *
982
+	 *
983 983
 	 *	@param	string	$table 				Name of table
984 984
 	 *	@param	string	$field_name 		Name of field to add
985 985
 	 *	@param	string	$field_desc 		Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
986 986
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
987 987
 	 *	@return	int							<0 if KO, >0 if OK
988
-     */
989
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
990
-    {
991
-        // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
992
-        // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
993
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
994
-        $sql.= $field_desc['type'];
995
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
996
-        if (! in_array($field_desc['type'],array('date','datetime')))
997
-        {
998
-            $sql.= "(".$field_desc['value'].")";
999
-        }
1000
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1001
-        $sql.= " ".$field_desc['attribute'];
1002
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1003
-        $sql.= " ".$field_desc['null'];
1004
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
1005
-        {
1006
-            if(preg_match("/null/i",$field_desc['default']))
1007
-            $sql.= " default ".$field_desc['default'];
1008
-            else
1009
-            $sql.= " default '".$field_desc['default']."'";
1010
-        }
1011
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1012
-        $sql.= " ".$field_desc['extra'];
1013
-        $sql.= " ".$field_position;
1014
-
1015
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1016
-        if(! $this->query($sql))
1017
-        {
1018
-            return -1;
1019
-        }
1020
-        return 1;
1021
-    }
988
+	 */
989
+	function DDLAddField($table,$field_name,$field_desc,$field_position="")
990
+	{
991
+		// cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
992
+		// ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
993
+		$sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
994
+		$sql.= $field_desc['type'];
995
+		if(preg_match("/^[^\s]/i",$field_desc['value']))
996
+		if (! in_array($field_desc['type'],array('date','datetime')))
997
+		{
998
+			$sql.= "(".$field_desc['value'].")";
999
+		}
1000
+		if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1001
+		$sql.= " ".$field_desc['attribute'];
1002
+		if(preg_match("/^[^\s]/i",$field_desc['null']))
1003
+		$sql.= " ".$field_desc['null'];
1004
+		if(preg_match("/^[^\s]/i",$field_desc['default']))
1005
+		{
1006
+			if(preg_match("/null/i",$field_desc['default']))
1007
+			$sql.= " default ".$field_desc['default'];
1008
+			else
1009
+			$sql.= " default '".$field_desc['default']."'";
1010
+		}
1011
+		if(preg_match("/^[^\s]/i",$field_desc['extra']))
1012
+		$sql.= " ".$field_desc['extra'];
1013
+		$sql.= " ".$field_position;
1014
+
1015
+		dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1016
+		if(! $this->query($sql))
1017
+		{
1018
+			return -1;
1019
+		}
1020
+		return 1;
1021
+	}
1022 1022
 
1023
-    /**
1023
+	/**
1024 1024
 	 *	Update format of a field into a table
1025
-     *
1025
+	 *
1026 1026
 	 *	@param	string	$table 				Name of table
1027 1027
 	 *	@param	string	$field_name 		Name of field to modify
1028 1028
 	 *	@param	string	$field_desc 		Array with description of field format
1029 1029
 	 *	@return	int							<0 if KO, >0 if OK
1030
-     */
1031
-    function DDLUpdateField($table,$field_name,$field_desc)
1032
-    {
1033
-        $sql = "ALTER TABLE ".$table;
1034
-        $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1035
-        if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1036
-            $sql.="(".$field_desc['value'].")";
1037
-        }
1038
-
1039
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1040
-        if (! $this->query($sql))
1041
-            return -1;
1042
-        return 1;
1043
-    }
1030
+	 */
1031
+	function DDLUpdateField($table,$field_name,$field_desc)
1032
+	{
1033
+		$sql = "ALTER TABLE ".$table;
1034
+		$sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1035
+		if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1036
+			$sql.="(".$field_desc['value'].")";
1037
+		}
1038
+
1039
+		dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1040
+		if (! $this->query($sql))
1041
+			return -1;
1042
+		return 1;
1043
+	}
1044 1044
 
1045
-    /**
1045
+	/**
1046 1046
 	 *	Drop a field from table
1047
-     *
1047
+	 *
1048 1048
 	 *	@param	string	$table 			Name of table
1049 1049
 	 *	@param	string	$field_name 	Name of field to drop
1050 1050
 	 *	@return	int						<0 if KO, >0 if OK
1051
-     */
1052
-    function DDLDropField($table,$field_name)
1053
-    {
1054
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1055
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1056
-        if (! $this->query($sql))
1057
-        {
1058
-            $this->error=$this->lasterror();
1059
-            return -1;
1060
-        }
1061
-        return 1;
1062
-    }
1051
+	 */
1052
+	function DDLDropField($table,$field_name)
1053
+	{
1054
+		$sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1055
+		dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1056
+		if (! $this->query($sql))
1057
+		{
1058
+			$this->error=$this->lasterror();
1059
+			return -1;
1060
+		}
1061
+		return 1;
1062
+	}
1063 1063
 
1064 1064
 
1065
-    /**
1065
+	/**
1066 1066
 	 * 	Create a user and privileges to connect to database (even if database does not exists yet)
1067
-     *
1067
+	 *
1068 1068
 	 *	@param	string	$dolibarr_main_db_host 		Ip serveur
1069 1069
 	 *	@param	string	$dolibarr_main_db_user 		Nom user a creer
1070 1070
 	 *	@param	string	$dolibarr_main_db_pass 		Mot de passe user a creer
1071 1071
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1072 1072
 	 *	@return	int									<0 if KO, >=0 if OK
1073
-     */
1074
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1075
-    {
1076
-        $sql = "INSERT INTO user ";
1077
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1078
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1079
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1080
-
1081
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1082
-        $resql=$this->query($sql);
1083
-        if (! $resql)
1084
-        {
1085
-            return -1;
1086
-        }
1087
-
1088
-        $sql = "INSERT INTO db ";
1089
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1090
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1091
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1092
-
1093
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1094
-        $resql=$this->query($sql);
1095
-        if (! $resql)
1096
-        {
1097
-            return -1;
1098
-        }
1099
-
1100
-        $sql="FLUSH Privileges";
1101
-
1102
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1103
-        $resql=$this->query($sql);
1104
-        if (! $resql)
1105
-        {
1106
-            return -1;
1107
-        }
1108
-        return 1;
1109
-    }
1073
+	 */
1074
+	function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1075
+	{
1076
+		$sql = "INSERT INTO user ";
1077
+		$sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1078
+		$sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1079
+		$sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1080
+
1081
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1082
+		$resql=$this->query($sql);
1083
+		if (! $resql)
1084
+		{
1085
+			return -1;
1086
+		}
1087
+
1088
+		$sql = "INSERT INTO db ";
1089
+		$sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1090
+		$sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1091
+		$sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1092
+
1093
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1094
+		$resql=$this->query($sql);
1095
+		if (! $resql)
1096
+		{
1097
+			return -1;
1098
+		}
1099
+
1100
+		$sql="FLUSH Privileges";
1101
+
1102
+		dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1103
+		$resql=$this->query($sql);
1104
+		if (! $resql)
1105
+		{
1106
+			return -1;
1107
+		}
1108
+		return 1;
1109
+	}
1110 1110
 
1111
-    /**
1111
+	/**
1112 1112
 	 *	Return charset used to store data in database
1113
-     *
1113
+	 *
1114 1114
 	 *	@return		string		Charset
1115
-     */
1116
-    function getDefaultCharacterSetDatabase()
1117
-    {
1118
-        return 'UTF-8';
1119
-    }
1115
+	 */
1116
+	function getDefaultCharacterSetDatabase()
1117
+	{
1118
+		return 'UTF-8';
1119
+	}
1120 1120
 
1121
-    /**
1121
+	/**
1122 1122
 	 *	Return list of available charset that can be used to store data in database
1123
-     *
1123
+	 *
1124 1124
 	 *	@return		array		List of Charset
1125
-     */
1126
-    function getListOfCharacterSet()
1127
-    {
1128
-        $liste = array();
1129
-        $i=0;
1130
-        $liste[$i]['charset'] = 'UTF-8';
1131
-        $liste[$i]['description'] = 'UTF-8';
1132
-        return $liste;
1133
-    }
1134
-
1135
-    /**
1125
+	 */
1126
+	function getListOfCharacterSet()
1127
+	{
1128
+		$liste = array();
1129
+		$i=0;
1130
+		$liste[$i]['charset'] = 'UTF-8';
1131
+		$liste[$i]['description'] = 'UTF-8';
1132
+		return $liste;
1133
+	}
1134
+
1135
+	/**
1136 1136
 	 *	Return collation used in database
1137
-     *
1137
+	 *
1138 1138
 	 *	@return		string		Collation value
1139
-     */
1140
-    function getDefaultCollationDatabase()
1141
-    {
1142
-        return 'UTF-8';
1143
-    }
1139
+	 */
1140
+	function getDefaultCollationDatabase()
1141
+	{
1142
+		return 'UTF-8';
1143
+	}
1144 1144
 
1145
-    /**
1145
+	/**
1146 1146
 	 *	Return list of available collation that can be used for database
1147
-     *
1147
+	 *
1148 1148
 	 *	@return		array		List of Collation
1149
-     */
1150
-    function getListOfCollation()
1151
-    {
1152
-        $liste = array();
1153
-        $i=0;
1154
-        $liste[$i]['charset'] = 'UTF-8';
1155
-        $liste[$i]['description'] = 'UTF-8';
1156
-        return $liste;
1157
-    }
1158
-
1159
-    /**
1149
+	 */
1150
+	function getListOfCollation()
1151
+	{
1152
+		$liste = array();
1153
+		$i=0;
1154
+		$liste[$i]['charset'] = 'UTF-8';
1155
+		$liste[$i]['description'] = 'UTF-8';
1156
+		return $liste;
1157
+	}
1158
+
1159
+	/**
1160 1160
 	 *	Return full path of dump program
1161
-     *
1161
+	 *
1162 1162
 	 *	@return		string		Full path of dump program
1163
-     */
1164
-    function getPathOfDump()
1165
-    {
1166
-	    // FIXME: not for SQLite
1167
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1168
-
1169
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1170
-        if ($resql)
1171
-        {
1172
-            $liste=$this->fetch_array($resql);
1173
-            $basedir=$liste['Value'];
1174
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1175
-        }
1176
-        return $fullpathofdump;
1177
-    }
1163
+	 */
1164
+	function getPathOfDump()
1165
+	{
1166
+		// FIXME: not for SQLite
1167
+		$fullpathofdump='/pathtomysqldump/mysqldump';
1168
+
1169
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1170
+		if ($resql)
1171
+		{
1172
+			$liste=$this->fetch_array($resql);
1173
+			$basedir=$liste['Value'];
1174
+			$fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1175
+		}
1176
+		return $fullpathofdump;
1177
+	}
1178 1178
 
1179
-    /**
1179
+	/**
1180 1180
 	 *	Return full path of restore program
1181
-     *
1181
+	 *
1182 1182
 	 *	@return		string		Full path of restore program
1183
-     */
1184
-    function getPathOfRestore()
1185
-    {
1186
-	    // FIXME: not for SQLite
1187
-        $fullpathofimport='/pathtomysql/mysql';
1188
-
1189
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1190
-        if ($resql)
1191
-        {
1192
-            $liste=$this->fetch_array($resql);
1193
-            $basedir=$liste['Value'];
1194
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1195
-        }
1196
-        return $fullpathofimport;
1197
-    }
1183
+	 */
1184
+	function getPathOfRestore()
1185
+	{
1186
+		// FIXME: not for SQLite
1187
+		$fullpathofimport='/pathtomysql/mysql';
1188
+
1189
+		$resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1190
+		if ($resql)
1191
+		{
1192
+			$liste=$this->fetch_array($resql);
1193
+			$basedir=$liste['Value'];
1194
+			$fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1195
+		}
1196
+		return $fullpathofimport;
1197
+	}
1198 1198
 
1199
-    /**
1200
-     * Return value of server parameters
1201
-     *
1199
+	/**
1200
+	 * Return value of server parameters
1201
+	 *
1202 1202
 	 * @param	string	$filter		Filter list on a particular value
1203 1203
 	 * @return	array				Array of key-values (key=>value)
1204
-     */
1205
-    function getServerParametersValues($filter='')
1206
-    {
1207
-        $result=array();
1208
-        static $pragmas;
1209
-        if (! isset($pragmas)) {
1210
-            // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1211
-            // indépendante de la base de données.
1212
-            // cf. http://www.sqlite.org/pragma.html
1213
-            $pragmas = array(
1214
-                'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1215
-                'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1204
+	 */
1205
+	function getServerParametersValues($filter='')
1206
+	{
1207
+		$result=array();
1208
+		static $pragmas;
1209
+		if (! isset($pragmas)) {
1210
+			// Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1211
+			// indépendante de la base de données.
1212
+			// cf. http://www.sqlite.org/pragma.html
1213
+			$pragmas = array(
1214
+				'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1215
+				'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1216 1216
 				'compile_options', 'data_version',	/*'database_list',*/
1217
-                'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1218
-                'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1219
-                'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
1220
-                'max_page_count', 'page_count', 'page_size', 'parser_trace',
1221
-                'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
1222
-                'reverse_unordered_selects', 'schema_version', 'user_version',
1223
-                'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
1224
-                'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
1225
-                'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
1226
-                'wal_autocheckpoint',
1227
-            );
1228
-        }
1229
-
1230
-        // TODO prendre en compte le filtre
1231
-        foreach($pragmas as $var) {
1232
-            $sql = "PRAGMA $var";
1233
-            $resql=$this->query($sql);
1234
-            if ($resql)
1235
-            {
1236
-                $obj = $this->fetch_row($resql);
1237
-                //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1238
-                $result[$var] = $obj[0];
1239
-            }
1240
-            else {
1241
-                // TODO Récupérer le message
1242
-                $result[$var] = 'FAIL';
1243
-            }
1244
-        }
1245
-        return $result;
1246
-    }
1217
+				'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1218
+				'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1219
+				'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
1220
+				'max_page_count', 'page_count', 'page_size', 'parser_trace',
1221
+				'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
1222
+				'reverse_unordered_selects', 'schema_version', 'user_version',
1223
+				'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
1224
+				'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
1225
+				'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
1226
+				'wal_autocheckpoint',
1227
+			);
1228
+		}
1229
+
1230
+		// TODO prendre en compte le filtre
1231
+		foreach($pragmas as $var) {
1232
+			$sql = "PRAGMA $var";
1233
+			$resql=$this->query($sql);
1234
+			if ($resql)
1235
+			{
1236
+				$obj = $this->fetch_row($resql);
1237
+				//dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1238
+				$result[$var] = $obj[0];
1239
+			}
1240
+			else {
1241
+				// TODO Récupérer le message
1242
+				$result[$var] = 'FAIL';
1243
+			}
1244
+		}
1245
+		return $result;
1246
+	}
1247 1247
 
1248
-    /**
1249
-     * Return value of server status
1250
-     *
1248
+	/**
1249
+	 * Return value of server status
1250
+	 *
1251 1251
 	 * @param	string	$filter		Filter list on a particular value
1252 1252
 	 * @return  array				Array of key-values (key=>value)
1253
-     */
1254
-    function getServerStatusValues($filter='')
1255
-    {
1256
-        $result=array();
1257
-        /*
1253
+	 */
1254
+	function getServerStatusValues($filter='')
1255
+	{
1256
+		$result=array();
1257
+		/*
1258 1258
         $sql='SHOW STATUS';
1259 1259
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1260 1260
         $resql=$this->query($sql);
@@ -1264,79 +1264,79 @@  discard block
 block discarded – undo
1264 1264
         }
1265 1265
          */
1266 1266
 
1267
-        return $result;
1268
-    }
1269
-
1270
-    /**
1271
-     * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
1272
-     * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
1273
-     * statique et publique. Le nombre de parametres est determine automatiquement.
1274
-     *
1275
-     * @param 	string 	$name 			Le nom de la fonction a definir dans Sqlite
1276
-     * @param	int		$arg_count		Arg count
1277
-     * @return	void
1278
-     */
1279
-    private function addCustomFunction($name, $arg_count = -1)
1280
-    {
1281
-        if ($this->db)
1282
-        {
1283
-        	$newname=preg_replace('/_/','',$name);
1284
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1285
-            $reflectClass = new ReflectionClass(__CLASS__);
1286
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1287
-            if ($arg_count < 0) {
1288
-                $arg_count = $reflectFunction->getNumberOfParameters();
1289
-            }
1290
-            if (!$this->db->createFunction($name, $localname, $arg_count))
1291
-            {
1292
-                $this->error = "unable to create custom function '$name'";
1293
-            }
1294
-        }
1295
-    }
1296
-
1297
-    /**
1298
-     * calc_daynr
1299
-     *
1300
-     * @param 	int 	$year		Year
1301
-     * @param 	int 	$month		Month
1302
-     * @param	int     $day 		Day
1303
-     * @return int Formatted date
1304
-     */
1305
-    private static function calc_daynr($year, $month, $day) {
1306
-        $y = $year;
1307
-        if ($y == 0 && $month == 0) return 0;
1308
-        $num = (365* $y + 31 * ($month - 1) + $day);
1309
-        if ($month <= 2) {
1310
-            $y--; }
1311
-        else {
1312
-            $num -= floor(($month * 4 + 23) / 10);
1313
-        }
1314
-        $temp = floor(($y / 100 + 1) * 3 / 4);
1315
-        return $num + floor($y / 4) - $temp;
1316
-    }
1317
-
1318
-    /**
1319
-     * calc_weekday
1320
-     *
1321
-     * @param int	$daynr							???
1322
-     * @param bool	$sunday_first_day_of_week		???
1323
-     * @return int
1324
-     */
1325
-    private static function calc_weekday($daynr, $sunday_first_day_of_week) {
1326
-      $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
1327
-      return $ret;
1328
-    }
1329
-
1330
-    /**
1331
-     * calc_days_in_year
1332
-     *
1333
-     * @param 	string	$year		Year
1334
-     * @return	int					Nb of days in year
1335
-     */
1336
-    private static function calc_days_in_year($year)
1337
-    {
1338
-      return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1339
-    }
1267
+		return $result;
1268
+	}
1269
+
1270
+	/**
1271
+	 * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
1272
+	 * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
1273
+	 * statique et publique. Le nombre de parametres est determine automatiquement.
1274
+	 *
1275
+	 * @param 	string 	$name 			Le nom de la fonction a definir dans Sqlite
1276
+	 * @param	int		$arg_count		Arg count
1277
+	 * @return	void
1278
+	 */
1279
+	private function addCustomFunction($name, $arg_count = -1)
1280
+	{
1281
+		if ($this->db)
1282
+		{
1283
+			$newname=preg_replace('/_/','',$name);
1284
+			$localname = __CLASS__ . '::' . 'db' . $newname;
1285
+			$reflectClass = new ReflectionClass(__CLASS__);
1286
+			$reflectFunction = $reflectClass->getMethod('db' . $newname);
1287
+			if ($arg_count < 0) {
1288
+				$arg_count = $reflectFunction->getNumberOfParameters();
1289
+			}
1290
+			if (!$this->db->createFunction($name, $localname, $arg_count))
1291
+			{
1292
+				$this->error = "unable to create custom function '$name'";
1293
+			}
1294
+		}
1295
+	}
1296
+
1297
+	/**
1298
+	 * calc_daynr
1299
+	 *
1300
+	 * @param 	int 	$year		Year
1301
+	 * @param 	int 	$month		Month
1302
+	 * @param	int     $day 		Day
1303
+	 * @return int Formatted date
1304
+	 */
1305
+	private static function calc_daynr($year, $month, $day) {
1306
+		$y = $year;
1307
+		if ($y == 0 && $month == 0) return 0;
1308
+		$num = (365* $y + 31 * ($month - 1) + $day);
1309
+		if ($month <= 2) {
1310
+			$y--; }
1311
+		else {
1312
+			$num -= floor(($month * 4 + 23) / 10);
1313
+		}
1314
+		$temp = floor(($y / 100 + 1) * 3 / 4);
1315
+		return $num + floor($y / 4) - $temp;
1316
+	}
1317
+
1318
+	/**
1319
+	 * calc_weekday
1320
+	 *
1321
+	 * @param int	$daynr							???
1322
+	 * @param bool	$sunday_first_day_of_week		???
1323
+	 * @return int
1324
+	 */
1325
+	private static function calc_weekday($daynr, $sunday_first_day_of_week) {
1326
+	  $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
1327
+	  return $ret;
1328
+	}
1329
+
1330
+	/**
1331
+	 * calc_days_in_year
1332
+	 *
1333
+	 * @param 	string	$year		Year
1334
+	 * @return	int					Nb of days in year
1335
+	 */
1336
+	private static function calc_days_in_year($year)
1337
+	{
1338
+	  return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1339
+	}
1340 1340
 
1341 1341
 	/**
1342 1342
 	 * calc_week
@@ -1348,44 +1348,44 @@  discard block
 block discarded – undo
1348 1348
 	 * @param 	string	$calc_year			???
1349 1349
 	 * @return	string						???
1350 1350
 	 */
1351
-    private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1352
-        $daynr=self::calc_daynr($year,$month,$day);
1353
-        $first_daynr=self::calc_daynr($year,1,1);
1354
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1355
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1356
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1357
-
1358
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1359
-        $calc_year=$year;
1360
-
1361
-        if ($month == 1 && $day <= 7-$weekday)
1362
-        {
1363
-            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1364
-                return 0;
1365
-            $week_year= 1;
1366
-            $calc_year--;
1367
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1368
-            $weekday= ($weekday + 53*7- $days) % 7;
1369
-      }
1370
-
1371
-      if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1372
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1373
-      }
1374
-      else {
1375
-        $days= $daynr - ($first_daynr - $weekday);
1376
-      }
1377
-
1378
-      if ($week_year && $days >= 52*7)
1379
-      {
1380
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1381
-        if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1382
-        {
1383
-          $calc_year++;
1384
-          return 1;
1385
-        }
1386
-      }
1387
-      return floor($days/7+1);
1388
-    }
1351
+	private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1352
+		$daynr=self::calc_daynr($year,$month,$day);
1353
+		$first_daynr=self::calc_daynr($year,1,1);
1354
+		$monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1355
+		$week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1356
+		$first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1357
+
1358
+		$weekday=self::calc_weekday($first_daynr, !$monday_first);
1359
+		$calc_year=$year;
1360
+
1361
+		if ($month == 1 && $day <= 7-$weekday)
1362
+		{
1363
+			if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1364
+				return 0;
1365
+			$week_year= 1;
1366
+			$calc_year--;
1367
+			$first_daynr-= ($days=self::calc_days_in_year($calc_year));
1368
+			$weekday= ($weekday + 53*7- $days) % 7;
1369
+	  }
1370
+
1371
+	  if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1372
+		$days= $daynr - ($first_daynr+ (7-$weekday));
1373
+	  }
1374
+	  else {
1375
+		$days= $daynr - ($first_daynr - $weekday);
1376
+	  }
1377
+
1378
+	  if ($week_year && $days >= 52*7)
1379
+	  {
1380
+		$weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1381
+		if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1382
+		{
1383
+		  $calc_year++;
1384
+		  return 1;
1385
+		}
1386
+	  }
1387
+	  return floor($days/7+1);
1388
+	}
1389 1389
 
1390 1390
 }
1391 1391
 
Please login to merge, or discard this patch.
Spacing   +253 added lines, -253 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
     }
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
     {
956 956
     	$sql = "DROP TABLE ".$table;
957 957
 
958
-    	if (! $this->query($sql))
958
+    	if (!$this->query($sql))
959 959
     		return -1;
960 960
     	else
961 961
     		return 1;
@@ -968,11 +968,11 @@  discard block
 block discarded – undo
968 968
 	 *	@param	string		$field	Optionnel : Name of field if we want description of field
969 969
 	 *	@return	SQLite3Result		Resource
970 970
      */
971
-    function DDLDescTable($table,$field="")
971
+    function DDLDescTable($table, $field = "")
972 972
     {
973
-        $sql="DESC ".$table." ".$field;
973
+        $sql = "DESC ".$table." ".$field;
974 974
 
975
-        dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
975
+        dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
976 976
         $this->_results = $this->query($sql);
977 977
         return $this->_results;
978 978
     }
@@ -986,34 +986,34 @@  discard block
 block discarded – undo
986 986
 	 *	@param	string	$field_position 	Optionnel ex.: "after champtruc"
987 987
 	 *	@return	int							<0 if KO, >0 if OK
988 988
      */
989
-    function DDLAddField($table,$field_name,$field_desc,$field_position="")
989
+    function DDLAddField($table, $field_name, $field_desc, $field_position = "")
990 990
     {
991 991
         // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
992 992
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
993
-        $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
994
-        $sql.= $field_desc['type'];
995
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
996
-        if (! in_array($field_desc['type'],array('date','datetime')))
993
+        $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
994
+        $sql .= $field_desc['type'];
995
+        if (preg_match("/^[^\s]/i", $field_desc['value']))
996
+        if (!in_array($field_desc['type'], array('date', 'datetime')))
997 997
         {
998
-            $sql.= "(".$field_desc['value'].")";
998
+            $sql .= "(".$field_desc['value'].")";
999 999
         }
1000
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1001
-        $sql.= " ".$field_desc['attribute'];
1002
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1003
-        $sql.= " ".$field_desc['null'];
1004
-        if(preg_match("/^[^\s]/i",$field_desc['default']))
1000
+        if (preg_match("/^[^\s]/i", $field_desc['attribute']))
1001
+        $sql .= " ".$field_desc['attribute'];
1002
+        if (preg_match("/^[^\s]/i", $field_desc['null']))
1003
+        $sql .= " ".$field_desc['null'];
1004
+        if (preg_match("/^[^\s]/i", $field_desc['default']))
1005 1005
         {
1006
-            if(preg_match("/null/i",$field_desc['default']))
1007
-            $sql.= " default ".$field_desc['default'];
1006
+            if (preg_match("/null/i", $field_desc['default']))
1007
+            $sql .= " default ".$field_desc['default'];
1008 1008
             else
1009
-            $sql.= " default '".$field_desc['default']."'";
1009
+            $sql .= " default '".$field_desc['default']."'";
1010 1010
         }
1011
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1012
-        $sql.= " ".$field_desc['extra'];
1013
-        $sql.= " ".$field_position;
1011
+        if (preg_match("/^[^\s]/i", $field_desc['extra']))
1012
+        $sql .= " ".$field_desc['extra'];
1013
+        $sql .= " ".$field_position;
1014 1014
 
1015
-        dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
1016
-        if(! $this->query($sql))
1015
+        dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1016
+        if (!$this->query($sql))
1017 1017
         {
1018 1018
             return -1;
1019 1019
         }
@@ -1028,16 +1028,16 @@  discard block
 block discarded – undo
1028 1028
 	 *	@param	string	$field_desc 		Array with description of field format
1029 1029
 	 *	@return	int							<0 if KO, >0 if OK
1030 1030
      */
1031
-    function DDLUpdateField($table,$field_name,$field_desc)
1031
+    function DDLUpdateField($table, $field_name, $field_desc)
1032 1032
     {
1033 1033
         $sql = "ALTER TABLE ".$table;
1034 1034
         $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
1035 1035
         if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
1036
-            $sql.="(".$field_desc['value'].")";
1036
+            $sql .= "(".$field_desc['value'].")";
1037 1037
         }
1038 1038
 
1039
-        dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1040
-        if (! $this->query($sql))
1039
+        dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1040
+        if (!$this->query($sql))
1041 1041
             return -1;
1042 1042
         return 1;
1043 1043
     }
@@ -1049,13 +1049,13 @@  discard block
 block discarded – undo
1049 1049
 	 *	@param	string	$field_name 	Name of field to drop
1050 1050
 	 *	@return	int						<0 if KO, >0 if OK
1051 1051
      */
1052
-    function DDLDropField($table,$field_name)
1052
+    function DDLDropField($table, $field_name)
1053 1053
     {
1054
-        $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1055
-        dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
1056
-        if (! $this->query($sql))
1054
+        $sql = "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
1055
+        dol_syslog(get_class($this)."::DDLDropField ".$sql, LOG_DEBUG);
1056
+        if (!$this->query($sql))
1057 1057
         {
1058
-            $this->error=$this->lasterror();
1058
+            $this->error = $this->lasterror();
1059 1059
             return -1;
1060 1060
         }
1061 1061
         return 1;
@@ -1071,37 +1071,37 @@  discard block
 block discarded – undo
1071 1071
 	 *	@param	string	$dolibarr_main_db_name		Database name where user must be granted
1072 1072
 	 *	@return	int									<0 if KO, >=0 if OK
1073 1073
      */
1074
-    function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
1074
+    function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1075 1075
     {
1076 1076
         $sql = "INSERT INTO user ";
1077
-        $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1078
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1079
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1077
+        $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1078
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
1079
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1080 1080
 
1081
-        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);	// No sql to avoid password in log
1082
-        $resql=$this->query($sql);
1083
-        if (! $resql)
1081
+        dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1082
+        $resql = $this->query($sql);
1083
+        if (!$resql)
1084 1084
         {
1085 1085
             return -1;
1086 1086
         }
1087 1087
 
1088 1088
         $sql = "INSERT INTO db ";
1089
-        $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1090
-        $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1091
-        $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1089
+        $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
1090
+        $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
1091
+        $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
1092 1092
 
1093 1093
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1094
-        $resql=$this->query($sql);
1095
-        if (! $resql)
1094
+        $resql = $this->query($sql);
1095
+        if (!$resql)
1096 1096
         {
1097 1097
             return -1;
1098 1098
         }
1099 1099
 
1100
-        $sql="FLUSH Privileges";
1100
+        $sql = "FLUSH Privileges";
1101 1101
 
1102 1102
         dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1103
-        $resql=$this->query($sql);
1104
-        if (! $resql)
1103
+        $resql = $this->query($sql);
1104
+        if (!$resql)
1105 1105
         {
1106 1106
             return -1;
1107 1107
         }
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
     function getListOfCharacterSet()
1127 1127
     {
1128 1128
         $liste = array();
1129
-        $i=0;
1129
+        $i = 0;
1130 1130
         $liste[$i]['charset'] = 'UTF-8';
1131 1131
         $liste[$i]['description'] = 'UTF-8';
1132 1132
         return $liste;
@@ -1150,7 +1150,7 @@  discard block
 block discarded – undo
1150 1150
     function getListOfCollation()
1151 1151
     {
1152 1152
         $liste = array();
1153
-        $i=0;
1153
+        $i = 0;
1154 1154
         $liste[$i]['charset'] = 'UTF-8';
1155 1155
         $liste[$i]['description'] = 'UTF-8';
1156 1156
         return $liste;
@@ -1164,14 +1164,14 @@  discard block
 block discarded – undo
1164 1164
     function getPathOfDump()
1165 1165
     {
1166 1166
 	    // FIXME: not for SQLite
1167
-        $fullpathofdump='/pathtomysqldump/mysqldump';
1167
+        $fullpathofdump = '/pathtomysqldump/mysqldump';
1168 1168
 
1169
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1169
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1170 1170
         if ($resql)
1171 1171
         {
1172
-            $liste=$this->fetch_array($resql);
1173
-            $basedir=$liste['Value'];
1174
-            $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1172
+            $liste = $this->fetch_array($resql);
1173
+            $basedir = $liste['Value'];
1174
+            $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
1175 1175
         }
1176 1176
         return $fullpathofdump;
1177 1177
     }
@@ -1184,14 +1184,14 @@  discard block
 block discarded – undo
1184 1184
     function getPathOfRestore()
1185 1185
     {
1186 1186
 	    // FIXME: not for SQLite
1187
-        $fullpathofimport='/pathtomysql/mysql';
1187
+        $fullpathofimport = '/pathtomysql/mysql';
1188 1188
 
1189
-        $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1189
+        $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
1190 1190
         if ($resql)
1191 1191
         {
1192
-            $liste=$this->fetch_array($resql);
1193
-            $basedir=$liste['Value'];
1194
-            $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1192
+            $liste = $this->fetch_array($resql);
1193
+            $basedir = $liste['Value'];
1194
+            $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
1195 1195
         }
1196 1196
         return $fullpathofimport;
1197 1197
     }
@@ -1202,18 +1202,18 @@  discard block
 block discarded – undo
1202 1202
 	 * @param	string	$filter		Filter list on a particular value
1203 1203
 	 * @return	array				Array of key-values (key=>value)
1204 1204
      */
1205
-    function getServerParametersValues($filter='')
1205
+    function getServerParametersValues($filter = '')
1206 1206
     {
1207
-        $result=array();
1207
+        $result = array();
1208 1208
         static $pragmas;
1209
-        if (! isset($pragmas)) {
1209
+        if (!isset($pragmas)) {
1210 1210
             // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
1211 1211
             // indépendante de la base de données.
1212 1212
             // cf. http://www.sqlite.org/pragma.html
1213 1213
             $pragmas = array(
1214 1214
                 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
1215 1215
                 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
1216
-				'compile_options', 'data_version',	/*'database_list',*/
1216
+				'compile_options', 'data_version', /*'database_list',*/
1217 1217
                 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
1218 1218
                 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
1219 1219
                 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
@@ -1228,9 +1228,9 @@  discard block
 block discarded – undo
1228 1228
         }
1229 1229
 
1230 1230
         // TODO prendre en compte le filtre
1231
-        foreach($pragmas as $var) {
1231
+        foreach ($pragmas as $var) {
1232 1232
             $sql = "PRAGMA $var";
1233
-            $resql=$this->query($sql);
1233
+            $resql = $this->query($sql);
1234 1234
             if ($resql)
1235 1235
             {
1236 1236
                 $obj = $this->fetch_row($resql);
@@ -1251,9 +1251,9 @@  discard block
 block discarded – undo
1251 1251
 	 * @param	string	$filter		Filter list on a particular value
1252 1252
 	 * @return  array				Array of key-values (key=>value)
1253 1253
      */
1254
-    function getServerStatusValues($filter='')
1254
+    function getServerStatusValues($filter = '')
1255 1255
     {
1256
-        $result=array();
1256
+        $result = array();
1257 1257
         /*
1258 1258
         $sql='SHOW STATUS';
1259 1259
         if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
@@ -1280,10 +1280,10 @@  discard block
 block discarded – undo
1280 1280
     {
1281 1281
         if ($this->db)
1282 1282
         {
1283
-        	$newname=preg_replace('/_/','',$name);
1284
-            $localname = __CLASS__ . '::' . 'db' . $newname;
1283
+        	$newname = preg_replace('/_/', '', $name);
1284
+            $localname = __CLASS__.'::'.'db'.$newname;
1285 1285
             $reflectClass = new ReflectionClass(__CLASS__);
1286
-            $reflectFunction = $reflectClass->getMethod('db' . $newname);
1286
+            $reflectFunction = $reflectClass->getMethod('db'.$newname);
1287 1287
             if ($arg_count < 0) {
1288 1288
                 $arg_count = $reflectFunction->getNumberOfParameters();
1289 1289
             }
@@ -1305,7 +1305,7 @@  discard block
 block discarded – undo
1305 1305
     private static function calc_daynr($year, $month, $day) {
1306 1306
         $y = $year;
1307 1307
         if ($y == 0 && $month == 0) return 0;
1308
-        $num = (365* $y + 31 * ($month - 1) + $day);
1308
+        $num = (365 * $y + 31 * ($month - 1) + $day);
1309 1309
         if ($month <= 2) {
1310 1310
             $y--; }
1311 1311
         else {
@@ -1335,7 +1335,7 @@  discard block
 block discarded – undo
1335 1335
      */
1336 1336
     private static function calc_days_in_year($year)
1337 1337
     {
1338
-      return (($year & 3) == 0 && ($year%100 || ($year%400 == 0 && $year)) ? 366 : 365);
1338
+      return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
1339 1339
     }
1340 1340
 
1341 1341
 	/**
@@ -1349,42 +1349,42 @@  discard block
 block discarded – undo
1349 1349
 	 * @return	string						???
1350 1350
 	 */
1351 1351
     private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year) {
1352
-        $daynr=self::calc_daynr($year,$month,$day);
1353
-        $first_daynr=self::calc_daynr($year,1,1);
1354
-        $monday_first= ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1355
-        $week_year= ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1356
-        $first_weekday= ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1352
+        $daynr = self::calc_daynr($year, $month, $day);
1353
+        $first_daynr = self::calc_daynr($year, 1, 1);
1354
+        $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
1355
+        $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
1356
+        $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
1357 1357
 
1358
-        $weekday=self::calc_weekday($first_daynr, !$monday_first);
1359
-        $calc_year=$year;
1358
+        $weekday = self::calc_weekday($first_daynr, !$monday_first);
1359
+        $calc_year = $year;
1360 1360
 
1361
-        if ($month == 1 && $day <= 7-$weekday)
1361
+        if ($month == 1 && $day <= 7 - $weekday)
1362 1362
         {
1363 1363
             if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1364 1364
                 return 0;
1365
-            $week_year= 1;
1365
+            $week_year = 1;
1366 1366
             $calc_year--;
1367
-            $first_daynr-= ($days=self::calc_days_in_year($calc_year));
1368
-            $weekday= ($weekday + 53*7- $days) % 7;
1367
+            $first_daynr -= ($days = self::calc_days_in_year($calc_year));
1368
+            $weekday = ($weekday + 53 * 7 - $days) % 7;
1369 1369
       }
1370 1370
 
1371 1371
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1372
-        $days= $daynr - ($first_daynr+ (7-$weekday));
1372
+        $days = $daynr - ($first_daynr + (7 - $weekday));
1373 1373
       }
1374 1374
       else {
1375
-        $days= $daynr - ($first_daynr - $weekday);
1375
+        $days = $daynr - ($first_daynr - $weekday);
1376 1376
       }
1377 1377
 
1378
-      if ($week_year && $days >= 52*7)
1378
+      if ($week_year && $days >= 52 * 7)
1379 1379
       {
1380
-        $weekday= ($weekday + self::calc_days_in_year($calc_year)) % 7;
1380
+        $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
1381 1381
         if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0))
1382 1382
         {
1383 1383
           $calc_year++;
1384 1384
           return 1;
1385 1385
         }
1386 1386
       }
1387
-      return floor($days/7+1);
1387
+      return floor($days / 7 + 1);
1388 1388
     }
1389 1389
 
1390 1390
 }
Please login to merge, or discard this patch.
Braces   +117 added lines, -84 removed lines patch added patch discarded remove patch
@@ -62,8 +62,12 @@  discard block
 block discarded – undo
62 62
         global $conf;
63 63
 
64 64
         // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
65
-        if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
66
-        if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
65
+        if (! empty($conf->db->character_set)) {
66
+        	$this->forcecharset=$conf->db->character_set;
67
+        }
68
+        if (! empty($conf->db->dolibarr_main_db_collation)) {
69
+        	$this->forcecollate=$conf->db->dolibarr_main_db_collation;
70
+        }
67 71
 
68 72
         $this->database_user=$user;
69 73
         $this->database_host=$host;
@@ -111,8 +115,7 @@  discard block
 block discarded – undo
111 115
             $this->addCustomFunction('WEEKDAY');
112 116
             $this->addCustomFunction('date_format');
113 117
             //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
-        }
115
-        else
118
+        } else
116 119
         {
117 120
             // host, login ou password incorrect
118 121
             $this->connected = false;
@@ -149,9 +152,13 @@  discard block
 block discarded – undo
149 152
         {
150 153
             if ($type == 'auto')
151 154
             {
152
-              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
153
-              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
154
-              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
155
+              if (preg_match('/ALTER TABLE/i',$line)) {
156
+              	$type='dml';
157
+              } else if (preg_match('/CREATE TABLE/i',$line)) {
158
+              	$type='dml';
159
+              } else if (preg_match('/DROP TABLE/i',$line)) {
160
+              	$type='dml';
161
+              }
155 162
             }
156 163
 
157 164
             if ($type == 'dml')
@@ -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
 
@@ -955,10 +981,11 @@  discard block
 block discarded – undo
955 981
     {
956 982
     	$sql = "DROP TABLE ".$table;
957 983
 
958
-    	if (! $this->query($sql))
959
-    		return -1;
960
-    	else
961
-    		return 1;
984
+    	if (! $this->query($sql)) {
985
+    	    		return -1;
986
+    	} else {
987
+    	    		return 1;
988
+    	}
962 989
     }
963 990
 
964 991
     /**
@@ -992,24 +1019,29 @@  discard block
 block discarded – undo
992 1019
         // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
993 1020
         $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
994 1021
         $sql.= $field_desc['type'];
995
-        if(preg_match("/^[^\s]/i",$field_desc['value']))
996
-        if (! in_array($field_desc['type'],array('date','datetime')))
1022
+        if(preg_match("/^[^\s]/i",$field_desc['value'])) {
1023
+                if (! in_array($field_desc['type'],array('date','datetime')))
997 1024
         {
998 1025
             $sql.= "(".$field_desc['value'].")";
999 1026
         }
1000
-        if(preg_match("/^[^\s]/i",$field_desc['attribute']))
1001
-        $sql.= " ".$field_desc['attribute'];
1002
-        if(preg_match("/^[^\s]/i",$field_desc['null']))
1003
-        $sql.= " ".$field_desc['null'];
1027
+        }
1028
+        if(preg_match("/^[^\s]/i",$field_desc['attribute'])) {
1029
+                $sql.= " ".$field_desc['attribute'];
1030
+        }
1031
+        if(preg_match("/^[^\s]/i",$field_desc['null'])) {
1032
+                $sql.= " ".$field_desc['null'];
1033
+        }
1004 1034
         if(preg_match("/^[^\s]/i",$field_desc['default']))
1005 1035
         {
1006
-            if(preg_match("/null/i",$field_desc['default']))
1007
-            $sql.= " default ".$field_desc['default'];
1008
-            else
1009
-            $sql.= " default '".$field_desc['default']."'";
1036
+            if(preg_match("/null/i",$field_desc['default'])) {
1037
+                        $sql.= " default ".$field_desc['default'];
1038
+            } else {
1039
+                        $sql.= " default '".$field_desc['default']."'";
1040
+            }
1041
+        }
1042
+        if(preg_match("/^[^\s]/i",$field_desc['extra'])) {
1043
+                $sql.= " ".$field_desc['extra'];
1010 1044
         }
1011
-        if(preg_match("/^[^\s]/i",$field_desc['extra']))
1012
-        $sql.= " ".$field_desc['extra'];
1013 1045
         $sql.= " ".$field_position;
1014 1046
 
1015 1047
         dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
@@ -1037,8 +1069,9 @@  discard block
 block discarded – undo
1037 1069
         }
1038 1070
 
1039 1071
         dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
1040
-        if (! $this->query($sql))
1041
-            return -1;
1072
+        if (! $this->query($sql)) {
1073
+                    return -1;
1074
+        }
1042 1075
         return 1;
1043 1076
     }
1044 1077
 
@@ -1236,8 +1269,7 @@  discard block
 block discarded – undo
1236 1269
                 $obj = $this->fetch_row($resql);
1237 1270
                 //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
1238 1271
                 $result[$var] = $obj[0];
1239
-            }
1240
-            else {
1272
+            } else {
1241 1273
                 // TODO Récupérer le message
1242 1274
                 $result[$var] = 'FAIL';
1243 1275
             }
@@ -1304,11 +1336,12 @@  discard block
 block discarded – undo
1304 1336
      */
1305 1337
     private static function calc_daynr($year, $month, $day) {
1306 1338
         $y = $year;
1307
-        if ($y == 0 && $month == 0) return 0;
1339
+        if ($y == 0 && $month == 0) {
1340
+        	return 0;
1341
+        }
1308 1342
         $num = (365* $y + 31 * ($month - 1) + $day);
1309 1343
         if ($month <= 2) {
1310
-            $y--; }
1311
-        else {
1344
+            $y--; } else {
1312 1345
             $num -= floor(($month * 4 + 23) / 10);
1313 1346
         }
1314 1347
         $temp = floor(($y / 100 + 1) * 3 / 4);
@@ -1360,8 +1393,9 @@  discard block
 block discarded – undo
1360 1393
 
1361 1394
         if ($month == 1 && $day <= 7-$weekday)
1362 1395
         {
1363
-            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)))
1364
-                return 0;
1396
+            if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4))) {
1397
+                            return 0;
1398
+            }
1365 1399
             $week_year= 1;
1366 1400
             $calc_year--;
1367 1401
             $first_daynr-= ($days=self::calc_days_in_year($calc_year));
@@ -1370,8 +1404,7 @@  discard block
 block discarded – undo
1370 1404
 
1371 1405
       if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
1372 1406
         $days= $daynr - ($first_daynr+ (7-$weekday));
1373
-      }
1374
-      else {
1407
+      } else {
1375 1408
         $days= $daynr - ($first_daynr - $weekday);
1376 1409
       }
1377 1410
 
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.