Test Failed
Branch develop (86e751)
by Laurent
34:11
created
htdocs/product/dynamic_price/class/price_expression.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -297,7 +297,7 @@
 block discarded – undo
297 297
     /**
298 298
      *  Update object into database
299 299
      *
300
-     *  @param	User	$user        User that modifies
300
+     *  @param	integer	$user        User that modifies
301 301
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302 302
      *  @return int     		   	 <0 if KO, >0 if OK
303 303
      */
Please login to merge, or discard this patch.
Indentation   +196 added lines, -196 removed lines patch added patch discarded remove patch
@@ -32,39 +32,39 @@  discard block
 block discarded – undo
32 32
 	var $db;							//!< To store db handler
33 33
 	var $error;							//!< To return error code (or message)
34 34
 	var $errors=array();				//!< To return several error codes (or messages)
35
-    var $id;
36
-    var $title;
35
+	var $id;
36
+	var $title;
37 37
 	var $expression;
38
-    public $table_element = "c_price_expression";
39
-
40
-    /**
41
-     *  Constructor
42
-     *
43
-     *  @param	DoliDb		$db      Database handler
44
-     */
45
-    function __construct($db)
46
-    {
47
-        $this->db = $db;
48
-        return 1;
49
-    }
50
-
51
-
52
-    /**
53
-     *  Create object into database
54
-     *
55
-     *  @param	User	$user        User that creates
56
-     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
57
-     *  @return int      		   	 <0 if KO, Id of created object if OK
58
-     */
59
-    function create($user, $notrigger=0)
60
-    {
61
-        $error=0;
38
+	public $table_element = "c_price_expression";
39
+
40
+	/**
41
+	 *  Constructor
42
+	 *
43
+	 *  @param	DoliDb		$db      Database handler
44
+	 */
45
+	function __construct($db)
46
+	{
47
+		$this->db = $db;
48
+		return 1;
49
+	}
50
+
51
+
52
+	/**
53
+	 *  Create object into database
54
+	 *
55
+	 *  @param	User	$user        User that creates
56
+	 *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
57
+	 *  @return int      		   	 <0 if KO, Id of created object if OK
58
+	 */
59
+	function create($user, $notrigger=0)
60
+	{
61
+		$error=0;
62 62
 
63 63
 		// Clean parameters
64 64
 		if (isset($this->title)) $this->title=trim($this->title);
65 65
 		if (isset($this->expression)) $this->expression=trim($this->expression);
66 66
 
67
-        // Insert request
67
+		// Insert request
68 68
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
69 69
 		$sql.= "title, expression";
70 70
 		$sql.= ") VALUES (";
@@ -75,32 +75,32 @@  discard block
 block discarded – undo
75 75
 		$this->db->begin();
76 76
 
77 77
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
78
-        $resql=$this->db->query($sql);
79
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
78
+		$resql=$this->db->query($sql);
79
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
80 80
 
81 81
 		if (! $error)
82
-        {
83
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
82
+		{
83
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
84 84
 
85 85
 			if (! $notrigger)
86 86
 			{
87
-	            // Uncomment this and change MYOBJECT to your own tag if you
88
-	            // want this action calls a trigger.
87
+				// Uncomment this and change MYOBJECT to your own tag if you
88
+				// want this action calls a trigger.
89 89
 
90
-	            //// Call triggers
91
-	            //$result=$this->call_trigger('MYOBJECT_CREATE',$user);
92
-	            //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
93
-	            //// End call triggers
90
+				//// Call triggers
91
+				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
92
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
93
+				//// End call triggers
94 94
 			}
95
-        }
95
+		}
96 96
 
97
-        // Commit or rollback
98
-        if ($error)
97
+		// Commit or rollback
98
+		if ($error)
99 99
 		{
100 100
 			foreach($this->errors as $errmsg)
101 101
 			{
102
-	            dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
102
+				dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
104 104
 			}
105 105
 			$this->db->rollback();
106 106
 			return -1*$error;
@@ -108,166 +108,166 @@  discard block
 block discarded – undo
108 108
 		else
109 109
 		{
110 110
 			$this->db->commit();
111
-            return $this->id;
111
+			return $this->id;
112 112
 		}
113
-    }
114
-
115
-
116
-    /**
117
-     *  Load object in memory from the database
118
-     *
119
-     *  @param		int		$id    	Id object
120
-     *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
121
-     */
122
-    function fetch($id)
123
-    {
124
-        $sql = "SELECT title, expression";
125
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
-        $sql.= " WHERE rowid = ".$id;
127
-
128
-    	dol_syslog(get_class($this)."::fetch");
129
-        $resql=$this->db->query($sql);
130
-        if ($resql)
131
-        {
132
-            $obj = $this->db->fetch_object($resql);
133
-            if ($obj)
134
-            {
135
-                $this->id			= $id;
136
-                $this->title		= $obj->title;
137
-                $this->expression	= $obj->expression;
138
-                return 1;
139
-            }
140
-            else
141
-            {
142
-                return 0;
143
-            }
144
-        }
145
-        else
146
-        {
147
-      	    $this->error="Error ".$this->db->lasterror();
148
-            return -1;
149
-        }
150
-    }
151
-
152
-    /**
153
-     *    List all price expressions
154
-     *
155
-     *    @return	array				Array of price expressions
156
-     */
157
-    function list_price_expression()
158
-    {
159
-        $sql = "SELECT rowid, title, expression";
160
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
161
-        $sql.= " ORDER BY title";
162
-
163
-        dol_syslog(get_class($this)."::list_price_expression");
164
-        $resql=$this->db->query($sql);
165
-        if ($resql)
166
-        {
167
-            $retarray = array();
168
-
169
-            while ($record = $this->db->fetch_array($resql))
170
-            {
171
-                $price_expression_obj = new PriceExpression($this->db);
172
-                $price_expression_obj->id			= $record["rowid"];
173
-                $price_expression_obj->title		= $record["title"];
113
+	}
114
+
115
+
116
+	/**
117
+	 *  Load object in memory from the database
118
+	 *
119
+	 *  @param		int		$id    	Id object
120
+	 *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
121
+	 */
122
+	function fetch($id)
123
+	{
124
+		$sql = "SELECT title, expression";
125
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
+		$sql.= " WHERE rowid = ".$id;
127
+
128
+		dol_syslog(get_class($this)."::fetch");
129
+		$resql=$this->db->query($sql);
130
+		if ($resql)
131
+		{
132
+			$obj = $this->db->fetch_object($resql);
133
+			if ($obj)
134
+			{
135
+				$this->id			= $id;
136
+				$this->title		= $obj->title;
137
+				$this->expression	= $obj->expression;
138
+				return 1;
139
+			}
140
+			else
141
+			{
142
+				return 0;
143
+			}
144
+		}
145
+		else
146
+		{
147
+	  		$this->error="Error ".$this->db->lasterror();
148
+			return -1;
149
+		}
150
+	}
151
+
152
+	/**
153
+	 *    List all price expressions
154
+	 *
155
+	 *    @return	array				Array of price expressions
156
+	 */
157
+	function list_price_expression()
158
+	{
159
+		$sql = "SELECT rowid, title, expression";
160
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
161
+		$sql.= " ORDER BY title";
162
+
163
+		dol_syslog(get_class($this)."::list_price_expression");
164
+		$resql=$this->db->query($sql);
165
+		if ($resql)
166
+		{
167
+			$retarray = array();
168
+
169
+			while ($record = $this->db->fetch_array($resql))
170
+			{
171
+				$price_expression_obj = new PriceExpression($this->db);
172
+				$price_expression_obj->id			= $record["rowid"];
173
+				$price_expression_obj->title		= $record["title"];
174 174
 				$price_expression_obj->expression	= $record["expression"];
175
-                $retarray[]=$price_expression_obj;
176
-            }
177
-
178
-            $this->db->free($resql);
179
-            return $retarray;
180
-        }
181
-        else
182
-        {
183
-            $this->error=$this->db->error();
184
-            return -1;
185
-        }
186
-    }
187
-
188
-
189
-    /**
190
-     *  Returns any existing rowid with specified title
191
-     *
192
-     *  @param		String	$title  Title of expression
193
-     *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 rowid
194
-     */
195
-    function find_title($title)
196
-    {
197
-        $sql = "SELECT rowid";
198
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
199
-        $sql.= " WHERE title = '".$this->db->escape($title)."'";
200
-
201
-    	dol_syslog(get_class($this)."::find_title");
202
-        $resql=$this->db->query($sql);
203
-        if ($resql)
204
-        {
205
-            $obj = $this->db->fetch_object($resql);
206
-            if ($obj)
207
-            {
208
-            	return (int) $obj->rowid;
209
-            }
210
-            else
211
-            {
212
-                return 0;
213
-            }
214
-        }
215
-        else
216
-        {
217
-      	    $this->error="Error ".$this->db->lasterror();
218
-            return -1;
219
-        }
220
-    }
221
-
222
-
223
-    /**
224
-     *  Update object into database
225
-     *
226
-     *  @param	User	$user        User that modifies
227
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
228
-     *  @return int     		   	 <0 if KO, >0 if OK
229
-     */
230
-    function update($user=0, $notrigger=0)
231
-    {
175
+				$retarray[]=$price_expression_obj;
176
+			}
177
+
178
+			$this->db->free($resql);
179
+			return $retarray;
180
+		}
181
+		else
182
+		{
183
+			$this->error=$this->db->error();
184
+			return -1;
185
+		}
186
+	}
187
+
188
+
189
+	/**
190
+	 *  Returns any existing rowid with specified title
191
+	 *
192
+	 *  @param		String	$title  Title of expression
193
+	 *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 rowid
194
+	 */
195
+	function find_title($title)
196
+	{
197
+		$sql = "SELECT rowid";
198
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
199
+		$sql.= " WHERE title = '".$this->db->escape($title)."'";
200
+
201
+		dol_syslog(get_class($this)."::find_title");
202
+		$resql=$this->db->query($sql);
203
+		if ($resql)
204
+		{
205
+			$obj = $this->db->fetch_object($resql);
206
+			if ($obj)
207
+			{
208
+				return (int) $obj->rowid;
209
+			}
210
+			else
211
+			{
212
+				return 0;
213
+			}
214
+		}
215
+		else
216
+		{
217
+	  		$this->error="Error ".$this->db->lasterror();
218
+			return -1;
219
+		}
220
+	}
221
+
222
+
223
+	/**
224
+	 *  Update object into database
225
+	 *
226
+	 *  @param	User	$user        User that modifies
227
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
228
+	 *  @return int     		   	 <0 if KO, >0 if OK
229
+	 */
230
+	function update($user=0, $notrigger=0)
231
+	{
232 232
 		$error=0;
233 233
 
234 234
 		// Clean parameters
235 235
 		if (isset($this->title)) $this->title=trim($this->title);
236 236
 		if (isset($this->expression)) $this->expression=trim($this->expression);
237 237
 
238
-        // Update request
239
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
238
+		// Update request
239
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
240 240
 		$sql.= " title = ".(isset($this->title)?"'".$this->db->escape($this->title)."'":"''").",";
241 241
 		$sql.= " expression = ".(isset($this->expression)?"'".$this->db->escape($this->expression)."'":"''")."";
242
-        $sql.= " WHERE rowid = ".$this->id;
242
+		$sql.= " WHERE rowid = ".$this->id;
243 243
 
244 244
 		$this->db->begin();
245 245
 
246
-    	dol_syslog(get_class($this)."::update");
247
-        $resql = $this->db->query($sql);
248
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
246
+		dol_syslog(get_class($this)."::update");
247
+		$resql = $this->db->query($sql);
248
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
249 249
 
250 250
 		if (! $error)
251 251
 		{
252 252
 			if (! $notrigger)
253 253
 			{
254
-	            // Uncomment this and change MYOBJECT to your own tag if you
255
-	            // want this action calls a trigger.
254
+				// Uncomment this and change MYOBJECT to your own tag if you
255
+				// want this action calls a trigger.
256 256
 
257
-	            //// Call triggers
258
-	            //$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
259
-	            //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
260
-	            //// End call triggers
257
+				//// Call triggers
258
+				//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
259
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
260
+				//// End call triggers
261 261
 			 }
262 262
 		}
263 263
 
264
-        // Commit or rollback
264
+		// Commit or rollback
265 265
 		if ($error)
266 266
 		{
267 267
 			foreach($this->errors as $errmsg)
268 268
 			{
269
-	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
270
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
269
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
270
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
271 271
 			}
272 272
 			$this->db->rollback();
273 273
 			return -1*$error;
@@ -277,16 +277,16 @@  discard block
 block discarded – undo
277 277
 			$this->db->commit();
278 278
 			return 1;
279 279
 		}
280
-    }
280
+	}
281 281
 
282 282
 
283 283
  	/**
284
-	 *  Delete object in database
285
-	 *
286
-     *	@param  User	$user        User that deletes
287
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
288
-	 *  @return	int					 <0 if KO, >0 if OK
289
-	 */
284
+ 	 *  Delete object in database
285
+ 	 *
286
+ 	 *	@param  User	$user        User that deletes
287
+ 	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
288
+ 	 *  @return	int					 <0 if KO, >0 if OK
289
+ 	 */
290 290
 	function delete(User $user, $notrigger=0)
291 291
 	{
292 292
 		$error=0;
@@ -300,32 +300,32 @@  discard block
 block discarded – undo
300 300
 			if (! $notrigger)
301 301
 			{
302 302
 				// Uncomment this and change MYOBJECT to your own tag if you
303
-		        // want this action calls a trigger.
303
+				// want this action calls a trigger.
304 304
 
305
-	            //// Call triggers
306
-	            //$result=$this->call_trigger('MYOBJECT_DELETE',$user);
307
-	            //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
308
-	            //// End call triggers
305
+				//// Call triggers
306
+				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
307
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
308
+				//// End call triggers
309 309
 			}
310 310
 		}
311 311
 
312 312
 		if (! $error)
313 313
 		{
314
-    		$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
315
-    		$sql.= " WHERE rowid = ".$rowid;
314
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
315
+			$sql.= " WHERE rowid = ".$rowid;
316 316
 
317
-	        dol_syslog(get_class($this)."::delete");
318
-    		$resql = $this->db->query($sql);
319
-        	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
317
+			dol_syslog(get_class($this)."::delete");
318
+			$resql = $this->db->query($sql);
319
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
320 320
 		}
321 321
 
322
-        // Commit or rollback
322
+		// Commit or rollback
323 323
 		if ($error)
324 324
 		{
325 325
 			foreach($this->errors as $errmsg)
326 326
 			{
327
-	        	dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
328
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
327
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
328
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
329 329
 			}
330 330
 			$this->db->rollback();
331 331
 			return -1*$error;
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -29,9 +29,9 @@  discard block
 block discarded – undo
29 29
  */
30 30
 class PriceExpression
31 31
 {
32
-	var $db;							//!< To store db handler
33
-	var $error;							//!< To return error code (or message)
34
-	var $errors=array();				//!< To return several error codes (or messages)
32
+	var $db; //!< To store db handler
33
+	var $error; //!< To return error code (or message)
34
+	var $errors = array(); //!< To return several error codes (or messages)
35 35
     var $id;
36 36
     var $title;
37 37
 	var $expression;
@@ -56,33 +56,33 @@  discard block
 block discarded – undo
56 56
      *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
57 57
      *  @return int      		   	 <0 if KO, Id of created object if OK
58 58
      */
59
-    function create($user, $notrigger=0)
59
+    function create($user, $notrigger = 0)
60 60
     {
61
-        $error=0;
61
+        $error = 0;
62 62
 
63 63
 		// Clean parameters
64
-		if (isset($this->title)) $this->title=trim($this->title);
65
-		if (isset($this->expression)) $this->expression=trim($this->expression);
64
+		if (isset($this->title)) $this->title = trim($this->title);
65
+		if (isset($this->expression)) $this->expression = trim($this->expression);
66 66
 
67 67
         // Insert request
68 68
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
69
-		$sql.= "title, expression";
70
-		$sql.= ") VALUES (";
71
-		$sql.= " ".(isset($this->title)?"'".$this->db->escape($this->title)."'":"''").",";
72
-		$sql.= " ".(isset($this->expression)?"'".$this->db->escape($this->expression)."'":"''");
73
-		$sql.= ")";
69
+		$sql .= "title, expression";
70
+		$sql .= ") VALUES (";
71
+		$sql .= " ".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "''").",";
72
+		$sql .= " ".(isset($this->expression) ? "'".$this->db->escape($this->expression)."'" : "''");
73
+		$sql .= ")";
74 74
 
75 75
 		$this->db->begin();
76 76
 
77 77
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
78
-        $resql=$this->db->query($sql);
79
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
78
+        $resql = $this->db->query($sql);
79
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
80 80
 
81
-		if (! $error)
81
+		if (!$error)
82 82
         {
83 83
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
84 84
 
85
-			if (! $notrigger)
85
+			if (!$notrigger)
86 86
 			{
87 87
 	            // Uncomment this and change MYOBJECT to your own tag if you
88 88
 	            // want this action calls a trigger.
@@ -97,13 +97,13 @@  discard block
 block discarded – undo
97 97
         // Commit or rollback
98 98
         if ($error)
99 99
 		{
100
-			foreach($this->errors as $errmsg)
100
+			foreach ($this->errors as $errmsg)
101 101
 			{
102 102
 	            dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
103
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
104 104
 			}
105 105
 			$this->db->rollback();
106
-			return -1*$error;
106
+			return -1 * $error;
107 107
 		}
108 108
 		else
109 109
 		{
@@ -122,19 +122,19 @@  discard block
 block discarded – undo
122 122
     function fetch($id)
123 123
     {
124 124
         $sql = "SELECT title, expression";
125
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
-        $sql.= " WHERE rowid = ".$id;
125
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
+        $sql .= " WHERE rowid = ".$id;
127 127
 
128 128
     	dol_syslog(get_class($this)."::fetch");
129
-        $resql=$this->db->query($sql);
129
+        $resql = $this->db->query($sql);
130 130
         if ($resql)
131 131
         {
132 132
             $obj = $this->db->fetch_object($resql);
133 133
             if ($obj)
134 134
             {
135
-                $this->id			= $id;
136
-                $this->title		= $obj->title;
137
-                $this->expression	= $obj->expression;
135
+                $this->id = $id;
136
+                $this->title = $obj->title;
137
+                $this->expression = $obj->expression;
138 138
                 return 1;
139 139
             }
140 140
             else
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
         }
145 145
         else
146 146
         {
147
-      	    $this->error="Error ".$this->db->lasterror();
147
+      	    $this->error = "Error ".$this->db->lasterror();
148 148
             return -1;
149 149
         }
150 150
     }
@@ -157,11 +157,11 @@  discard block
 block discarded – undo
157 157
     function list_price_expression()
158 158
     {
159 159
         $sql = "SELECT rowid, title, expression";
160
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
161
-        $sql.= " ORDER BY title";
160
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
161
+        $sql .= " ORDER BY title";
162 162
 
163 163
         dol_syslog(get_class($this)."::list_price_expression");
164
-        $resql=$this->db->query($sql);
164
+        $resql = $this->db->query($sql);
165 165
         if ($resql)
166 166
         {
167 167
             $retarray = array();
@@ -169,10 +169,10 @@  discard block
 block discarded – undo
169 169
             while ($record = $this->db->fetch_array($resql))
170 170
             {
171 171
                 $price_expression_obj = new PriceExpression($this->db);
172
-                $price_expression_obj->id			= $record["rowid"];
173
-                $price_expression_obj->title		= $record["title"];
172
+                $price_expression_obj->id = $record["rowid"];
173
+                $price_expression_obj->title = $record["title"];
174 174
 				$price_expression_obj->expression	= $record["expression"];
175
-                $retarray[]=$price_expression_obj;
175
+                $retarray[] = $price_expression_obj;
176 176
             }
177 177
 
178 178
             $this->db->free($resql);
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
         }
181 181
         else
182 182
         {
183
-            $this->error=$this->db->error();
183
+            $this->error = $this->db->error();
184 184
             return -1;
185 185
         }
186 186
     }
@@ -195,11 +195,11 @@  discard block
 block discarded – undo
195 195
     function find_title($title)
196 196
     {
197 197
         $sql = "SELECT rowid";
198
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
199
-        $sql.= " WHERE title = '".$this->db->escape($title)."'";
198
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
199
+        $sql .= " WHERE title = '".$this->db->escape($title)."'";
200 200
 
201 201
     	dol_syslog(get_class($this)."::find_title");
202
-        $resql=$this->db->query($sql);
202
+        $resql = $this->db->query($sql);
203 203
         if ($resql)
204 204
         {
205 205
             $obj = $this->db->fetch_object($resql);
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
         }
215 215
         else
216 216
         {
217
-      	    $this->error="Error ".$this->db->lasterror();
217
+      	    $this->error = "Error ".$this->db->lasterror();
218 218
             return -1;
219 219
         }
220 220
     }
@@ -227,29 +227,29 @@  discard block
 block discarded – undo
227 227
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
228 228
      *  @return int     		   	 <0 if KO, >0 if OK
229 229
      */
230
-    function update($user=0, $notrigger=0)
230
+    function update($user = 0, $notrigger = 0)
231 231
     {
232
-		$error=0;
232
+		$error = 0;
233 233
 
234 234
 		// Clean parameters
235
-		if (isset($this->title)) $this->title=trim($this->title);
236
-		if (isset($this->expression)) $this->expression=trim($this->expression);
235
+		if (isset($this->title)) $this->title = trim($this->title);
236
+		if (isset($this->expression)) $this->expression = trim($this->expression);
237 237
 
238 238
         // Update request
239 239
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
240
-		$sql.= " title = ".(isset($this->title)?"'".$this->db->escape($this->title)."'":"''").",";
241
-		$sql.= " expression = ".(isset($this->expression)?"'".$this->db->escape($this->expression)."'":"''")."";
242
-        $sql.= " WHERE rowid = ".$this->id;
240
+		$sql .= " title = ".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "''").",";
241
+		$sql .= " expression = ".(isset($this->expression) ? "'".$this->db->escape($this->expression)."'" : "''")."";
242
+        $sql .= " WHERE rowid = ".$this->id;
243 243
 
244 244
 		$this->db->begin();
245 245
 
246 246
     	dol_syslog(get_class($this)."::update");
247 247
         $resql = $this->db->query($sql);
248
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
248
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
249 249
 
250
-		if (! $error)
250
+		if (!$error)
251 251
 		{
252
-			if (! $notrigger)
252
+			if (!$notrigger)
253 253
 			{
254 254
 	            // Uncomment this and change MYOBJECT to your own tag if you
255 255
 	            // want this action calls a trigger.
@@ -264,13 +264,13 @@  discard block
 block discarded – undo
264 264
         // Commit or rollback
265 265
 		if ($error)
266 266
 		{
267
-			foreach($this->errors as $errmsg)
267
+			foreach ($this->errors as $errmsg)
268 268
 			{
269 269
 	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
270
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
270
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
271 271
 			}
272 272
 			$this->db->rollback();
273
-			return -1*$error;
273
+			return -1 * $error;
274 274
 		}
275 275
 		else
276 276
 		{
@@ -287,17 +287,17 @@  discard block
 block discarded – undo
287 287
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
288 288
 	 *  @return	int					 <0 if KO, >0 if OK
289 289
 	 */
290
-	function delete(User $user, $notrigger=0)
290
+	function delete(User $user, $notrigger = 0)
291 291
 	{
292
-		$error=0;
292
+		$error = 0;
293 293
 
294 294
 		$rowid = $this->id;
295 295
 		
296 296
 		$this->db->begin();
297 297
 
298
-		if (! $error)
298
+		if (!$error)
299 299
 		{
300
-			if (! $notrigger)
300
+			if (!$notrigger)
301 301
 			{
302 302
 				// Uncomment this and change MYOBJECT to your own tag if you
303 303
 		        // want this action calls a trigger.
@@ -309,26 +309,26 @@  discard block
 block discarded – undo
309 309
 			}
310 310
 		}
311 311
 
312
-		if (! $error)
312
+		if (!$error)
313 313
 		{
314 314
     		$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
315
-    		$sql.= " WHERE rowid = ".$rowid;
315
+    		$sql .= " WHERE rowid = ".$rowid;
316 316
 
317 317
 	        dol_syslog(get_class($this)."::delete");
318 318
     		$resql = $this->db->query($sql);
319
-        	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
319
+        	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
320 320
 		}
321 321
 
322 322
         // Commit or rollback
323 323
 		if ($error)
324 324
 		{
325
-			foreach($this->errors as $errmsg)
325
+			foreach ($this->errors as $errmsg)
326 326
 			{
327 327
 	        	dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
328
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
328
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
329 329
 			}
330 330
 			$this->db->rollback();
331
-			return -1*$error;
331
+			return -1 * $error;
332 332
 		}
333 333
 		else
334 334
 		{
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 	 */
346 346
 	function initAsSpecimen()
347 347
 	{
348
-		$this->id=0;
349
-		$this->expression='';
348
+		$this->id = 0;
349
+		$this->expression = '';
350 350
 	}
351 351
 }
Please login to merge, or discard this patch.
Braces   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -61,8 +61,12 @@  discard block
 block discarded – undo
61 61
         $error=0;
62 62
 
63 63
 		// Clean parameters
64
-		if (isset($this->title)) $this->title=trim($this->title);
65
-		if (isset($this->expression)) $this->expression=trim($this->expression);
64
+		if (isset($this->title)) {
65
+			$this->title=trim($this->title);
66
+		}
67
+		if (isset($this->expression)) {
68
+			$this->expression=trim($this->expression);
69
+		}
66 70
 
67 71
         // Insert request
68 72
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
@@ -104,8 +108,7 @@  discard block
 block discarded – undo
104 108
 			}
105 109
 			$this->db->rollback();
106 110
 			return -1*$error;
107
-		}
108
-		else
111
+		} else
109 112
 		{
110 113
 			$this->db->commit();
111 114
             return $this->id;
@@ -136,13 +139,11 @@  discard block
 block discarded – undo
136 139
                 $this->title		= $obj->title;
137 140
                 $this->expression	= $obj->expression;
138 141
                 return 1;
139
-            }
140
-            else
142
+            } else
141 143
             {
142 144
                 return 0;
143 145
             }
144
-        }
145
-        else
146
+        } else
146 147
         {
147 148
       	    $this->error="Error ".$this->db->lasterror();
148 149
             return -1;
@@ -177,8 +178,7 @@  discard block
 block discarded – undo
177 178
 
178 179
             $this->db->free($resql);
179 180
             return $retarray;
180
-        }
181
-        else
181
+        } else
182 182
         {
183 183
             $this->error=$this->db->error();
184 184
             return -1;
@@ -206,13 +206,11 @@  discard block
 block discarded – undo
206 206
             if ($obj)
207 207
             {
208 208
             	return (int) $obj->rowid;
209
-            }
210
-            else
209
+            } else
211 210
             {
212 211
                 return 0;
213 212
             }
214
-        }
215
-        else
213
+        } else
216 214
         {
217 215
       	    $this->error="Error ".$this->db->lasterror();
218 216
             return -1;
@@ -232,8 +230,12 @@  discard block
 block discarded – undo
232 230
 		$error=0;
233 231
 
234 232
 		// Clean parameters
235
-		if (isset($this->title)) $this->title=trim($this->title);
236
-		if (isset($this->expression)) $this->expression=trim($this->expression);
233
+		if (isset($this->title)) {
234
+			$this->title=trim($this->title);
235
+		}
236
+		if (isset($this->expression)) {
237
+			$this->expression=trim($this->expression);
238
+		}
237 239
 
238 240
         // Update request
239 241
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
@@ -271,8 +273,7 @@  discard block
 block discarded – undo
271 273
 			}
272 274
 			$this->db->rollback();
273 275
 			return -1*$error;
274
-		}
275
-		else
276
+		} else
276 277
 		{
277 278
 			$this->db->commit();
278 279
 			return 1;
@@ -329,8 +330,7 @@  discard block
 block discarded – undo
329 330
 			}
330 331
 			$this->db->rollback();
331 332
 			return -1*$error;
332
-		}
333
-		else
333
+		} else
334 334
 		{
335 335
 			$this->db->commit();
336 336
 			return 1;
Please login to merge, or discard this patch.
htdocs/product/dynamic_price/class/price_global_variable.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -297,7 +297,7 @@
 block discarded – undo
297 297
     /**
298 298
      *  Update object into database
299 299
      *
300
-     *  @param	User	$user        User that modifies
300
+     *  @param	integer	$user        User that modifies
301 301
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302 302
      *  @return int     		   	 <0 if KO, >0 if OK
303 303
      */
Please login to merge, or discard this patch.
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -29,307 +29,307 @@
 block discarded – undo
29 29
  */
30 30
 class PriceGlobalVariable
31 31
 {
32
-    var $db;							//!< To store db handler
33
-    var $error;							//!< To return error code (or message)
34
-    var $errors=array();				//!< To return several error codes (or messages)
35
-    var $id;
36
-    var $code;
37
-    var $description;
38
-    var $value;
39
-    public $table_element = "c_price_global_variable";
40
-
41
-    /**
42
-     *  Constructor
43
-     *
44
-     *  @param	DoliDb		$db      Database handler
45
-     */
46
-    function __construct($db)
47
-    {
48
-        $this->db = $db;
49
-        return 1;
50
-    }
51
-
52
-
53
-    /**
54
-     *  Create object into database
55
-     *
56
-     *  @param	User	$user        User that creates
57
-     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
58
-     *  @return int      		   	 <0 if KO, Id of created object if OK
59
-     */
60
-    function create($user, $notrigger=0)
61
-    {
62
-        $error=0;
63
-
64
-        $this->checkParameters();
65
-
66
-        // Insert request
67
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
68
-        $sql.= "code, description, value";
69
-        $sql.= ") VALUES (";
70
-        $sql.= " ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
71
-        $sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
72
-        $sql.= " ".$this->value;
73
-        $sql.= ")";
74
-
75
-        $this->db->begin();
76
-
77
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
78
-        $resql=$this->db->query($sql);
79
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
80
-
81
-        if (! $error)
82
-        {
83
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
84
-
85
-            if (! $notrigger)
86
-            {
87
-                // Uncomment this and change MYOBJECT to your own tag if you
88
-                // want this action calls a trigger.
89
-
90
-                //// Call triggers
91
-                //$result=$this->call_trigger('MYOBJECT_CREATE',$user);
92
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
93
-                //// End call triggers
94
-            }
95
-        }
96
-
97
-        // Commit or rollback
98
-        if ($error)
99
-        {
100
-            foreach($this->errors as $errmsg)
101
-            {
102
-                dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
104
-            }
105
-            $this->db->rollback();
106
-            return -1*$error;
107
-        }
108
-        else
109
-        {
110
-            $this->db->commit();
111
-            return $this->id;
112
-        }
113
-    }
114
-
115
-
116
-    /**
117
-     *  Load object in memory from the database
118
-     *
119
-     *  @param		int		$id    	Id object
120
-     *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
121
-     */
122
-    function fetch($id)
123
-    {
124
-        $sql = "SELECT code, description, value";
125
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
-        $sql.= " WHERE rowid = ".$id;
127
-
128
-        dol_syslog(get_class($this)."::fetch");
129
-        $resql=$this->db->query($sql);
130
-        if ($resql)
131
-        {
132
-            $obj = $this->db->fetch_object($resql);
133
-            if ($obj)
134
-            {
135
-                $this->id			= $id;
136
-                $this->code			= $obj->code;
137
-                $this->description	= $obj->description;
138
-                $this->value		= $obj->value;
139
-                $this->checkParameters();
140
-                return 1;
141
-            }
142
-            else
143
-            {
144
-                return 0;
145
-            }
146
-        }
147
-        else
148
-        {
149
-            $this->error="Error ".$this->db->lasterror();
150
-            return -1;
151
-        }
152
-    }
153
-
154
-    /**
155
-     *  Update object into database
156
-     *
157
-     *  @param	User	$user        User that modifies
158
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
159
-     *  @return int     		   	 <0 if KO, >0 if OK
160
-     */
161
-    function update($user=0, $notrigger=0)
162
-    {
163
-        $error=0;
164
-
165
-        $this->checkParameters();
166
-
167
-        // Update request
168
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
169
-        $sql.= " code = ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
170
-        $sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
171
-        $sql.= " value = ".$this->value;
172
-        $sql.= " WHERE rowid = ".$this->id;
173
-
174
-        $this->db->begin();
175
-
176
-        dol_syslog(get_class($this)."::update");
177
-        $resql = $this->db->query($sql);
178
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
179
-
180
-        if (! $error)
181
-        {
182
-            if (! $notrigger)
183
-            {
184
-                // Uncomment this and change MYOBJECT to your own tag if you
185
-                // want this action calls a trigger.
186
-
187
-                //// Call triggers
188
-                //$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
189
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
190
-                //// End call triggers
191
-             }
192
-        }
193
-
194
-        // Commit or rollback
195
-        if ($error)
196
-        {
197
-            foreach($this->errors as $errmsg)
198
-            {
199
-                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
200
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
201
-            }
202
-            $this->db->rollback();
203
-            return -1*$error;
204
-        }
205
-        else
206
-        {
207
-            $this->db->commit();
208
-            return 1;
209
-        }
210
-    }
211
-
212
-
213
-    /**
214
-     *  Delete object in database
215
-     *
216
-     * 	@param	int		$rowid		 Row id of global variable
217
-     *	@param  User	$user        User that deletes
218
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
219
-     *  @return	int					 <0 if KO, >0 if OK
220
-     */
221
-    function delete($rowid, $user, $notrigger=0)
222
-    {
223
-        $error=0;
224
-
225
-        $this->db->begin();
226
-
227
-        if (! $error)
228
-        {
229
-            if (! $notrigger)
230
-            {
231
-                // Uncomment this and change MYOBJECT to your own tag if you
232
-                // want this action calls a trigger.
233
-
234
-                //// Call triggers
235
-                //$result=$this->call_trigger('MYOBJECT_DELETE',$user);
236
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
237
-                //// End call triggers
238
-            }
239
-        }
240
-
241
-        if (! $error)
242
-        {
243
-            $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
244
-            $sql.= " WHERE rowid = ".$rowid;
245
-
246
-            dol_syslog(get_class($this)."::delete");
247
-            $resql = $this->db->query($sql);
248
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
249
-        }
250
-
251
-        // Commit or rollback
252
-        if ($error)
253
-        {
254
-            foreach($this->errors as $errmsg)
255
-            {
256
-                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
257
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
258
-            }
259
-            $this->db->rollback();
260
-            return -1*$error;
261
-        }
262
-        else
263
-        {
264
-            $this->db->commit();
265
-            return 1;
266
-        }
267
-    }
268
-
269
-    /**
270
-     *	Initialise object with example values
271
-     *	Id must be 0 if object instance is a specimen
272
-     *
273
-     *	@return	void
274
-     */
275
-    function initAsSpecimen()
276
-    {
277
-        $this->id=0;
278
-        $this->code='';
279
-        $this->description='';
280
-        $this->value='';
281
-    }
282
-
283
-    /**
284
-     *	Checks if all parameters are in order
285
-     *
286
-     *	@return	void
287
-     */
288
-    function checkParameters()
289
-    {
290
-        // Clean parameters
291
-        if (isset($this->code)) $this->code=trim($this->code);
292
-        if (isset($this->description)) $this->description=trim($this->description);
293
-
294
-        // Check parameters
295
-        if (empty($this->value) || !is_numeric($this->value)) $this->value=0;
296
-    }
297
-
298
-    /**
299
-     *    List all price global variables
300
-     *
301
-     *    @return	array				Array of price global variables
302
-     */
303
-    function listGlobalVariables()
304
-    {
305
-        $sql = "SELECT rowid, code, description, value";
306
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
307
-        $sql.= " ORDER BY code";
308
-
309
-        dol_syslog(get_class($this)."::listGlobalVariables");
310
-        $resql=$this->db->query($sql);
311
-        if ($resql)
312
-        {
313
-            $retarray = array();
314
-
315
-            while ($record = $this->db->fetch_array($resql))
316
-            {
317
-                $variable_obj = new PriceGlobalVariable($this->db);
318
-                $variable_obj->id			= $record["rowid"];
319
-                $variable_obj->code			= $record["code"];
320
-                $variable_obj->description	= $record["description"];
321
-                $variable_obj->value			= $record["value"];
322
-                $variable_obj->checkParameters();
323
-                $retarray[]=$variable_obj;
324
-            }
325
-
326
-            $this->db->free($resql);
327
-            return $retarray;
328
-        }
329
-        else
330
-        {
331
-            $this->error=$this->db->error();
332
-            return -1;
333
-        }
334
-    }
32
+	var $db;							//!< To store db handler
33
+	var $error;							//!< To return error code (or message)
34
+	var $errors=array();				//!< To return several error codes (or messages)
35
+	var $id;
36
+	var $code;
37
+	var $description;
38
+	var $value;
39
+	public $table_element = "c_price_global_variable";
40
+
41
+	/**
42
+	 *  Constructor
43
+	 *
44
+	 *  @param	DoliDb		$db      Database handler
45
+	 */
46
+	function __construct($db)
47
+	{
48
+		$this->db = $db;
49
+		return 1;
50
+	}
51
+
52
+
53
+	/**
54
+	 *  Create object into database
55
+	 *
56
+	 *  @param	User	$user        User that creates
57
+	 *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
58
+	 *  @return int      		   	 <0 if KO, Id of created object if OK
59
+	 */
60
+	function create($user, $notrigger=0)
61
+	{
62
+		$error=0;
63
+
64
+		$this->checkParameters();
65
+
66
+		// Insert request
67
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
68
+		$sql.= "code, description, value";
69
+		$sql.= ") VALUES (";
70
+		$sql.= " ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
71
+		$sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
72
+		$sql.= " ".$this->value;
73
+		$sql.= ")";
74
+
75
+		$this->db->begin();
76
+
77
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
78
+		$resql=$this->db->query($sql);
79
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
80
+
81
+		if (! $error)
82
+		{
83
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
84
+
85
+			if (! $notrigger)
86
+			{
87
+				// Uncomment this and change MYOBJECT to your own tag if you
88
+				// want this action calls a trigger.
89
+
90
+				//// Call triggers
91
+				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
92
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
93
+				//// End call triggers
94
+			}
95
+		}
96
+
97
+		// Commit or rollback
98
+		if ($error)
99
+		{
100
+			foreach($this->errors as $errmsg)
101
+			{
102
+				dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
104
+			}
105
+			$this->db->rollback();
106
+			return -1*$error;
107
+		}
108
+		else
109
+		{
110
+			$this->db->commit();
111
+			return $this->id;
112
+		}
113
+	}
114
+
115
+
116
+	/**
117
+	 *  Load object in memory from the database
118
+	 *
119
+	 *  @param		int		$id    	Id object
120
+	 *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
121
+	 */
122
+	function fetch($id)
123
+	{
124
+		$sql = "SELECT code, description, value";
125
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
+		$sql.= " WHERE rowid = ".$id;
127
+
128
+		dol_syslog(get_class($this)."::fetch");
129
+		$resql=$this->db->query($sql);
130
+		if ($resql)
131
+		{
132
+			$obj = $this->db->fetch_object($resql);
133
+			if ($obj)
134
+			{
135
+				$this->id			= $id;
136
+				$this->code			= $obj->code;
137
+				$this->description	= $obj->description;
138
+				$this->value		= $obj->value;
139
+				$this->checkParameters();
140
+				return 1;
141
+			}
142
+			else
143
+			{
144
+				return 0;
145
+			}
146
+		}
147
+		else
148
+		{
149
+			$this->error="Error ".$this->db->lasterror();
150
+			return -1;
151
+		}
152
+	}
153
+
154
+	/**
155
+	 *  Update object into database
156
+	 *
157
+	 *  @param	User	$user        User that modifies
158
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
159
+	 *  @return int     		   	 <0 if KO, >0 if OK
160
+	 */
161
+	function update($user=0, $notrigger=0)
162
+	{
163
+		$error=0;
164
+
165
+		$this->checkParameters();
166
+
167
+		// Update request
168
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
169
+		$sql.= " code = ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
170
+		$sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
171
+		$sql.= " value = ".$this->value;
172
+		$sql.= " WHERE rowid = ".$this->id;
173
+
174
+		$this->db->begin();
175
+
176
+		dol_syslog(get_class($this)."::update");
177
+		$resql = $this->db->query($sql);
178
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
179
+
180
+		if (! $error)
181
+		{
182
+			if (! $notrigger)
183
+			{
184
+				// Uncomment this and change MYOBJECT to your own tag if you
185
+				// want this action calls a trigger.
186
+
187
+				//// Call triggers
188
+				//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
189
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
190
+				//// End call triggers
191
+			 }
192
+		}
193
+
194
+		// Commit or rollback
195
+		if ($error)
196
+		{
197
+			foreach($this->errors as $errmsg)
198
+			{
199
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
200
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
201
+			}
202
+			$this->db->rollback();
203
+			return -1*$error;
204
+		}
205
+		else
206
+		{
207
+			$this->db->commit();
208
+			return 1;
209
+		}
210
+	}
211
+
212
+
213
+	/**
214
+	 *  Delete object in database
215
+	 *
216
+	 * 	@param	int		$rowid		 Row id of global variable
217
+	 *	@param  User	$user        User that deletes
218
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
219
+	 *  @return	int					 <0 if KO, >0 if OK
220
+	 */
221
+	function delete($rowid, $user, $notrigger=0)
222
+	{
223
+		$error=0;
224
+
225
+		$this->db->begin();
226
+
227
+		if (! $error)
228
+		{
229
+			if (! $notrigger)
230
+			{
231
+				// Uncomment this and change MYOBJECT to your own tag if you
232
+				// want this action calls a trigger.
233
+
234
+				//// Call triggers
235
+				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
236
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
237
+				//// End call triggers
238
+			}
239
+		}
240
+
241
+		if (! $error)
242
+		{
243
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
244
+			$sql.= " WHERE rowid = ".$rowid;
245
+
246
+			dol_syslog(get_class($this)."::delete");
247
+			$resql = $this->db->query($sql);
248
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
249
+		}
250
+
251
+		// Commit or rollback
252
+		if ($error)
253
+		{
254
+			foreach($this->errors as $errmsg)
255
+			{
256
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
257
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
258
+			}
259
+			$this->db->rollback();
260
+			return -1*$error;
261
+		}
262
+		else
263
+		{
264
+			$this->db->commit();
265
+			return 1;
266
+		}
267
+	}
268
+
269
+	/**
270
+	 *	Initialise object with example values
271
+	 *	Id must be 0 if object instance is a specimen
272
+	 *
273
+	 *	@return	void
274
+	 */
275
+	function initAsSpecimen()
276
+	{
277
+		$this->id=0;
278
+		$this->code='';
279
+		$this->description='';
280
+		$this->value='';
281
+	}
282
+
283
+	/**
284
+	 *	Checks if all parameters are in order
285
+	 *
286
+	 *	@return	void
287
+	 */
288
+	function checkParameters()
289
+	{
290
+		// Clean parameters
291
+		if (isset($this->code)) $this->code=trim($this->code);
292
+		if (isset($this->description)) $this->description=trim($this->description);
293
+
294
+		// Check parameters
295
+		if (empty($this->value) || !is_numeric($this->value)) $this->value=0;
296
+	}
297
+
298
+	/**
299
+	 *    List all price global variables
300
+	 *
301
+	 *    @return	array				Array of price global variables
302
+	 */
303
+	function listGlobalVariables()
304
+	{
305
+		$sql = "SELECT rowid, code, description, value";
306
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
307
+		$sql.= " ORDER BY code";
308
+
309
+		dol_syslog(get_class($this)."::listGlobalVariables");
310
+		$resql=$this->db->query($sql);
311
+		if ($resql)
312
+		{
313
+			$retarray = array();
314
+
315
+			while ($record = $this->db->fetch_array($resql))
316
+			{
317
+				$variable_obj = new PriceGlobalVariable($this->db);
318
+				$variable_obj->id			= $record["rowid"];
319
+				$variable_obj->code			= $record["code"];
320
+				$variable_obj->description	= $record["description"];
321
+				$variable_obj->value			= $record["value"];
322
+				$variable_obj->checkParameters();
323
+				$retarray[]=$variable_obj;
324
+			}
325
+
326
+			$this->db->free($resql);
327
+			return $retarray;
328
+		}
329
+		else
330
+		{
331
+			$this->error=$this->db->error();
332
+			return -1;
333
+		}
334
+	}
335 335
 }
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -29,9 +29,9 @@  discard block
 block discarded – undo
29 29
  */
30 30
 class PriceGlobalVariable
31 31
 {
32
-    var $db;							//!< To store db handler
33
-    var $error;							//!< To return error code (or message)
34
-    var $errors=array();				//!< To return several error codes (or messages)
32
+    var $db; //!< To store db handler
33
+    var $error; //!< To return error code (or message)
34
+    var $errors = array(); //!< To return several error codes (or messages)
35 35
     var $id;
36 36
     var $code;
37 37
     var $description;
@@ -57,32 +57,32 @@  discard block
 block discarded – undo
57 57
      *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
58 58
      *  @return int      		   	 <0 if KO, Id of created object if OK
59 59
      */
60
-    function create($user, $notrigger=0)
60
+    function create($user, $notrigger = 0)
61 61
     {
62
-        $error=0;
62
+        $error = 0;
63 63
 
64 64
         $this->checkParameters();
65 65
 
66 66
         // Insert request
67 67
         $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
68
-        $sql.= "code, description, value";
69
-        $sql.= ") VALUES (";
70
-        $sql.= " ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
71
-        $sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
72
-        $sql.= " ".$this->value;
73
-        $sql.= ")";
68
+        $sql .= "code, description, value";
69
+        $sql .= ") VALUES (";
70
+        $sql .= " ".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "''").",";
71
+        $sql .= " ".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "''").",";
72
+        $sql .= " ".$this->value;
73
+        $sql .= ")";
74 74
 
75 75
         $this->db->begin();
76 76
 
77 77
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
78
-        $resql=$this->db->query($sql);
79
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
78
+        $resql = $this->db->query($sql);
79
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
80 80
 
81
-        if (! $error)
81
+        if (!$error)
82 82
         {
83 83
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
84 84
 
85
-            if (! $notrigger)
85
+            if (!$notrigger)
86 86
             {
87 87
                 // Uncomment this and change MYOBJECT to your own tag if you
88 88
                 // want this action calls a trigger.
@@ -97,13 +97,13 @@  discard block
 block discarded – undo
97 97
         // Commit or rollback
98 98
         if ($error)
99 99
         {
100
-            foreach($this->errors as $errmsg)
100
+            foreach ($this->errors as $errmsg)
101 101
             {
102 102
                 dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
103
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
103
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
104 104
             }
105 105
             $this->db->rollback();
106
-            return -1*$error;
106
+            return -1 * $error;
107 107
         }
108 108
         else
109 109
         {
@@ -122,19 +122,19 @@  discard block
 block discarded – undo
122 122
     function fetch($id)
123 123
     {
124 124
         $sql = "SELECT code, description, value";
125
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
-        $sql.= " WHERE rowid = ".$id;
125
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
126
+        $sql .= " WHERE rowid = ".$id;
127 127
 
128 128
         dol_syslog(get_class($this)."::fetch");
129
-        $resql=$this->db->query($sql);
129
+        $resql = $this->db->query($sql);
130 130
         if ($resql)
131 131
         {
132 132
             $obj = $this->db->fetch_object($resql);
133 133
             if ($obj)
134 134
             {
135
-                $this->id			= $id;
135
+                $this->id = $id;
136 136
                 $this->code			= $obj->code;
137
-                $this->description	= $obj->description;
137
+                $this->description = $obj->description;
138 138
                 $this->value		= $obj->value;
139 139
                 $this->checkParameters();
140 140
                 return 1;
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         }
147 147
         else
148 148
         {
149
-            $this->error="Error ".$this->db->lasterror();
149
+            $this->error = "Error ".$this->db->lasterror();
150 150
             return -1;
151 151
         }
152 152
     }
@@ -158,28 +158,28 @@  discard block
 block discarded – undo
158 158
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
159 159
      *  @return int     		   	 <0 if KO, >0 if OK
160 160
      */
161
-    function update($user=0, $notrigger=0)
161
+    function update($user = 0, $notrigger = 0)
162 162
     {
163
-        $error=0;
163
+        $error = 0;
164 164
 
165 165
         $this->checkParameters();
166 166
 
167 167
         // Update request
168 168
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
169
-        $sql.= " code = ".(isset($this->code)?"'".$this->db->escape($this->code)."'":"''").",";
170
-        $sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
171
-        $sql.= " value = ".$this->value;
172
-        $sql.= " WHERE rowid = ".$this->id;
169
+        $sql .= " code = ".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "''").",";
170
+        $sql .= " description = ".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "''").",";
171
+        $sql .= " value = ".$this->value;
172
+        $sql .= " WHERE rowid = ".$this->id;
173 173
 
174 174
         $this->db->begin();
175 175
 
176 176
         dol_syslog(get_class($this)."::update");
177 177
         $resql = $this->db->query($sql);
178
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
178
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
179 179
 
180
-        if (! $error)
180
+        if (!$error)
181 181
         {
182
-            if (! $notrigger)
182
+            if (!$notrigger)
183 183
             {
184 184
                 // Uncomment this and change MYOBJECT to your own tag if you
185 185
                 // want this action calls a trigger.
@@ -194,13 +194,13 @@  discard block
 block discarded – undo
194 194
         // Commit or rollback
195 195
         if ($error)
196 196
         {
197
-            foreach($this->errors as $errmsg)
197
+            foreach ($this->errors as $errmsg)
198 198
             {
199 199
                 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
200
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
200
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
201 201
             }
202 202
             $this->db->rollback();
203
-            return -1*$error;
203
+            return -1 * $error;
204 204
         }
205 205
         else
206 206
         {
@@ -218,15 +218,15 @@  discard block
 block discarded – undo
218 218
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
219 219
      *  @return	int					 <0 if KO, >0 if OK
220 220
      */
221
-    function delete($rowid, $user, $notrigger=0)
221
+    function delete($rowid, $user, $notrigger = 0)
222 222
     {
223
-        $error=0;
223
+        $error = 0;
224 224
 
225 225
         $this->db->begin();
226 226
 
227
-        if (! $error)
227
+        if (!$error)
228 228
         {
229
-            if (! $notrigger)
229
+            if (!$notrigger)
230 230
             {
231 231
                 // Uncomment this and change MYOBJECT to your own tag if you
232 232
                 // want this action calls a trigger.
@@ -238,26 +238,26 @@  discard block
 block discarded – undo
238 238
             }
239 239
         }
240 240
 
241
-        if (! $error)
241
+        if (!$error)
242 242
         {
243 243
             $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
244
-            $sql.= " WHERE rowid = ".$rowid;
244
+            $sql .= " WHERE rowid = ".$rowid;
245 245
 
246 246
             dol_syslog(get_class($this)."::delete");
247 247
             $resql = $this->db->query($sql);
248
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
248
+            if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
249 249
         }
250 250
 
251 251
         // Commit or rollback
252 252
         if ($error)
253 253
         {
254
-            foreach($this->errors as $errmsg)
254
+            foreach ($this->errors as $errmsg)
255 255
             {
256 256
                 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
257
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
257
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
258 258
             }
259 259
             $this->db->rollback();
260
-            return -1*$error;
260
+            return -1 * $error;
261 261
         }
262 262
         else
263 263
         {
@@ -274,10 +274,10 @@  discard block
 block discarded – undo
274 274
      */
275 275
     function initAsSpecimen()
276 276
     {
277
-        $this->id=0;
278
-        $this->code='';
279
-        $this->description='';
280
-        $this->value='';
277
+        $this->id = 0;
278
+        $this->code = '';
279
+        $this->description = '';
280
+        $this->value = '';
281 281
     }
282 282
 
283 283
     /**
@@ -288,11 +288,11 @@  discard block
 block discarded – undo
288 288
     function checkParameters()
289 289
     {
290 290
         // Clean parameters
291
-        if (isset($this->code)) $this->code=trim($this->code);
292
-        if (isset($this->description)) $this->description=trim($this->description);
291
+        if (isset($this->code)) $this->code = trim($this->code);
292
+        if (isset($this->description)) $this->description = trim($this->description);
293 293
 
294 294
         // Check parameters
295
-        if (empty($this->value) || !is_numeric($this->value)) $this->value=0;
295
+        if (empty($this->value) || !is_numeric($this->value)) $this->value = 0;
296 296
     }
297 297
 
298 298
     /**
@@ -303,11 +303,11 @@  discard block
 block discarded – undo
303 303
     function listGlobalVariables()
304 304
     {
305 305
         $sql = "SELECT rowid, code, description, value";
306
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
307
-        $sql.= " ORDER BY code";
306
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
307
+        $sql .= " ORDER BY code";
308 308
 
309 309
         dol_syslog(get_class($this)."::listGlobalVariables");
310
-        $resql=$this->db->query($sql);
310
+        $resql = $this->db->query($sql);
311 311
         if ($resql)
312 312
         {
313 313
             $retarray = array();
@@ -315,12 +315,12 @@  discard block
 block discarded – undo
315 315
             while ($record = $this->db->fetch_array($resql))
316 316
             {
317 317
                 $variable_obj = new PriceGlobalVariable($this->db);
318
-                $variable_obj->id			= $record["rowid"];
319
-                $variable_obj->code			= $record["code"];
320
-                $variable_obj->description	= $record["description"];
321
-                $variable_obj->value			= $record["value"];
318
+                $variable_obj->id = $record["rowid"];
319
+                $variable_obj->code = $record["code"];
320
+                $variable_obj->description = $record["description"];
321
+                $variable_obj->value = $record["value"];
322 322
                 $variable_obj->checkParameters();
323
-                $retarray[]=$variable_obj;
323
+                $retarray[] = $variable_obj;
324 324
             }
325 325
 
326 326
             $this->db->free($resql);
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
         }
329 329
         else
330 330
         {
331
-            $this->error=$this->db->error();
331
+            $this->error = $this->db->error();
332 332
             return -1;
333 333
         }
334 334
     }
Please login to merge, or discard this patch.
Braces   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -104,8 +104,7 @@  discard block
 block discarded – undo
104 104
             }
105 105
             $this->db->rollback();
106 106
             return -1*$error;
107
-        }
108
-        else
107
+        } else
109 108
         {
110 109
             $this->db->commit();
111 110
             return $this->id;
@@ -138,13 +137,11 @@  discard block
 block discarded – undo
138 137
                 $this->value		= $obj->value;
139 138
                 $this->checkParameters();
140 139
                 return 1;
141
-            }
142
-            else
140
+            } else
143 141
             {
144 142
                 return 0;
145 143
             }
146
-        }
147
-        else
144
+        } else
148 145
         {
149 146
             $this->error="Error ".$this->db->lasterror();
150 147
             return -1;
@@ -201,8 +198,7 @@  discard block
 block discarded – undo
201 198
             }
202 199
             $this->db->rollback();
203 200
             return -1*$error;
204
-        }
205
-        else
201
+        } else
206 202
         {
207 203
             $this->db->commit();
208 204
             return 1;
@@ -258,8 +254,7 @@  discard block
 block discarded – undo
258 254
             }
259 255
             $this->db->rollback();
260 256
             return -1*$error;
261
-        }
262
-        else
257
+        } else
263 258
         {
264 259
             $this->db->commit();
265 260
             return 1;
@@ -288,11 +283,17 @@  discard block
 block discarded – undo
288 283
     function checkParameters()
289 284
     {
290 285
         // Clean parameters
291
-        if (isset($this->code)) $this->code=trim($this->code);
292
-        if (isset($this->description)) $this->description=trim($this->description);
286
+        if (isset($this->code)) {
287
+        	$this->code=trim($this->code);
288
+        }
289
+        if (isset($this->description)) {
290
+        	$this->description=trim($this->description);
291
+        }
293 292
 
294 293
         // Check parameters
295
-        if (empty($this->value) || !is_numeric($this->value)) $this->value=0;
294
+        if (empty($this->value) || !is_numeric($this->value)) {
295
+        	$this->value=0;
296
+        }
296 297
     }
297 298
 
298 299
     /**
@@ -325,8 +326,7 @@  discard block
 block discarded – undo
325 326
 
326 327
             $this->db->free($resql);
327 328
             return $retarray;
328
-        }
329
-        else
329
+        } else
330 330
         {
331 331
             $this->error=$this->db->error();
332 332
             return -1;
Please login to merge, or discard this patch.
htdocs/product/stock/class/entrepot.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -673,7 +673,7 @@
 block discarded – undo
673 673
 	 * Return array of children warehouses ids from $id warehouse (recursive function)
674 674
 	 *
675 675
 	 * @param	int		$id					id parent warehouse
676
-	 * @param	array()	$TChildWarehouses	array which will contain all children (param by reference)
676
+	 * @param	integer[]	$TChildWarehouses	array which will contain all children (param by reference)
677 677
 	 * @return	array()	$TChildWarehouses	array which will contain all children
678 678
 	 */
679 679
 	function get_children_warehouses($id, &$TChildWarehouses) {
Please login to merge, or discard this patch.
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	 */
161 161
 	function update($id, $user)
162 162
 	{
163
-	    if (empty($id)) $id = $this->id;
163
+		if (empty($id)) $id = $this->id;
164 164
 
165 165
 		// Check if new parent is already a child of current warehouse
166 166
 		if(!empty($this->fk_parent))
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 
228 228
 		if (! $error && empty($notrigger))
229 229
 		{
230
-            // Call trigger
231
-            $result=$this->call_trigger('WAREHOUSE_DELETE',$user);
232
-            if ($result < 0) { $error++; }
233
-            // End call triggers
230
+			// Call trigger
231
+			$result=$this->call_trigger('WAREHOUSE_DELETE',$user);
232
+			if ($result < 0) { $error++; }
233
+			// End call triggers
234 234
 		}
235 235
 
236 236
 		$elements = array('stock_mouvement','product_stock','product_warehouse_properties');
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 				$this->country_id     = $obj->country_id;
332 332
 
333 333
 				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
334
-	            $tmp=getCountry($this->country_id,'all');
334
+				$tmp=getCountry($this->country_id,'all');
335 335
 				$this->country=$tmp['label'];
336 336
 				$this->country_code=$tmp['code'];
337 337
 
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 		}
395 395
 		else
396 396
 		{
397
-	        dol_print_error($this->db);
397
+			dol_print_error($this->db);
398 398
 		}
399 399
 	}
400 400
 
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 	 *	@param		int		$withpicto		with pictogram
561 561
 	 *	@param		string	$option			Where the link point to
562 562
 	 *  @param      int     $showfullpath   0=Show ref only. 1=Show full path instead of Ref (this->fk_parent must be defined)
563
-     *  @param	    int   	$notooltip		1=Disable tooltip
563
+	 *  @param	    int   	$notooltip		1=Disable tooltip
564 564
 	 *	@return		string					String with URL
565 565
 	 */
566 566
 	function getNomUrl($withpicto=0, $option='',$showfullpath=0, $notooltip=0)
@@ -568,66 +568,66 @@  discard block
 block discarded – undo
568 568
 		global $conf, $langs;
569 569
 		$langs->load("stocks");
570 570
 
571
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
571
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
572 572
 
573
-        $result='';
574
-        $label = '';
573
+		$result='';
574
+		$label = '';
575 575
 
576
-        $label = '<u>' . $langs->trans("ShowWarehouse").'</u>';
577
-        $label.= '<br><b>' . $langs->trans('Ref') . ':</b> ' . (empty($this->label)?$this->libelle:$this->label);
578
-        if (! empty($this->lieu))
579
-            $label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
576
+		$label = '<u>' . $langs->trans("ShowWarehouse").'</u>';
577
+		$label.= '<br><b>' . $langs->trans('Ref') . ':</b> ' . (empty($this->label)?$this->libelle:$this->label);
578
+		if (! empty($this->lieu))
579
+			$label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
580 580
 
581
-        $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
581
+		$url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
582 582
 
583
-        $linkclose='';
584
-        if (empty($notooltip))
585
-        {
586
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
587
-            {
588
-                $label=$langs->trans("ShowWarehouse");
589
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
590
-            }
591
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
592
-            $linkclose.=' class="classfortooltip"';
593
-        }
583
+		$linkclose='';
584
+		if (empty($notooltip))
585
+		{
586
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
587
+			{
588
+				$label=$langs->trans("ShowWarehouse");
589
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
590
+			}
591
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
592
+			$linkclose.=' class="classfortooltip"';
593
+		}
594 594
 
595
-        $linkstart = '<a href="'.$url.'"';
596
-        $linkstart.=$linkclose.'>';
597
-        $linkend='</a>';
595
+		$linkstart = '<a href="'.$url.'"';
596
+		$linkstart.=$linkclose.'>';
597
+		$linkend='</a>';
598 598
 
599
-        if ($withpicto) $result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
599
+		if ($withpicto) $result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
600 600
 		$result.=$linkstart.($showfullpath ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label)).$linkend;
601 601
 		return $result;
602 602
 	}
603 603
 
604 604
 	/**
605
-     *  Initialise an instance with random values.
606
-     *  Used to build previews or test instances.
607
-     *	id must be 0 if object instance is a specimen.
608
-     *
609
-     *  @return	void
610
-     */
611
-    function initAsSpecimen()
612
-    {
613
-        global $user,$langs,$conf,$mysoc;
614
-
615
-        $now=dol_now();
616
-
617
-        // Initialize parameters
618
-        $this->id=0;
619
-        $this->libelle = 'WAREHOUSE SPECIMEN';
620
-        $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now,'dayhourlog');
605
+	 *  Initialise an instance with random values.
606
+	 *  Used to build previews or test instances.
607
+	 *	id must be 0 if object instance is a specimen.
608
+	 *
609
+	 *  @return	void
610
+	 */
611
+	function initAsSpecimen()
612
+	{
613
+		global $user,$langs,$conf,$mysoc;
614
+
615
+		$now=dol_now();
616
+
617
+		// Initialize parameters
618
+		$this->id=0;
619
+		$this->libelle = 'WAREHOUSE SPECIMEN';
620
+		$this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now,'dayhourlog');
621 621
 		$this->statut=1;
622
-        $this->specimen=1;
622
+		$this->specimen=1;
623 623
 
624 624
 		$this->lieu='Location test';
625
-        $this->address='21 jump street';
626
-        $this->zip='99999';
627
-        $this->town='MyTown';
628
-        $this->country_id=1;
629
-        $this->country_code='FR';
630
-    }
625
+		$this->address='21 jump street';
626
+		$this->zip='99999';
627
+		$this->town='MyTown';
628
+		$this->country_id=1;
629
+		$this->country_code='FR';
630
+	}
631 631
 
632 632
 	/**
633 633
 	 *	Return full path to current warehouse
@@ -636,37 +636,37 @@  discard block
 block discarded – undo
636 636
 	 */
637 637
 	function get_full_arbo()
638 638
 	{
639
-        global $user,$langs,$conf;
640
-
641
-        $TArbo = array(empty($this->label)?$this->libelle:$this->label);
642
-
643
-        $protection=100; // We limit depth of warehouses to 100
644
-
645
-        $warehousetmp = new Entrepot($this->db);
646
-
647
-        $parentid = $this->fk_parent;       // If parent_id not defined on current object, we do not start consecutive searches of parents
648
-        $i=0;
649
-        while ($parentid > 0 && $i < $protection)
650
-        {
651
-            $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid;
652
-            $resql = $this->db->query($sql);
653
-            if ($resql)
654
-            {
655
-                $objarbo = $this->db->fetch_object($resql);
656
-                if ($objarbo)
657
-                {
658
-                	$warehousetmp->fetch($parentid);
659
-                	$TArbo[] = $warehousetmp->label;
660
-                 	$parentid = $objarbo->fk_parent;
661
-                }
662
-                else break;
663
-            }
664
-            else dol_print_error($this->db);
665
-
666
-            $i++;
667
-        }
668
-
669
-        return implode(' >> ', array_reverse($TArbo));
639
+		global $user,$langs,$conf;
640
+
641
+		$TArbo = array(empty($this->label)?$this->libelle:$this->label);
642
+
643
+		$protection=100; // We limit depth of warehouses to 100
644
+
645
+		$warehousetmp = new Entrepot($this->db);
646
+
647
+		$parentid = $this->fk_parent;       // If parent_id not defined on current object, we do not start consecutive searches of parents
648
+		$i=0;
649
+		while ($parentid > 0 && $i < $protection)
650
+		{
651
+			$sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid;
652
+			$resql = $this->db->query($sql);
653
+			if ($resql)
654
+			{
655
+				$objarbo = $this->db->fetch_object($resql);
656
+				if ($objarbo)
657
+				{
658
+					$warehousetmp->fetch($parentid);
659
+					$TArbo[] = $warehousetmp->label;
660
+				 	$parentid = $objarbo->fk_parent;
661
+				}
662
+				else break;
663
+			}
664
+			else dol_print_error($this->db);
665
+
666
+			$i++;
667
+		}
668
+
669
+		return implode(' >> ', array_reverse($TArbo));
670 670
 	}
671 671
 
672 672
 	/**
Please login to merge, or discard this patch.
Spacing   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -33,9 +33,9 @@  discard block
 block discarded – undo
33 33
  */
34 34
 class Entrepot extends CommonObject
35 35
 {
36
-	public $element='stock';
37
-	public $table_element='entrepot';
38
-	public $picto='stock';
36
+	public $element = 'stock';
37
+	public $table_element = 'entrepot';
38
+	public $picto = 'stock';
39 39
 
40 40
 	/**
41 41
 	 * Warehouse closed, inactive
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 			return 0;
108 108
 		}
109 109
 
110
-		$now=dol_now();
110
+		$now = dol_now();
111 111
 
112 112
 		$this->db->begin();
113 113
 
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 		$sql .= " VALUES (".$conf->entity.",'".$this->db->idate($now)."',".$user->id.",'".$this->db->escape($this->libelle)."', ".($this->fk_parent > 0 ? $this->fk_parent : "NULL").")";
116 116
 
117 117
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
118
-		$result=$this->db->query($sql);
118
+		$result = $this->db->query($sql);
119 119
 		if ($result)
120 120
 		{
121 121
 			$id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot");
@@ -136,14 +136,14 @@  discard block
 block discarded – undo
136 136
 				}
137 137
 			}
138 138
 			else {
139
-				$this->error="Failed to get insert id";
139
+				$this->error = "Failed to get insert id";
140 140
 				dol_syslog(get_class($this)."::create return -2");
141 141
 				return -2;
142 142
 			}
143 143
 		}
144 144
 		else
145 145
 		{
146
-			$this->error=$this->db->error();
146
+			$this->error = $this->db->error();
147 147
 			dol_syslog(get_class($this)."::create Error ".$this->db->error());
148 148
 			$this->db->rollback();
149 149
 			return -1;
@@ -163,43 +163,43 @@  discard block
 block discarded – undo
163 163
 	    if (empty($id)) $id = $this->id;
164 164
 
165 165
 		// Check if new parent is already a child of current warehouse
166
-		if(!empty($this->fk_parent))
166
+		if (!empty($this->fk_parent))
167 167
 		{
168 168
 			$TChildWarehouses = array($id);
169 169
 			$TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses);
170
-			if(in_array($this->fk_parent, $TChildWarehouses))
170
+			if (in_array($this->fk_parent, $TChildWarehouses))
171 171
 			{
172 172
 				$this->error = 'ErrorCannotAddThisParentWarehouse';
173 173
 				return -2;
174 174
 			}
175 175
 		}
176 176
 
177
-		$this->libelle=trim($this->libelle);
178
-		$this->description=trim($this->description);
177
+		$this->libelle = trim($this->libelle);
178
+		$this->description = trim($this->description);
179 179
 
180
-		$this->lieu=trim($this->lieu);
180
+		$this->lieu = trim($this->lieu);
181 181
 
182
-		$this->address=trim($this->address);
183
-		$this->zip=trim($this->zip);
184
-		$this->town=trim($this->town);
185
-		$this->country_id=($this->country_id > 0 ? $this->country_id : 0);
182
+		$this->address = trim($this->address);
183
+		$this->zip = trim($this->zip);
184
+		$this->town = trim($this->town);
185
+		$this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
186 186
 
187 187
 		$sql = "UPDATE ".MAIN_DB_PREFIX."entrepot ";
188
-		$sql .= " SET label = '" . $this->db->escape($this->libelle) ."'";
189
-		$sql .= ", fk_parent = " . (($this->fk_parent > 0) ? $this->fk_parent : "NULL");
190
-		$sql .= ", description = '" . $this->db->escape($this->description) ."'";
191
-		$sql .= ", statut = " . $this->statut;
192
-		$sql .= ", lieu = '" . $this->db->escape($this->lieu) ."'";
193
-		$sql .= ", address = '" . $this->db->escape($this->address) ."'";
194
-		$sql .= ", zip = '" . $this->db->escape($this->zip) ."'";
195
-		$sql .= ", town = '" . $this->db->escape($this->town) ."'";
196
-		$sql .= ", fk_pays = " . $this->country_id;
197
-		$sql .= " WHERE rowid = " . $id;
188
+		$sql .= " SET label = '".$this->db->escape($this->libelle)."'";
189
+		$sql .= ", fk_parent = ".(($this->fk_parent > 0) ? $this->fk_parent : "NULL");
190
+		$sql .= ", description = '".$this->db->escape($this->description)."'";
191
+		$sql .= ", statut = ".$this->statut;
192
+		$sql .= ", lieu = '".$this->db->escape($this->lieu)."'";
193
+		$sql .= ", address = '".$this->db->escape($this->address)."'";
194
+		$sql .= ", zip = '".$this->db->escape($this->zip)."'";
195
+		$sql .= ", town = '".$this->db->escape($this->town)."'";
196
+		$sql .= ", fk_pays = ".$this->country_id;
197
+		$sql .= " WHERE rowid = ".$id;
198 198
 
199 199
 		$this->db->begin();
200 200
 
201 201
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
202
-		$resql=$this->db->query($sql);
202
+		$resql = $this->db->query($sql);
203 203
 		if ($resql)
204 204
 		{
205 205
 			$this->db->commit();
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 		else
209 209
 		{
210 210
 			$this->db->rollback();
211
-			$this->error=$this->db->lasterror();
211
+			$this->error = $this->db->lasterror();
212 212
 			return -1;
213 213
 		}
214 214
 	}
@@ -221,28 +221,28 @@  discard block
 block discarded – undo
221 221
 	 *  @param      int     $notrigger     1=No trigger
222 222
 	 *	@return		int					   <0 if KO, >0 if OK
223 223
 	 */
224
-	function delete($user, $notrigger=0)
224
+	function delete($user, $notrigger = 0)
225 225
 	{
226 226
 		$this->db->begin();
227 227
 
228
-		if (! $error && empty($notrigger))
228
+		if (!$error && empty($notrigger))
229 229
 		{
230 230
             // Call trigger
231
-            $result=$this->call_trigger('WAREHOUSE_DELETE',$user);
231
+            $result = $this->call_trigger('WAREHOUSE_DELETE', $user);
232 232
             if ($result < 0) { $error++; }
233 233
             // End call triggers
234 234
 		}
235 235
 
236
-		$elements = array('stock_mouvement','product_stock','product_warehouse_properties');
237
-		foreach($elements as $table)
236
+		$elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties');
237
+		foreach ($elements as $table)
238 238
 		{
239
-			if (! $error)
239
+			if (!$error)
240 240
 			{
241 241
 				$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
242
-				$sql.= " WHERE fk_entrepot = " . $this->id;
242
+				$sql .= " WHERE fk_entrepot = ".$this->id;
243 243
 				dol_syslog(get_class($this)."::delete", LOG_DEBUG);
244
-				$result=$this->db->query($sql);
245
-				if (! $result)
244
+				$result = $this->db->query($sql);
245
+				if (!$result)
246 246
 				{
247 247
 					$error++;
248 248
 					$this->errors[] = $this->db->lasterror();
@@ -250,19 +250,19 @@  discard block
 block discarded – undo
250 250
 			}
251 251
 		}
252 252
 
253
-		if (! $error)
253
+		if (!$error)
254 254
 		{
255 255
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot";
256
-			$sql.= " WHERE rowid = " . $this->id;
256
+			$sql .= " WHERE rowid = ".$this->id;
257 257
 
258 258
 			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
259
-			$resql1=$this->db->query($sql);
259
+			$resql1 = $this->db->query($sql);
260 260
 
261 261
 			// Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
262 262
 			$sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
263 263
 
264 264
 			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
265
-			$resql2=$this->db->query($sql);
265
+			$resql2 = $this->db->query($sql);
266 266
 
267 267
 			if ($resql1 && $resql2)
268 268
 			{
@@ -272,14 +272,14 @@  discard block
 block discarded – undo
272 272
 			else
273 273
 			{
274 274
 				$this->db->rollback();
275
-				$this->error=$this->db->lasterror();
275
+				$this->error = $this->db->lasterror();
276 276
 				return -2;
277 277
 			}
278 278
 		}
279 279
 		else
280 280
 		{
281 281
 			$this->db->rollback();
282
-			$this->error=$this->db->lasterror();
282
+			$this->error = $this->db->lasterror();
283 283
 			return -1;
284 284
 		}
285 285
 
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 	 *	@param		string	$ref	Warehouse label
294 294
 	 *	@return		int				>0 if OK, <0 if KO
295 295
 	 */
296
-	function fetch($id, $ref='')
296
+	function fetch($id, $ref = '')
297 297
 	{
298 298
 		global $conf;
299 299
 
@@ -301,12 +301,12 @@  discard block
 block discarded – undo
301 301
 		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot";
302 302
 		if ($id)
303 303
 		{
304
-			$sql.= " WHERE rowid = '".$id."'";
304
+			$sql .= " WHERE rowid = '".$id."'";
305 305
 		}
306 306
 		else
307 307
 		{
308
-			$sql.= " WHERE entity = " .$conf->entity;
309
-			if ($ref) $sql.= " AND label = '".$this->db->escape($ref)."'";
308
+			$sql .= " WHERE entity = ".$conf->entity;
309
+			if ($ref) $sql .= " AND label = '".$this->db->escape($ref)."'";
310 310
 		}
311 311
 
312 312
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
@@ -315,13 +315,13 @@  discard block
 block discarded – undo
315 315
 		{
316 316
 			if ($this->db->num_rows($result) > 0)
317 317
 			{
318
-				$obj=$this->db->fetch_object($result);
318
+				$obj = $this->db->fetch_object($result);
319 319
 
320 320
 				$this->id             = $obj->rowid;
321 321
 				$this->fk_parent      = $obj->fk_parent;
322 322
 				$this->ref            = $obj->rowid;
323 323
 				$this->label          = $obj->label;
324
-				$this->libelle        = $obj->label;            // deprecated
324
+				$this->libelle        = $obj->label; // deprecated
325 325
 				$this->description    = $obj->description;
326 326
 				$this->statut         = $obj->statut;
327 327
 				$this->lieu           = $obj->lieu;
@@ -331,9 +331,9 @@  discard block
 block discarded – undo
331 331
 				$this->country_id     = $obj->country_id;
332 332
 
333 333
 				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
334
-	            $tmp=getCountry($this->country_id,'all');
335
-				$this->country=$tmp['label'];
336
-				$this->country_code=$tmp['code'];
334
+	            $tmp = getCountry($this->country_id, 'all');
335
+				$this->country = $tmp['label'];
336
+				$this->country_code = $tmp['code'];
337 337
 
338 338
 				return 1;
339 339
 			}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 		}
345 345
 		else
346 346
 		{
347
-			$this->error=$this->db->error();
347
+			$this->error = $this->db->error();
348 348
 			return -1;
349 349
 		}
350 350
 	}
@@ -359,11 +359,11 @@  discard block
 block discarded – undo
359 359
 	function info($id)
360 360
 	{
361 361
 		$sql = "SELECT e.rowid, e.datec, e.tms as datem, e.fk_user_author";
362
-		$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
363
-		$sql.= " WHERE e.rowid = ".$id;
362
+		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e";
363
+		$sql .= " WHERE e.rowid = ".$id;
364 364
 
365 365
 		dol_syslog(get_class($this)."::info", LOG_DEBUG);
366
-		$result=$this->db->query($sql);
366
+		$result = $this->db->query($sql);
367 367
 		if ($result)
368 368
 		{
369 369
 			if ($this->db->num_rows($result))
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 				if ($obj->fk_user_author) {
376 376
 					$cuser = new User($this->db);
377 377
 					$cuser->fetch($obj->fk_user_author);
378
-					$this->user_creation     = $cuser;
378
+					$this->user_creation = $cuser;
379 379
 				}
380 380
 
381 381
 				if ($obj->fk_user_valid) {
@@ -405,19 +405,19 @@  discard block
 block discarded – undo
405 405
 	 *	@param	int		$status		Status
406 406
 	 * 	@return array				Array list of warehouses
407 407
 	 */
408
-	function list_array($status=1)
408
+	function list_array($status = 1)
409 409
 	{
410 410
 		$liste = array();
411 411
 
412 412
 		$sql = "SELECT rowid, label";
413
-		$sql.= " FROM ".MAIN_DB_PREFIX."entrepot";
414
-		$sql.= " WHERE entity IN (".getEntity('stock').")";
415
-		$sql.= " AND statut = ".$status;
413
+		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot";
414
+		$sql .= " WHERE entity IN (".getEntity('stock').")";
415
+		$sql .= " AND statut = ".$status;
416 416
 
417 417
 		$result = $this->db->query($sql);
418 418
 		$i = 0;
419 419
 		$num = $this->db->num_rows($result);
420
-		if ( $result )
420
+		if ($result)
421 421
 		{
422 422
 			while ($i < $num)
423 423
 			{
@@ -437,25 +437,25 @@  discard block
 block discarded – undo
437 437
 	 */
438 438
 	function nb_different_products()
439 439
 	{
440
-		$ret=array();
440
+		$ret = array();
441 441
 
442 442
 		$sql = "SELECT count(distinct p.rowid) as nb";
443
-		$sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
444
-		$sql.= ", ".MAIN_DB_PREFIX."product as p";
445
-		$sql.= " WHERE ps.fk_entrepot = ".$this->id;
446
-		$sql.= " AND ps.fk_product = p.rowid";
443
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
444
+		$sql .= ", ".MAIN_DB_PREFIX."product as p";
445
+		$sql .= " WHERE ps.fk_entrepot = ".$this->id;
446
+		$sql .= " AND ps.fk_product = p.rowid";
447 447
 
448 448
 		//print $sql;
449 449
 		$result = $this->db->query($sql);
450 450
 		if ($result)
451 451
 		{
452 452
 			$obj = $this->db->fetch_object($result);
453
-			$ret['nb']=$obj->nb;
453
+			$ret['nb'] = $obj->nb;
454 454
 			$this->db->free($result);
455 455
 		}
456 456
 		else
457 457
 		{
458
-			$this->error=$this->db->lasterror();
458
+			$this->error = $this->db->lasterror();
459 459
 			return -1;
460 460
 		}
461 461
 
@@ -469,26 +469,26 @@  discard block
 block discarded – undo
469 469
 	 */
470 470
 	function nb_products()
471 471
 	{
472
-		$ret=array();
472
+		$ret = array();
473 473
 
474 474
 		$sql = "SELECT sum(ps.reel) as nb, sum(ps.reel * p.pmp) as value";
475
-		$sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
476
-		$sql.= ", ".MAIN_DB_PREFIX."product as p";
477
-		$sql.= " WHERE ps.fk_entrepot = ".$this->id;
478
-		$sql.= " AND ps.fk_product = p.rowid";
475
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
476
+		$sql .= ", ".MAIN_DB_PREFIX."product as p";
477
+		$sql .= " WHERE ps.fk_entrepot = ".$this->id;
478
+		$sql .= " AND ps.fk_product = p.rowid";
479 479
 
480 480
 		//print $sql;
481 481
 		$result = $this->db->query($sql);
482 482
 		if ($result)
483 483
 		{
484 484
 			$obj = $this->db->fetch_object($result);
485
-			$ret['nb']=$obj->nb;
486
-			$ret['value']=$obj->value;
485
+			$ret['nb'] = $obj->nb;
486
+			$ret['value'] = $obj->value;
487 487
 			$this->db->free($result);
488 488
 		}
489 489
 		else
490 490
 		{
491
-			$this->error=$this->db->lasterror();
491
+			$this->error = $this->db->lasterror();
492 492
 			return -1;
493 493
 		}
494 494
 
@@ -501,9 +501,9 @@  discard block
 block discarded – undo
501 501
 	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
502 502
 	 *	@return     string      		Label of status
503 503
 	 */
504
-	function getLibStatut($mode=0)
504
+	function getLibStatut($mode = 0)
505 505
 	{
506
-		return $this->LibStatut($this->statut,$mode);
506
+		return $this->LibStatut($this->statut, $mode);
507 507
 	}
508 508
 
509 509
 	/**
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	 *	@param  int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
514 514
 	 *	@return string      		Label of status
515 515
 	 */
516
-	function LibStatut($statut,$mode=0)
516
+	function LibStatut($statut, $mode = 0)
517 517
 	{
518 518
 		global $langs;
519 519
 
@@ -563,41 +563,41 @@  discard block
 block discarded – undo
563 563
      *  @param	    int   	$notooltip		1=Disable tooltip
564 564
 	 *	@return		string					String with URL
565 565
 	 */
566
-	function getNomUrl($withpicto=0, $option='',$showfullpath=0, $notooltip=0)
566
+	function getNomUrl($withpicto = 0, $option = '', $showfullpath = 0, $notooltip = 0)
567 567
 	{
568 568
 		global $conf, $langs;
569 569
 		$langs->load("stocks");
570 570
 
571
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
571
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
572 572
 
573
-        $result='';
573
+        $result = '';
574 574
         $label = '';
575 575
 
576
-        $label = '<u>' . $langs->trans("ShowWarehouse").'</u>';
577
-        $label.= '<br><b>' . $langs->trans('Ref') . ':</b> ' . (empty($this->label)?$this->libelle:$this->label);
578
-        if (! empty($this->lieu))
579
-            $label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
576
+        $label = '<u>'.$langs->trans("ShowWarehouse").'</u>';
577
+        $label .= '<br><b>'.$langs->trans('Ref').':</b> '.(empty($this->label) ? $this->libelle : $this->label);
578
+        if (!empty($this->lieu))
579
+            $label .= '<br><b>'.$langs->trans('LocationSummary').':</b> '.$this->lieu;
580 580
 
581 581
         $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
582 582
 
583
-        $linkclose='';
583
+        $linkclose = '';
584 584
         if (empty($notooltip))
585 585
         {
586
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
586
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
587 587
             {
588
-                $label=$langs->trans("ShowWarehouse");
589
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
588
+                $label = $langs->trans("ShowWarehouse");
589
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
590 590
             }
591
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
592
-            $linkclose.=' class="classfortooltip"';
591
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
592
+            $linkclose .= ' class="classfortooltip"';
593 593
         }
594 594
 
595 595
         $linkstart = '<a href="'.$url.'"';
596
-        $linkstart.=$linkclose.'>';
597
-        $linkend='</a>';
596
+        $linkstart .= $linkclose.'>';
597
+        $linkend = '</a>';
598 598
 
599
-        if ($withpicto) $result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
600
-		$result.=$linkstart.($showfullpath ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label)).$linkend;
599
+        if ($withpicto) $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend.' ');
600
+		$result .= $linkstart.($showfullpath ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label)).$linkend;
601 601
 		return $result;
602 602
 	}
603 603
 
@@ -610,23 +610,23 @@  discard block
 block discarded – undo
610 610
      */
611 611
     function initAsSpecimen()
612 612
     {
613
-        global $user,$langs,$conf,$mysoc;
613
+        global $user, $langs, $conf, $mysoc;
614 614
 
615
-        $now=dol_now();
615
+        $now = dol_now();
616 616
 
617 617
         // Initialize parameters
618
-        $this->id=0;
618
+        $this->id = 0;
619 619
         $this->libelle = 'WAREHOUSE SPECIMEN';
620
-        $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now,'dayhourlog');
621
-		$this->statut=1;
622
-        $this->specimen=1;
623
-
624
-		$this->lieu='Location test';
625
-        $this->address='21 jump street';
626
-        $this->zip='99999';
627
-        $this->town='MyTown';
628
-        $this->country_id=1;
629
-        $this->country_code='FR';
620
+        $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now, 'dayhourlog');
621
+		$this->statut = 1;
622
+        $this->specimen = 1;
623
+
624
+		$this->lieu = 'Location test';
625
+        $this->address = '21 jump street';
626
+        $this->zip = '99999';
627
+        $this->town = 'MyTown';
628
+        $this->country_id = 1;
629
+        $this->country_code = 'FR';
630 630
     }
631 631
 
632 632
 	/**
@@ -636,16 +636,16 @@  discard block
 block discarded – undo
636 636
 	 */
637 637
 	function get_full_arbo()
638 638
 	{
639
-        global $user,$langs,$conf;
639
+        global $user, $langs, $conf;
640 640
 
641
-        $TArbo = array(empty($this->label)?$this->libelle:$this->label);
641
+        $TArbo = array(empty($this->label) ? $this->libelle : $this->label);
642 642
 
643
-        $protection=100; // We limit depth of warehouses to 100
643
+        $protection = 100; // We limit depth of warehouses to 100
644 644
 
645 645
         $warehousetmp = new Entrepot($this->db);
646 646
 
647
-        $parentid = $this->fk_parent;       // If parent_id not defined on current object, we do not start consecutive searches of parents
648
-        $i=0;
647
+        $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents
648
+        $i = 0;
649 649
         while ($parentid > 0 && $i < $protection)
650 650
         {
651 651
             $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid;
@@ -683,8 +683,8 @@  discard block
 block discarded – undo
683 683
 				WHERE fk_parent = '.$id;
684 684
 
685 685
 		$resql = $this->db->query($sql);
686
-		if($resql) {
687
-			while($res = $this->db->fetch_object($resql)) {
686
+		if ($resql) {
687
+			while ($res = $this->db->fetch_object($resql)) {
688 688
 				$TChildWarehouses[] = $res->rowid;
689 689
 				$this->get_children_warehouses($res->rowid, $TChildWarehouses);
690 690
 			}
Please login to merge, or discard this patch.
Braces   +45 added lines, -38 removed lines patch added patch discarded remove patch
@@ -80,8 +80,7 @@  discard block
 block discarded – undo
80 80
 		{
81 81
 			$this->statuts[self::STATUS_OPEN_ALL] = 'OpenAll';
82 82
 			$this->statuts[self::STATUS_OPEN_INTERNAL] = 'OpenInternal';
83
-		}
84
-		else
83
+		} else
85 84
 		{
86 85
 			$this->statuts[self::STATUS_OPEN_ALL] = 'Opened';
87 86
 		}
@@ -127,21 +126,18 @@  discard block
 block discarded – undo
127 126
 				{
128 127
 					$this->db->commit();
129 128
 					return $id;
130
-				}
131
-				else
129
+				} else
132 130
 				{
133 131
 					dol_syslog(get_class($this)."::create return -3");
134 132
 					$this->db->rollback();
135 133
 					return -3;
136 134
 				}
137
-			}
138
-			else {
135
+			} else {
139 136
 				$this->error="Failed to get insert id";
140 137
 				dol_syslog(get_class($this)."::create return -2");
141 138
 				return -2;
142 139
 			}
143
-		}
144
-		else
140
+		} else
145 141
 		{
146 142
 			$this->error=$this->db->error();
147 143
 			dol_syslog(get_class($this)."::create Error ".$this->db->error());
@@ -160,7 +156,9 @@  discard block
 block discarded – undo
160 156
 	 */
161 157
 	function update($id, $user)
162 158
 	{
163
-	    if (empty($id)) $id = $this->id;
159
+	    if (empty($id)) {
160
+	    	$id = $this->id;
161
+	    }
164 162
 
165 163
 		// Check if new parent is already a child of current warehouse
166 164
 		if(!empty($this->fk_parent))
@@ -204,8 +202,7 @@  discard block
 block discarded – undo
204 202
 		{
205 203
 			$this->db->commit();
206 204
 			return 1;
207
-		}
208
-		else
205
+		} else
209 206
 		{
210 207
 			$this->db->rollback();
211 208
 			$this->error=$this->db->lasterror();
@@ -268,15 +265,13 @@  discard block
 block discarded – undo
268 265
 			{
269 266
 				$this->db->commit();
270 267
 				return 1;
271
-			}
272
-			else
268
+			} else
273 269
 			{
274 270
 				$this->db->rollback();
275 271
 				$this->error=$this->db->lasterror();
276 272
 				return -2;
277 273
 			}
278
-		}
279
-		else
274
+		} else
280 275
 		{
281 276
 			$this->db->rollback();
282 277
 			$this->error=$this->db->lasterror();
@@ -302,11 +297,12 @@  discard block
 block discarded – undo
302 297
 		if ($id)
303 298
 		{
304 299
 			$sql.= " WHERE rowid = '".$id."'";
305
-		}
306
-		else
300
+		} else
307 301
 		{
308 302
 			$sql.= " WHERE entity = " .$conf->entity;
309
-			if ($ref) $sql.= " AND label = '".$this->db->escape($ref)."'";
303
+			if ($ref) {
304
+				$sql.= " AND label = '".$this->db->escape($ref)."'";
305
+			}
310 306
 		}
311 307
 
312 308
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
@@ -336,13 +332,11 @@  discard block
 block discarded – undo
336 332
 				$this->country_code=$tmp['code'];
337 333
 
338 334
 				return 1;
339
-			}
340
-			else
335
+			} else
341 336
 			{
342 337
 				return 0;
343 338
 			}
344
-		}
345
-		else
339
+		} else
346 340
 		{
347 341
 			$this->error=$this->db->error();
348 342
 			return -1;
@@ -391,8 +385,7 @@  discard block
 block discarded – undo
391 385
 
392 386
 			$this->db->free($result);
393 387
 
394
-		}
395
-		else
388
+		} else
396 389
 		{
397 390
 	        dol_print_error($this->db);
398 391
 		}
@@ -452,8 +445,7 @@  discard block
 block discarded – undo
452 445
 			$obj = $this->db->fetch_object($result);
453 446
 			$ret['nb']=$obj->nb;
454 447
 			$this->db->free($result);
455
-		}
456
-		else
448
+		} else
457 449
 		{
458 450
 			$this->error=$this->db->lasterror();
459 451
 			return -1;
@@ -485,8 +477,7 @@  discard block
 block discarded – undo
485 477
 			$ret['nb']=$obj->nb;
486 478
 			$ret['value']=$obj->value;
487 479
 			$this->db->free($result);
488
-		}
489
-		else
480
+		} else
490 481
 		{
491 482
 			$this->error=$this->db->lasterror();
492 483
 			return -1;
@@ -533,22 +524,30 @@  discard block
 block discarded – undo
533 524
 		}
534 525
 		if ($mode == 2)
535 526
 		{
536
-			if ($statut > 0) $picto = 'statut4';
527
+			if ($statut > 0) {
528
+				$picto = 'statut4';
529
+			}
537 530
 			return img_picto($label, $picto).' '.$label;
538 531
 		}
539 532
 		if ($mode == 3)
540 533
 		{
541
-			if ($statut > 0) $picto = 'statut4';
534
+			if ($statut > 0) {
535
+				$picto = 'statut4';
536
+			}
542 537
 			return img_picto($label, $picto).' '.$label;
543 538
 		}
544 539
 		if ($mode == 4)
545 540
 		{
546
-			if ($statut > 0) $picto = 'statut4';
541
+			if ($statut > 0) {
542
+				$picto = 'statut4';
543
+			}
547 544
 			return img_picto($label, $picto).' '.$label;
548 545
 		}
549 546
 		if ($mode == 5)
550 547
 		{
551
-			if ($statut > 0) $picto = 'statut4';
548
+			if ($statut > 0) {
549
+				$picto = 'statut4';
550
+			}
552 551
 			return $label.' '.img_picto($label, $picto);
553 552
 		}
554 553
 	}
@@ -568,15 +567,19 @@  discard block
 block discarded – undo
568 567
 		global $conf, $langs;
569 568
 		$langs->load("stocks");
570 569
 
571
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
570
+        if (! empty($conf->dol_no_mouse_hover)) {
571
+        	$notooltip=1;
572
+        }
573
+        // Force disable tooltips
572 574
 
573 575
         $result='';
574 576
         $label = '';
575 577
 
576 578
         $label = '<u>' . $langs->trans("ShowWarehouse").'</u>';
577 579
         $label.= '<br><b>' . $langs->trans('Ref') . ':</b> ' . (empty($this->label)?$this->libelle:$this->label);
578
-        if (! empty($this->lieu))
579
-            $label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
580
+        if (! empty($this->lieu)) {
581
+                    $label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
582
+        }
580 583
 
581 584
         $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
582 585
 
@@ -596,7 +599,9 @@  discard block
 block discarded – undo
596 599
         $linkstart.=$linkclose.'>';
597 600
         $linkend='</a>';
598 601
 
599
-        if ($withpicto) $result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
602
+        if ($withpicto) {
603
+        	$result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
604
+        }
600 605
 		$result.=$linkstart.($showfullpath ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label)).$linkend;
601 606
 		return $result;
602 607
 	}
@@ -658,10 +663,12 @@  discard block
 block discarded – undo
658 663
                 	$warehousetmp->fetch($parentid);
659 664
                 	$TArbo[] = $warehousetmp->label;
660 665
                  	$parentid = $objarbo->fk_parent;
666
+                } else {
667
+                	break;
661 668
                 }
662
-                else break;
669
+            } else {
670
+            	dol_print_error($this->db);
663 671
             }
664
-            else dol_print_error($this->db);
665 672
 
666 673
             $i++;
667 674
         }
Please login to merge, or discard this patch.
htdocs/projet/class/task.class.php 4 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -650,16 +650,16 @@
 block discarded – undo
650 650
      * Return list of tasks for all projects or for one particular project
651 651
      * Sort order is on project, then on position of task, and last on start date of first level task
652 652
      *
653
-     * @param	User	$usert				Object user to limit tasks affected to a particular user
654
-     * @param	User	$userp				Object user to limit projects of a particular user and public projects
653
+     * @param	integer	$usert				Object user to limit tasks affected to a particular user
654
+     * @param	integer	$userp				Object user to limit projects of a particular user and public projects
655 655
      * @param	int		$projectid			Project id
656 656
      * @param	int		$socid				Third party id
657 657
      * @param	int		$mode				0=Return list of tasks and their projects, 1=Return projects and tasks if exists
658 658
      * @param	string	$filteronprojref	Filter on project ref
659
-     * @param	string	$filteronprojstatus	Filter on project status
659
+     * @param	integer	$filteronprojstatus	Filter on project status
660 660
      * @param	string	$morewherefilter	Add more filter into where SQL request (must start with ' AND ...')
661
-     * @param	string	$filteronprojuser	Filter on user that is a contact of project
662
-     * @param	string	$filterontaskuser	Filter on user assigned to task
661
+     * @param	integer	$filteronprojuser	Filter on user that is a contact of project
662
+     * @param	integer	$filterontaskuser	Filter on user assigned to task
663 663
      * @return 	array						Array of tasks
664 664
      */
665 665
     function getTasksArray($usert=0, $userp=0, $projectid=0, $socid=0, $mode=0, $filteronprojref='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0)
Please login to merge, or discard this patch.
Indentation   +1332 added lines, -1332 removed lines patch added patch discarded remove patch
@@ -31,25 +31,25 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class Task extends CommonObject
33 33
 {
34
-    public $element='project_task';		//!< Id that identify managed objects
35
-    public $table_element='projet_task';	//!< Name of table without prefix where object is stored
36
-    public $fk_element='fk_task';
37
-    public $picto = 'task';
38
-    protected $childtables=array('projet_task_time','projet_task_comment');    // To test if we can delete object
39
-
40
-    var $fk_task_parent;
41
-    var $label;
42
-    var $description;
43
-    var $duration_effective;		// total of time spent on this task
44
-    var $planned_workload;
45
-    var $date_c;
46
-    var $date_start;
47
-    var $date_end;
48
-    var $progress;
49
-    var $fk_statut;
50
-    var $priority;
51
-    var $fk_user_creat;
52
-    var $fk_user_valid;
34
+	public $element='project_task';		//!< Id that identify managed objects
35
+	public $table_element='projet_task';	//!< Name of table without prefix where object is stored
36
+	public $fk_element='fk_task';
37
+	public $picto = 'task';
38
+	protected $childtables=array('projet_task_time','projet_task_comment');    // To test if we can delete object
39
+
40
+	var $fk_task_parent;
41
+	var $label;
42
+	var $description;
43
+	var $duration_effective;		// total of time spent on this task
44
+	var $planned_workload;
45
+	var $date_c;
46
+	var $date_start;
47
+	var $date_end;
48
+	var $progress;
49
+	var $fk_statut;
50
+	var $priority;
51
+	var $fk_user_creat;
52
+	var $fk_user_valid;
53 53
 	var $rang;
54 54
 
55 55
 	var $timespent_min_date;
@@ -61,1294 +61,1294 @@  discard block
 block discarded – undo
61 61
 	// For detail of lines of timespent record, there is the property ->lines in common
62 62
 
63 63
 	// Var used to call method addTimeSpent(). Bad practice.
64
-    var $timespent_id;
65
-    var $timespent_duration;
66
-    var $timespent_old_duration;
67
-    var $timespent_date;
68
-    var $timespent_datehour;		// More accurate start date (same than timespent_date but includes hours, minutes and seconds)
69
-    var $timespent_withhour;		// 1 = we entered also start hours for timesheet line
70
-    var $timespent_fk_user;
71
-    var $timespent_note;
72
-
73
-    var $comments = array();
74
-
75
-    public $oldcopy;
76
-
77
-
78
-    /**
79
-     *  Constructor
80
-     *
81
-     *  @param      DoliDB		$db      Database handler
82
-     */
83
-    function __construct($db)
84
-    {
85
-        $this->db = $db;
86
-    }
87
-
88
-
89
-    /**
90
-     *  Create into database
91
-     *
92
-     *  @param	User	$user        	User that create
93
-     *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
94
-     *  @return int 		        	<0 if KO, Id of created object if OK
95
-     */
96
-    function create($user, $notrigger=0)
97
-    {
98
-        global $conf, $langs;
99
-
100
-        $error=0;
101
-
102
-        // Clean parameters
103
-        $this->label = trim($this->label);
104
-        $this->description = trim($this->description);
105
-
106
-        // Check parameters
107
-        // Put here code to add control on parameters values
108
-
109
-        // Insert request
110
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
111
-        $sql.= "fk_projet";
64
+	var $timespent_id;
65
+	var $timespent_duration;
66
+	var $timespent_old_duration;
67
+	var $timespent_date;
68
+	var $timespent_datehour;		// More accurate start date (same than timespent_date but includes hours, minutes and seconds)
69
+	var $timespent_withhour;		// 1 = we entered also start hours for timesheet line
70
+	var $timespent_fk_user;
71
+	var $timespent_note;
72
+
73
+	var $comments = array();
74
+
75
+	public $oldcopy;
76
+
77
+
78
+	/**
79
+	 *  Constructor
80
+	 *
81
+	 *  @param      DoliDB		$db      Database handler
82
+	 */
83
+	function __construct($db)
84
+	{
85
+		$this->db = $db;
86
+	}
87
+
88
+
89
+	/**
90
+	 *  Create into database
91
+	 *
92
+	 *  @param	User	$user        	User that create
93
+	 *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
94
+	 *  @return int 		        	<0 if KO, Id of created object if OK
95
+	 */
96
+	function create($user, $notrigger=0)
97
+	{
98
+		global $conf, $langs;
99
+
100
+		$error=0;
101
+
102
+		// Clean parameters
103
+		$this->label = trim($this->label);
104
+		$this->description = trim($this->description);
105
+
106
+		// Check parameters
107
+		// Put here code to add control on parameters values
108
+
109
+		// Insert request
110
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
111
+		$sql.= "fk_projet";
112 112
 		$sql.= ", ref";
113
-        $sql.= ", fk_task_parent";
114
-        $sql.= ", label";
115
-        $sql.= ", description";
116
-        $sql.= ", datec";
117
-        $sql.= ", fk_user_creat";
118
-        $sql.= ", dateo";
119
-        $sql.= ", datee";
120
-        $sql.= ", planned_workload";
121
-        $sql.= ", progress";
122
-        $sql.= ") VALUES (";
123
-        $sql.= $this->fk_project;
113
+		$sql.= ", fk_task_parent";
114
+		$sql.= ", label";
115
+		$sql.= ", description";
116
+		$sql.= ", datec";
117
+		$sql.= ", fk_user_creat";
118
+		$sql.= ", dateo";
119
+		$sql.= ", datee";
120
+		$sql.= ", planned_workload";
121
+		$sql.= ", progress";
122
+		$sql.= ") VALUES (";
123
+		$sql.= $this->fk_project;
124 124
 		$sql.= ", ".(!empty($this->ref)?"'".$this->db->escape($this->ref)."'":'null');
125
-        $sql.= ", ".$this->fk_task_parent;
126
-        $sql.= ", '".$this->db->escape($this->label)."'";
127
-        $sql.= ", '".$this->db->escape($this->description)."'";
128
-        $sql.= ", '".$this->db->idate($this->date_c)."'";
129
-        $sql.= ", ".$user->id;
130
-        $sql.= ", ".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null');
131
-        $sql.= ", ".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null');
132
-        $sql.= ", ".(($this->planned_workload!='' && $this->planned_workload >= 0)?$this->planned_workload:'null');
133
-        $sql.= ", ".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null');
134
-        $sql.= ")";
135
-
136
-        $this->db->begin();
137
-
138
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
139
-        $resql=$this->db->query($sql);
140
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
141
-
142
-        if (! $error)
143
-        {
144
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task");
145
-
146
-            if (! $notrigger)
147
-            {
148
-                // Call trigger
149
-                $result=$this->call_trigger('TASK_CREATE',$user);
150
-                if ($result < 0) { $error++; }
151
-                // End call triggers
152
-            }
153
-        }
154
-
155
-        // Update extrafield
156
-        if (! $error)
157
-        {
158
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
159
-        	{
160
-        		$result=$this->insertExtraFields();
161
-        		if ($result < 0)
162
-        		{
163
-        			$error++;
164
-        		}
165
-        	}
166
-        }
167
-
168
-        // Commit or rollback
169
-        if ($error)
170
-        {
171
-            foreach($this->errors as $errmsg)
172
-            {
173
-                dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
174
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
175
-            }
176
-            $this->db->rollback();
177
-            return -1*$error;
178
-        }
179
-        else
180
-        {
181
-            $this->db->commit();
182
-            return $this->id;
183
-        }
184
-    }
185
-
186
-
187
-    /**
188
-     *  Load object in memory from database
189
-     *
190
-     *  @param	int		$id			Id object
191
-     *  @param	int		$ref		ref object
192
-     *  @return int 		        <0 if KO, 0 if not found, >0 if OK
193
-     */
194
-    function fetch($id,$ref='')
195
-    {
196
-        global $langs;
197
-
198
-        $sql = "SELECT";
199
-        $sql.= " t.rowid,";
125
+		$sql.= ", ".$this->fk_task_parent;
126
+		$sql.= ", '".$this->db->escape($this->label)."'";
127
+		$sql.= ", '".$this->db->escape($this->description)."'";
128
+		$sql.= ", '".$this->db->idate($this->date_c)."'";
129
+		$sql.= ", ".$user->id;
130
+		$sql.= ", ".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null');
131
+		$sql.= ", ".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null');
132
+		$sql.= ", ".(($this->planned_workload!='' && $this->planned_workload >= 0)?$this->planned_workload:'null');
133
+		$sql.= ", ".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null');
134
+		$sql.= ")";
135
+
136
+		$this->db->begin();
137
+
138
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
139
+		$resql=$this->db->query($sql);
140
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
141
+
142
+		if (! $error)
143
+		{
144
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task");
145
+
146
+			if (! $notrigger)
147
+			{
148
+				// Call trigger
149
+				$result=$this->call_trigger('TASK_CREATE',$user);
150
+				if ($result < 0) { $error++; }
151
+				// End call triggers
152
+			}
153
+		}
154
+
155
+		// Update extrafield
156
+		if (! $error)
157
+		{
158
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
159
+			{
160
+				$result=$this->insertExtraFields();
161
+				if ($result < 0)
162
+				{
163
+					$error++;
164
+				}
165
+			}
166
+		}
167
+
168
+		// Commit or rollback
169
+		if ($error)
170
+		{
171
+			foreach($this->errors as $errmsg)
172
+			{
173
+				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
174
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
175
+			}
176
+			$this->db->rollback();
177
+			return -1*$error;
178
+		}
179
+		else
180
+		{
181
+			$this->db->commit();
182
+			return $this->id;
183
+		}
184
+	}
185
+
186
+
187
+	/**
188
+	 *  Load object in memory from database
189
+	 *
190
+	 *  @param	int		$id			Id object
191
+	 *  @param	int		$ref		ref object
192
+	 *  @return int 		        <0 if KO, 0 if not found, >0 if OK
193
+	 */
194
+	function fetch($id,$ref='')
195
+	{
196
+		global $langs;
197
+
198
+		$sql = "SELECT";
199
+		$sql.= " t.rowid,";
200 200
 		$sql.= " t.ref,";
201
-        $sql.= " t.fk_projet,";
202
-        $sql.= " t.fk_task_parent,";
203
-        $sql.= " t.label,";
204
-        $sql.= " t.description,";
205
-        $sql.= " t.duration_effective,";
206
-        $sql.= " t.planned_workload,";
207
-        $sql.= " t.datec,";
208
-        $sql.= " t.dateo,";
209
-        $sql.= " t.datee,";
210
-        $sql.= " t.fk_user_creat,";
211
-        $sql.= " t.fk_user_valid,";
212
-        $sql.= " t.fk_statut,";
213
-        $sql.= " t.progress,";
214
-        $sql.= " t.priority,";
215
-        $sql.= " t.note_private,";
201
+		$sql.= " t.fk_projet,";
202
+		$sql.= " t.fk_task_parent,";
203
+		$sql.= " t.label,";
204
+		$sql.= " t.description,";
205
+		$sql.= " t.duration_effective,";
206
+		$sql.= " t.planned_workload,";
207
+		$sql.= " t.datec,";
208
+		$sql.= " t.dateo,";
209
+		$sql.= " t.datee,";
210
+		$sql.= " t.fk_user_creat,";
211
+		$sql.= " t.fk_user_valid,";
212
+		$sql.= " t.fk_statut,";
213
+		$sql.= " t.progress,";
214
+		$sql.= " t.priority,";
215
+		$sql.= " t.note_private,";
216 216
 		$sql.= " t.note_public,";
217 217
 		$sql.= " t.rang";
218
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as t";
219
-        $sql.= " WHERE ";
220
-        if (!empty($ref)) {
221
-        	$sql.="t.ref = '".$this->db->escape($ref)."'";
222
-        }else {
223
-        	$sql.="t.rowid = ".$id;
224
-        }
225
-
226
-        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
227
-        $resql=$this->db->query($sql);
228
-        if ($resql)
229
-        {
230
-            $num_rows = $this->db->num_rows($resql);
231
-
232
-            if ($num_rows)
233
-            {
234
-                $obj = $this->db->fetch_object($resql);
235
-
236
-                $this->id					= $obj->rowid;
218
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task as t";
219
+		$sql.= " WHERE ";
220
+		if (!empty($ref)) {
221
+			$sql.="t.ref = '".$this->db->escape($ref)."'";
222
+		}else {
223
+			$sql.="t.rowid = ".$id;
224
+		}
225
+
226
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
227
+		$resql=$this->db->query($sql);
228
+		if ($resql)
229
+		{
230
+			$num_rows = $this->db->num_rows($resql);
231
+
232
+			if ($num_rows)
233
+			{
234
+				$obj = $this->db->fetch_object($resql);
235
+
236
+				$this->id					= $obj->rowid;
237 237
 				$this->ref					= $obj->ref;
238
-                $this->fk_project			= $obj->fk_projet;
239
-                $this->fk_task_parent		= $obj->fk_task_parent;
240
-                $this->label				= $obj->label;
241
-                $this->description			= $obj->description;
242
-                $this->duration_effective	= $obj->duration_effective;
243
-                $this->planned_workload		= $obj->planned_workload;
244
-                $this->date_c				= $this->db->jdate($obj->datec);
245
-                $this->date_start			= $this->db->jdate($obj->dateo);
246
-                $this->date_end				= $this->db->jdate($obj->datee);
247
-                $this->fk_user_creat		= $obj->fk_user_creat;
248
-                $this->fk_user_valid		= $obj->fk_user_valid;
249
-                $this->fk_statut			= $obj->fk_statut;
250
-                $this->progress				= $obj->progress;
251
-                $this->priority				= $obj->priority;
252
-                $this->note_private			= $obj->note_private;
253
-                $this->note_public			= $obj->note_public;
238
+				$this->fk_project			= $obj->fk_projet;
239
+				$this->fk_task_parent		= $obj->fk_task_parent;
240
+				$this->label				= $obj->label;
241
+				$this->description			= $obj->description;
242
+				$this->duration_effective	= $obj->duration_effective;
243
+				$this->planned_workload		= $obj->planned_workload;
244
+				$this->date_c				= $this->db->jdate($obj->datec);
245
+				$this->date_start			= $this->db->jdate($obj->dateo);
246
+				$this->date_end				= $this->db->jdate($obj->datee);
247
+				$this->fk_user_creat		= $obj->fk_user_creat;
248
+				$this->fk_user_valid		= $obj->fk_user_valid;
249
+				$this->fk_statut			= $obj->fk_statut;
250
+				$this->progress				= $obj->progress;
251
+				$this->priority				= $obj->priority;
252
+				$this->note_private			= $obj->note_private;
253
+				$this->note_public			= $obj->note_public;
254 254
 				$this->rang					= $obj->rang;
255 255
 
256
-                // Retreive all extrafield for thirdparty
257
-               	$this->fetch_optionals();
258
-            }
259
-
260
-            $this->db->free($resql);
261
-
262
-            if ($num_rows) {
263
-            	$this->fetchComments();
264
-            	return 1;
265
-            }else {
266
-            	return 0;
267
-            }
268
-        }
269
-        else
270
-        {
271
-            $this->error="Error ".$this->db->lasterror();
272
-            return -1;
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     *  Update database
279
-     *
280
-     *  @param	User	$user        	User that modify
281
-     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
282
-     *  @return int			         	<=0 if KO, >0 if OK
283
-     */
284
-    function update($user=null, $notrigger=0)
285
-    {
286
-        global $conf, $langs;
287
-        $error=0;
288
-
289
-        // Clean parameters
290
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
291
-		if (isset($this->ref)) $this->ref=trim($this->ref);
292
-        if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent);
293
-        if (isset($this->label)) $this->label=trim($this->label);
294
-        if (isset($this->description)) $this->description=trim($this->description);
295
-        if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective);
296
-        if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload);
297
-
298
-        // Check parameters
299
-        // Put here code to add control on parameters values
300
-
301
-        // Update request
302
-        $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
303
-        $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
304
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"'".$this->db->escape($this->id)."'").",";
305
-        $sql.= " fk_task_parent=".(isset($this->fk_task_parent)?$this->fk_task_parent:"null").",";
306
-        $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
307
-        $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
308
-        $sql.= " duration_effective=".(isset($this->duration_effective)?$this->duration_effective:"null").",";
309
-        $sql.= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '')?$this->planned_workload:"null").",";
310
-        $sql.= " dateo=".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null').",";
311
-        $sql.= " datee=".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null').",";
312
-        $sql.= " progress=".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null').",";
313
-        $sql.= " rang=".((!empty($this->rang))?$this->rang:"0");
314
-        $sql.= " WHERE rowid=".$this->id;
315
-
316
-        $this->db->begin();
317
-
318
-        dol_syslog(get_class($this)."::update", LOG_DEBUG);
319
-        $resql = $this->db->query($sql);
320
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
321
-
322
-        if (! $error)
323
-        {
324
-            if (! $notrigger)
325
-            {
326
-                // Call trigger
327
-                $result=$this->call_trigger('TASK_MODIFY',$user);
328
-                if ($result < 0) { $error++; }
329
-                // End call triggers
330
-            }
331
-        }
332
-
333
-        //Update extrafield
334
-        if (!$error) {
335
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
336
-        	{
337
-        		$result=$this->insertExtraFields();
338
-        		if ($result < 0)
339
-        		{
340
-        			$error++;
341
-        		}
342
-        	}
343
-        }
344
-
345
-        if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref))
346
-        {
347
-            // We remove directory
348
-            if ($conf->projet->dir_output)
349
-            {
350
-                $project = new Project($this->db);
351
-                $project->fetch($this->fk_project);
352
-
353
-                $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref);
354
-                $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref);
355
-                if (file_exists($olddir))
356
-                {
357
-                    include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
358
-                    $res=dol_move($olddir, $newdir);
359
-                    if (! $res)
360
-                    {
361
-                        $langs->load("errors");
362
-                        $this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir);
363
-                        $error++;
364
-                    }
365
-                }
366
-            }
367
-        }
368
-
369
-        // Commit or rollback
370
-        if ($error)
371
-        {
372
-            foreach($this->errors as $errmsg)
373
-            {
374
-                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
375
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
376
-            }
377
-            $this->db->rollback();
378
-            return -1*$error;
379
-        }
380
-        else
381
-        {
382
-            $this->db->commit();
383
-            return 1;
384
-        }
385
-    }
386
-
387
-
388
-    /**
389
-     *	Delete task from database
390
-     *
391
-     *	@param	User	$user        	User that delete
392
-     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
393
-     *	@return	int						<0 if KO, >0 if OK
394
-     */
395
-    function delete($user, $notrigger=0)
396
-    {
397
-
398
-        global $conf, $langs;
399
-        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
400
-
401
-        $error=0;
402
-
403
-        $this->db->begin();
404
-
405
-        if ($this->hasChildren() > 0)
406
-        {
407
-            dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING);
408
-            $this->error='ErrorRecordHasSubTasks';
409
-            $this->db->rollback();
410
-            return 0;
411
-        }
412
-
413
-        $objectisused = $this->isObjectUsed($this->id);
414
-        if (! empty($objectisused))
415
-        {
416
-            dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING);
417
-            $this->error='ErrorRecordHasChildren';
418
-            $this->db->rollback();
419
-            return 0;
420
-        }
421
-
422
-        if (! $error)
423
-        {
424
-            // Delete linked contacts
425
-            $res = $this->delete_linked_contact();
426
-            if ($res < 0)
427
-            {
428
-                $this->error='ErrorFailToDeleteLinkedContact';
429
-                //$error++;
430
-                $this->db->rollback();
431
-                return 0;
432
-            }
433
-        }
434
-
435
-        if (! $error)
436
-        {
437
-	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
438
-	        $sql.= " WHERE fk_task=".$this->id;
439
-
440
-	        $resql = $this->db->query($sql);
441
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
442
-        }
443
-
444
-        if (! $error)
445
-        {
446
-	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields";
447
-	        $sql.= " WHERE fk_object=".$this->id;
448
-
449
-	        $resql = $this->db->query($sql);
450
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
451
-        }
452
-
453
-        if (! $error)
454
-        {
455
-	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task";
456
-	        $sql.= " WHERE rowid=".$this->id;
457
-
458
-	        $resql = $this->db->query($sql);
459
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
460
-        }
461
-
462
-        if (! $error)
463
-        {
464
-            if (! $notrigger)
465
-            {
466
-                // Call trigger
467
-                $result=$this->call_trigger('TASK_DELETE',$user);
468
-                if ($result < 0) { $error++; }
469
-                // End call triggers
470
-            }
471
-        }
472
-
473
-        // Commit or rollback
474
-        if ($error)
475
-        {
476
-            foreach($this->errors as $errmsg)
477
-            {
478
-                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
479
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
480
-            }
481
-            $this->db->rollback();
482
-            return -1*$error;
483
-        }
484
-        else
256
+				// Retreive all extrafield for thirdparty
257
+			   	$this->fetch_optionals();
258
+			}
259
+
260
+			$this->db->free($resql);
261
+
262
+			if ($num_rows) {
263
+				$this->fetchComments();
264
+				return 1;
265
+			}else {
266
+				return 0;
267
+			}
268
+		}
269
+		else
270
+		{
271
+			$this->error="Error ".$this->db->lasterror();
272
+			return -1;
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 *  Update database
279
+	 *
280
+	 *  @param	User	$user        	User that modify
281
+	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
282
+	 *  @return int			         	<=0 if KO, >0 if OK
283
+	 */
284
+	function update($user=null, $notrigger=0)
285
+	{
286
+		global $conf, $langs;
287
+		$error=0;
288
+
289
+		// Clean parameters
290
+		if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
291
+		if (isset($this->ref)) $this->ref=trim($this->ref);
292
+		if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent);
293
+		if (isset($this->label)) $this->label=trim($this->label);
294
+		if (isset($this->description)) $this->description=trim($this->description);
295
+		if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective);
296
+		if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload);
297
+
298
+		// Check parameters
299
+		// Put here code to add control on parameters values
300
+
301
+		// Update request
302
+		$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
303
+		$sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
304
+		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"'".$this->db->escape($this->id)."'").",";
305
+		$sql.= " fk_task_parent=".(isset($this->fk_task_parent)?$this->fk_task_parent:"null").",";
306
+		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
307
+		$sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
308
+		$sql.= " duration_effective=".(isset($this->duration_effective)?$this->duration_effective:"null").",";
309
+		$sql.= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '')?$this->planned_workload:"null").",";
310
+		$sql.= " dateo=".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null').",";
311
+		$sql.= " datee=".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null').",";
312
+		$sql.= " progress=".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null').",";
313
+		$sql.= " rang=".((!empty($this->rang))?$this->rang:"0");
314
+		$sql.= " WHERE rowid=".$this->id;
315
+
316
+		$this->db->begin();
317
+
318
+		dol_syslog(get_class($this)."::update", LOG_DEBUG);
319
+		$resql = $this->db->query($sql);
320
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
321
+
322
+		if (! $error)
323
+		{
324
+			if (! $notrigger)
325
+			{
326
+				// Call trigger
327
+				$result=$this->call_trigger('TASK_MODIFY',$user);
328
+				if ($result < 0) { $error++; }
329
+				// End call triggers
330
+			}
331
+		}
332
+
333
+		//Update extrafield
334
+		if (!$error) {
335
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
336
+			{
337
+				$result=$this->insertExtraFields();
338
+				if ($result < 0)
339
+				{
340
+					$error++;
341
+				}
342
+			}
343
+		}
344
+
345
+		if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref))
346
+		{
347
+			// We remove directory
348
+			if ($conf->projet->dir_output)
349
+			{
350
+				$project = new Project($this->db);
351
+				$project->fetch($this->fk_project);
352
+
353
+				$olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref);
354
+				$newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref);
355
+				if (file_exists($olddir))
356
+				{
357
+					include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
358
+					$res=dol_move($olddir, $newdir);
359
+					if (! $res)
360
+					{
361
+						$langs->load("errors");
362
+						$this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir);
363
+						$error++;
364
+					}
365
+				}
366
+			}
367
+		}
368
+
369
+		// Commit or rollback
370
+		if ($error)
371
+		{
372
+			foreach($this->errors as $errmsg)
373
+			{
374
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
375
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
376
+			}
377
+			$this->db->rollback();
378
+			return -1*$error;
379
+		}
380
+		else
381
+		{
382
+			$this->db->commit();
383
+			return 1;
384
+		}
385
+	}
386
+
387
+
388
+	/**
389
+	 *	Delete task from database
390
+	 *
391
+	 *	@param	User	$user        	User that delete
392
+	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
393
+	 *	@return	int						<0 if KO, >0 if OK
394
+	 */
395
+	function delete($user, $notrigger=0)
396
+	{
397
+
398
+		global $conf, $langs;
399
+		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
400
+
401
+		$error=0;
402
+
403
+		$this->db->begin();
404
+
405
+		if ($this->hasChildren() > 0)
406
+		{
407
+			dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING);
408
+			$this->error='ErrorRecordHasSubTasks';
409
+			$this->db->rollback();
410
+			return 0;
411
+		}
412
+
413
+		$objectisused = $this->isObjectUsed($this->id);
414
+		if (! empty($objectisused))
415
+		{
416
+			dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING);
417
+			$this->error='ErrorRecordHasChildren';
418
+			$this->db->rollback();
419
+			return 0;
420
+		}
421
+
422
+		if (! $error)
423
+		{
424
+			// Delete linked contacts
425
+			$res = $this->delete_linked_contact();
426
+			if ($res < 0)
427
+			{
428
+				$this->error='ErrorFailToDeleteLinkedContact';
429
+				//$error++;
430
+				$this->db->rollback();
431
+				return 0;
432
+			}
433
+		}
434
+
435
+		if (! $error)
436
+		{
437
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
438
+			$sql.= " WHERE fk_task=".$this->id;
439
+
440
+			$resql = $this->db->query($sql);
441
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
442
+		}
443
+
444
+		if (! $error)
445
+		{
446
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields";
447
+			$sql.= " WHERE fk_object=".$this->id;
448
+
449
+			$resql = $this->db->query($sql);
450
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
451
+		}
452
+
453
+		if (! $error)
454
+		{
455
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task";
456
+			$sql.= " WHERE rowid=".$this->id;
457
+
458
+			$resql = $this->db->query($sql);
459
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
460
+		}
461
+
462
+		if (! $error)
463
+		{
464
+			if (! $notrigger)
465
+			{
466
+				// Call trigger
467
+				$result=$this->call_trigger('TASK_DELETE',$user);
468
+				if ($result < 0) { $error++; }
469
+				// End call triggers
470
+			}
471
+		}
472
+
473
+		// Commit or rollback
474
+		if ($error)
475
+		{
476
+			foreach($this->errors as $errmsg)
477
+			{
478
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
479
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
480
+			}
481
+			$this->db->rollback();
482
+			return -1*$error;
483
+		}
484
+		else
485
+		{
486
+			//Delete associated link file
487
+			if ($conf->projet->dir_output)
488
+			{
489
+				$projectstatic=new Project($this->db);
490
+				$projectstatic->fetch($this->fk_project);
491
+
492
+				$dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($projectstatic->ref) . '/' . dol_sanitizeFileName($this->id);
493
+				dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG);
494
+				if (file_exists($dir))
495
+				{
496
+					require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
497
+					$res = @dol_delete_dir_recursive($dir);
498
+					if (!$res)
499
+					{
500
+						$this->error = 'ErrorFailToDeleteDir';
501
+						$this->db->rollback();
502
+						return 0;
503
+					}
504
+				}
505
+			}
506
+
507
+			$this->db->commit();
508
+
509
+			return 1;
510
+		}
511
+	}
512
+
513
+	/**
514
+	 *	Return nb of children
515
+	 *
516
+	 *	@return	int		<0 if KO, 0 if no children, >0 if OK
517
+	 */
518
+	function hasChildren()
519
+	{
520
+		$error=0;
521
+		$ret=0;
522
+
523
+		$sql = "SELECT COUNT(*) as nb";
524
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task";
525
+		$sql.= " WHERE fk_task_parent=".$this->id;
526
+
527
+		dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
528
+		$resql = $this->db->query($sql);
529
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
530
+		else
531
+		{
532
+			$obj=$this->db->fetch_object($resql);
533
+			if ($obj) $ret=$obj->nb;
534
+			$this->db->free($resql);
535
+		}
536
+
537
+		if (! $error)
538
+		{
539
+			return $ret;
540
+		}
541
+		else
542
+		{
543
+			return -1;
544
+		}
545
+	}
546
+
547
+	/**
548
+	 *	Return nb of time spent
549
+	 *
550
+	 *	@return	int		<0 if KO, 0 if no children, >0 if OK
551
+	 */
552
+	function hasTimeSpent()
553
+	{
554
+		$error=0;
555
+		$ret=0;
556
+
557
+		$sql = "SELECT COUNT(*) as nb";
558
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time";
559
+		$sql.= " WHERE fk_task=".$this->id;
560
+
561
+		dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
562
+		$resql = $this->db->query($sql);
563
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
564
+		else
565
+		{
566
+			$obj=$this->db->fetch_object($resql);
567
+			if ($obj) $ret=$obj->nb;
568
+			$this->db->free($resql);
569
+		}
570
+
571
+		if (! $error)
572
+		{
573
+			return $ret;
574
+		}
575
+		else
576
+		{
577
+			return -1;
578
+		}
579
+	}
580
+
581
+
582
+	/**
583
+	 *	Return clicable name (with picto eventually)
584
+	 *
585
+	 *	@param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
586
+	 *	@param	string	$option			'withproject' or ''
587
+	 *  @param	string	$mode			Mode 'task', 'time', 'contact', 'note', document' define page to link to.
588
+	 * 	@param	int		$addlabel		0=Default, 1=Add label into string, >1=Add first chars into string
589
+	 *  @param	string	$sep			Separator between ref and label if option addlabel is set
590
+	 *  @param	int   	$notooltip		1=Disable tooltip
591
+	 *  @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
592
+	 *	@return	string					Chaine avec URL
593
+	 */
594
+	function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1)
595
+	{
596
+		global $conf, $langs, $user;
597
+
598
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
599
+
600
+		$result='';
601
+		$label = '<u>' . $langs->trans("ShowTask") . '</u>';
602
+		if (! empty($this->ref))
603
+			$label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
604
+		if (! empty($this->label))
605
+			$label .= '<br><b>' . $langs->trans('LabelTask') . ':</b> ' . $this->label;
606
+		if ($this->date_start || $this->date_end)
607
+		{
608
+			$label .= "<br>".get_date_range($this->date_start,$this->date_end,'',$langs,0);
609
+		}
610
+
611
+		$url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':'');
612
+		// Add param to save lastsearch_values or not
613
+		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
614
+		if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
615
+		if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
616
+
617
+		$linkclose = '';
618
+		if (empty($notooltip))
619
+		{
620
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
621
+			{
622
+				$label=$langs->trans("ShowTask");
623
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
624
+			}
625
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
626
+			$linkclose.=' class="classfortooltip"';
627
+		}
628
+
629
+		$linkstart = '<a href="'.$url.'"';
630
+		$linkstart.=$linkclose.'>';
631
+		$linkend='</a>';
632
+
633
+		$picto='projecttask';
634
+
635
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
636
+		if ($withpicto && $withpicto != 2) $result.=' ';
637
+		if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
638
+		return $result;
639
+	}
640
+
641
+	/**
642
+	 *  Initialise an instance with random values.
643
+	 *  Used to build previews or test instances.
644
+	 *	id must be 0 if object instance is a specimen.
645
+	 *
646
+	 *  @return	void
647
+	 */
648
+	function initAsSpecimen()
649
+	{
650
+		$this->id=0;
651
+
652
+		$this->fk_projet='';
653
+		$this->ref='TK01';
654
+		$this->fk_task_parent='';
655
+		$this->label='Specimen task TK01';
656
+		$this->duration_effective='';
657
+		$this->fk_user_creat='';
658
+		$this->progress='25';
659
+		$this->fk_statut='';
660
+		$this->note='This is a specimen task not';
661
+	}
662
+
663
+	/**
664
+	 * Return list of tasks for all projects or for one particular project
665
+	 * Sort order is on project, then on position of task, and last on start date of first level task
666
+	 *
667
+	 * @param	User	$usert				Object user to limit tasks affected to a particular user
668
+	 * @param	User	$userp				Object user to limit projects of a particular user and public projects
669
+	 * @param	int		$projectid			Project id
670
+	 * @param	int		$socid				Third party id
671
+	 * @param	int		$mode				0=Return list of tasks and their projects, 1=Return projects and tasks if exists
672
+	 * @param	string	$filteronprojref	Filter on project ref
673
+	 * @param	string	$filteronprojstatus	Filter on project status
674
+	 * @param	string	$morewherefilter	Add more filter into where SQL request (must start with ' AND ...')
675
+	 * @param	string	$filteronprojuser	Filter on user that is a contact of project
676
+	 * @param	string	$filterontaskuser	Filter on user assigned to task
677
+	 * @return 	array						Array of tasks
678
+	 */
679
+	function getTasksArray($usert=0, $userp=0, $projectid=0, $socid=0, $mode=0, $filteronprojref='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0)
680
+	{
681
+		global $conf;
682
+
683
+		$tasks = array();
684
+
685
+		//print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'<br>';
686
+
687
+		// List of tasks (does not care about permissions. Filtering will be done later)
688
+		$sql = "SELECT p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,";
689
+		$sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
690
+		$sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,";
691
+		$sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name";
692
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
693
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
694
+		if ($mode == 0)
695
+		{
696
+			if ($filteronprojuser > 0)
697
+			{
698
+				$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
699
+				$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
700
+			}
701
+			$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
702
+			if ($filterontaskuser > 0)
703
+			{
704
+				$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
705
+				$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
706
+			}
707
+			$sql.= " WHERE p.entity IN (".getEntity('project').")";
708
+			$sql.= " AND t.fk_projet = p.rowid";
709
+		}
710
+		elseif ($mode == 1)
711
+		{
712
+			if ($filteronprojuser > 0)
713
+			{
714
+				$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
715
+				$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
716
+			}
717
+			if ($filterontaskuser > 0)
718
+			{
719
+				$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
720
+				$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
721
+				$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
722
+			}
723
+			else
724
+			{
725
+				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
726
+			}
727
+			$sql.= " WHERE p.entity IN (".getEntity('project').")";
728
+		}
729
+		else return 'BadValueForParameterMode';
730
+
731
+		if ($filteronprojuser > 0)
732
+		{
733
+			$sql.= " AND p.rowid = ec.element_id";
734
+			$sql.= " AND ctc.rowid = ec.fk_c_type_contact";
735
+			$sql.= " AND ctc.element = 'project'";
736
+			$sql.= " AND ec.fk_socpeople = ".$filteronprojuser;
737
+			$sql.= " AND ec.statut = 4";
738
+			$sql.= " AND ctc.source = 'internal'";
739
+		}
740
+		if ($filterontaskuser > 0)
741
+		{
742
+			$sql.= " AND t.fk_projet = p.rowid";
743
+			$sql.= " AND p.rowid = ec2.element_id";
744
+			$sql.= " AND ctc2.rowid = ec2.fk_c_type_contact";
745
+			$sql.= " AND ctc2.element = 'project_task'";
746
+			$sql.= " AND ec2.fk_socpeople = ".$filterontaskuser;
747
+			$sql.= " AND ec2.statut = 4";
748
+			$sql.= " AND ctc2.source = 'internal'";
749
+		}
750
+		if ($socid)	$sql.= " AND p.fk_soc = ".$socid;
751
+		if ($projectid) $sql.= " AND p.rowid in (".$projectid.")";
752
+		if ($filteronprojref) $sql.= " AND p.ref LIKE '%".$filteronprojref."%'";
753
+		if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus;
754
+		if ($morewherefilter) $sql.=$morewherefilter;
755
+		$sql.= " ORDER BY p.ref, t.rang, t.dateo";
756
+
757
+		//print $sql;exit;
758
+		dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG);
759
+		$resql = $this->db->query($sql);
760
+		if ($resql)
761
+		{
762
+			$num = $this->db->num_rows($resql);
763
+			$i = 0;
764
+			// Loop on each record found, so each couple (project id, task id)
765
+			while ($i < $num)
766
+			{
767
+				$error=0;
768
+
769
+				$obj = $this->db->fetch_object($resql);
770
+
771
+				if ((! $obj->public) && (is_object($userp)))	// If not public project and we ask a filter on project owned by a user
772
+				{
773
+					if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
774
+					{
775
+						$error++;
776
+					}
777
+				}
778
+				if (is_object($usert))							// If we ask a filter on a user affected to a task
779
+				{
780
+					if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
781
+					{
782
+						$error++;
783
+					}
784
+				}
785
+
786
+				if (! $error)
787
+				{
788
+					$tasks[$i] = new Task($this->db);
789
+					$tasks[$i]->id				= $obj->taskid;
790
+					$tasks[$i]->ref				= $obj->taskref;
791
+					$tasks[$i]->fk_project		= $obj->projectid;
792
+					$tasks[$i]->projectref		= $obj->ref;
793
+					$tasks[$i]->projectlabel	= $obj->plabel;
794
+					$tasks[$i]->projectstatus	= $obj->projectstatus;
795
+					$tasks[$i]->label			= $obj->label;
796
+					$tasks[$i]->description		= $obj->description;
797
+					$tasks[$i]->fk_parent		= $obj->fk_task_parent;      // deprecated
798
+					$tasks[$i]->fk_task_parent	= $obj->fk_task_parent;
799
+					$tasks[$i]->duration		= $obj->duration_effective;
800
+					$tasks[$i]->planned_workload= $obj->planned_workload;
801
+					$tasks[$i]->progress		= $obj->progress;
802
+					$tasks[$i]->fk_statut		= $obj->status;
803
+					$tasks[$i]->public			= $obj->public;
804
+					$tasks[$i]->date_start		= $this->db->jdate($obj->date_start);
805
+					$tasks[$i]->date_end		= $this->db->jdate($obj->date_end);
806
+					$tasks[$i]->rang	   		= $obj->rang;
807
+
808
+					$tasks[$i]->thirdparty_id	= $obj->thirdparty_id;
809
+					$tasks[$i]->thirdparty_name	= $obj->thirdparty_name;
810
+				}
811
+
812
+				$i++;
813
+			}
814
+			$this->db->free($resql);
815
+		}
816
+		else
817
+		{
818
+			dol_print_error($this->db);
819
+		}
820
+
821
+		return $tasks;
822
+	}
823
+
824
+	/**
825
+	 * Return list of roles for a user for each projects or each tasks (or a particular project or a particular task).
826
+	 *
827
+	 * @param	User	$userp			      Return roles on project for this internal user. If set, usert and taskid must not be defined.
828
+	 * @param	User	$usert			      Return roles on task for this internal user. If set userp must NOT be defined. -1 means no filter.
829
+	 * @param 	int		$projectid		      Project id list separated with , to filter on project
830
+	 * @param 	int		$taskid			      Task id to filter on a task
831
+	 * @param	integer	$filteronprojstatus	  Filter on project status if userp is set. Not used if userp not defined.
832
+	 * @return 	array					      Array (projectid => 'list of roles for project' or taskid => 'list of roles for task')
833
+	 */
834
+	function getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1)
835
+	{
836
+		$arrayroles = array();
837
+
838
+		dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid);
839
+
840
+		// We want role of user for a projet or role of user for a task. Both are not possible.
841
+		if (empty($userp) && empty($usert))
485 842
 		{
486
-			//Delete associated link file
487
-	        if ($conf->projet->dir_output)
488
-	        {
489
-	        	$projectstatic=new Project($this->db);
490
-	        	$projectstatic->fetch($this->fk_project);
491
-
492
-	            $dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($projectstatic->ref) . '/' . dol_sanitizeFileName($this->id);
493
-	            dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG);
494
-	            if (file_exists($dir))
495
-	            {
496
-	            	require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
497
-	                $res = @dol_delete_dir_recursive($dir);
498
-	                if (!$res)
499
-	                {
500
-	                    $this->error = 'ErrorFailToDeleteDir';
501
-	                    $this->db->rollback();
502
-	                    return 0;
503
-	                }
504
-	            }
505
-	        }
506
-
507
-            $this->db->commit();
508
-
509
-	        return 1;
510
-        }
511
-    }
512
-
513
-    /**
514
-     *	Return nb of children
515
-     *
516
-     *	@return	int		<0 if KO, 0 if no children, >0 if OK
517
-     */
518
-    function hasChildren()
519
-    {
520
-    	$error=0;
521
-        $ret=0;
522
-
523
-        $sql = "SELECT COUNT(*) as nb";
524
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task";
525
-        $sql.= " WHERE fk_task_parent=".$this->id;
526
-
527
-        dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
528
-        $resql = $this->db->query($sql);
529
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
530
-        else
531
-        {
532
-            $obj=$this->db->fetch_object($resql);
533
-            if ($obj) $ret=$obj->nb;
534
-            $this->db->free($resql);
535
-        }
536
-
537
-        if (! $error)
538
-        {
539
-            return $ret;
540
-        }
541
-        else
542
-        {
543
-            return -1;
544
-        }
545
-    }
843
+			$this->error="CallWithWrongParameters";
844
+			return -1;
845
+		}
846
+		if (! empty($userp) && ! empty($usert))
847
+		{
848
+			$this->error="CallWithWrongParameters";
849
+			return -1;
850
+		}
851
+
852
+		/* Liste des taches et role sur les projets ou taches */
853
+		$sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source";
854
+		if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt";
855
+		if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
856
+		if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
857
+		$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
858
+		$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
859
+		$sql.= " WHERE pt.rowid = ec.element_id";
860
+		if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus;
861
+		if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
862
+		if ($userp) $sql.= " AND ctc.element = 'project'";
863
+		if ($usert) $sql.= " AND ctc.element = 'project_task'";
864
+		$sql.= " AND ctc.rowid = ec.fk_c_type_contact";
865
+		if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id;
866
+		if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id;
867
+		$sql.= " AND ec.statut = 4";
868
+		$sql.= " AND ctc.source = 'internal'";
869
+		if ($projectid)
870
+		{
871
+			if ($userp) $sql.= " AND pt.rowid in (".$projectid.")";
872
+			if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")";
873
+		}
874
+		if ($taskid)
875
+		{
876
+			if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS";
877
+			if ($usert) $sql.= " AND pt.rowid = ".$taskid;
878
+		}
879
+		//print $sql;
880
+
881
+		dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG);
882
+		$resql = $this->db->query($sql);
883
+		if ($resql)
884
+		{
885
+			$num = $this->db->num_rows($resql);
886
+			$i = 0;
887
+			while ($i < $num)
888
+			{
889
+				$obj = $this->db->fetch_object($resql);
890
+				if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code;
891
+				else $arrayroles[$obj->pid].=','.$obj->code;
892
+				$i++;
893
+			}
894
+			$this->db->free($resql);
895
+		}
896
+		else
897
+		{
898
+			dol_print_error($this->db);
899
+		}
900
+
901
+		return $arrayroles;
902
+	}
903
+
546 904
 
547 905
 	/**
548
-     *	Return nb of time spent
549
-     *
550
-     *	@return	int		<0 if KO, 0 if no children, >0 if OK
551
-     */
552
-    function hasTimeSpent()
553
-    {
554
-    	$error=0;
555
-        $ret=0;
556
-
557
-        $sql = "SELECT COUNT(*) as nb";
558
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time";
559
-        $sql.= " WHERE fk_task=".$this->id;
560
-
561
-        dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
562
-        $resql = $this->db->query($sql);
563
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
564
-        else
565
-        {
566
-            $obj=$this->db->fetch_object($resql);
567
-            if ($obj) $ret=$obj->nb;
568
-            $this->db->free($resql);
569
-        }
570
-
571
-        if (! $error)
572
-        {
573
-            return $ret;
574
-        }
575
-        else
576
-        {
577
-            return -1;
578
-        }
579
-    }
580
-
581
-
582
-    /**
583
-     *	Return clicable name (with picto eventually)
584
-     *
585
-     *	@param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
586
-     *	@param	string	$option			'withproject' or ''
587
-     *  @param	string	$mode			Mode 'task', 'time', 'contact', 'note', document' define page to link to.
588
-     * 	@param	int		$addlabel		0=Default, 1=Add label into string, >1=Add first chars into string
589
-     *  @param	string	$sep			Separator between ref and label if option addlabel is set
590
-     *  @param	int   	$notooltip		1=Disable tooltip
591
-     *  @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
592
-     *	@return	string					Chaine avec URL
593
-     */
594
-    function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1)
595
-    {
596
-        global $conf, $langs, $user;
597
-
598
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
599
-
600
-        $result='';
601
-        $label = '<u>' . $langs->trans("ShowTask") . '</u>';
602
-        if (! empty($this->ref))
603
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
604
-        if (! empty($this->label))
605
-            $label .= '<br><b>' . $langs->trans('LabelTask') . ':</b> ' . $this->label;
606
-        if ($this->date_start || $this->date_end)
607
-        {
608
-        	$label .= "<br>".get_date_range($this->date_start,$this->date_end,'',$langs,0);
609
-        }
610
-
611
-        $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':'');
612
-        // Add param to save lastsearch_values or not
613
-        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
614
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
615
-        if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
616
-
617
-        $linkclose = '';
618
-        if (empty($notooltip))
619
-        {
620
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
621
-            {
622
-                $label=$langs->trans("ShowTask");
623
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
624
-            }
625
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
626
-            $linkclose.=' class="classfortooltip"';
627
-        }
628
-
629
-        $linkstart = '<a href="'.$url.'"';
630
-        $linkstart.=$linkclose.'>';
631
-        $linkend='</a>';
632
-
633
-        $picto='projecttask';
634
-
635
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
636
-        if ($withpicto && $withpicto != 2) $result.=' ';
637
-        if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
638
-        return $result;
639
-    }
640
-
641
-    /**
642
-     *  Initialise an instance with random values.
643
-     *  Used to build previews or test instances.
644
-     *	id must be 0 if object instance is a specimen.
645
-     *
646
-     *  @return	void
647
-     */
648
-    function initAsSpecimen()
649
-    {
650
-        $this->id=0;
651
-
652
-        $this->fk_projet='';
653
-		$this->ref='TK01';
654
-        $this->fk_task_parent='';
655
-        $this->label='Specimen task TK01';
656
-        $this->duration_effective='';
657
-        $this->fk_user_creat='';
658
-        $this->progress='25';
659
-        $this->fk_statut='';
660
-        $this->note='This is a specimen task not';
661
-    }
662
-
663
-    /**
664
-     * Return list of tasks for all projects or for one particular project
665
-     * Sort order is on project, then on position of task, and last on start date of first level task
666
-     *
667
-     * @param	User	$usert				Object user to limit tasks affected to a particular user
668
-     * @param	User	$userp				Object user to limit projects of a particular user and public projects
669
-     * @param	int		$projectid			Project id
670
-     * @param	int		$socid				Third party id
671
-     * @param	int		$mode				0=Return list of tasks and their projects, 1=Return projects and tasks if exists
672
-     * @param	string	$filteronprojref	Filter on project ref
673
-     * @param	string	$filteronprojstatus	Filter on project status
674
-     * @param	string	$morewherefilter	Add more filter into where SQL request (must start with ' AND ...')
675
-     * @param	string	$filteronprojuser	Filter on user that is a contact of project
676
-     * @param	string	$filterontaskuser	Filter on user assigned to task
677
-     * @return 	array						Array of tasks
678
-     */
679
-    function getTasksArray($usert=0, $userp=0, $projectid=0, $socid=0, $mode=0, $filteronprojref='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0)
680
-    {
681
-        global $conf;
682
-
683
-        $tasks = array();
684
-
685
-        //print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'<br>';
686
-
687
-        // List of tasks (does not care about permissions. Filtering will be done later)
688
-        $sql = "SELECT p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,";
689
-        $sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
690
-        $sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,";
691
-        $sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name";
692
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
693
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
694
-        if ($mode == 0)
695
-        {
696
-            if ($filteronprojuser > 0)
697
-            {
698
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
699
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
700
-            }
701
-            $sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
702
-            if ($filterontaskuser > 0)
703
-            {
704
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
705
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
706
-            }
707
-            $sql.= " WHERE p.entity IN (".getEntity('project').")";
708
-            $sql.= " AND t.fk_projet = p.rowid";
709
-        }
710
-        elseif ($mode == 1)
711
-        {
712
-            if ($filteronprojuser > 0)
713
-            {
714
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
715
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
716
-            }
717
-            if ($filterontaskuser > 0)
718
-            {
719
-                $sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
720
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
721
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
722
-            }
723
-            else
724
-            {
725
-                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
726
-            }
727
-            $sql.= " WHERE p.entity IN (".getEntity('project').")";
728
-        }
729
-        else return 'BadValueForParameterMode';
730
-
731
-        if ($filteronprojuser > 0)
732
-        {
733
-            $sql.= " AND p.rowid = ec.element_id";
734
-            $sql.= " AND ctc.rowid = ec.fk_c_type_contact";
735
-            $sql.= " AND ctc.element = 'project'";
736
-            $sql.= " AND ec.fk_socpeople = ".$filteronprojuser;
737
-            $sql.= " AND ec.statut = 4";
738
-            $sql.= " AND ctc.source = 'internal'";
739
-        }
740
-        if ($filterontaskuser > 0)
741
-        {
742
-            $sql.= " AND t.fk_projet = p.rowid";
743
-            $sql.= " AND p.rowid = ec2.element_id";
744
-            $sql.= " AND ctc2.rowid = ec2.fk_c_type_contact";
745
-            $sql.= " AND ctc2.element = 'project_task'";
746
-            $sql.= " AND ec2.fk_socpeople = ".$filterontaskuser;
747
-            $sql.= " AND ec2.statut = 4";
748
-            $sql.= " AND ctc2.source = 'internal'";
749
-        }
750
-        if ($socid)	$sql.= " AND p.fk_soc = ".$socid;
751
-        if ($projectid) $sql.= " AND p.rowid in (".$projectid.")";
752
-        if ($filteronprojref) $sql.= " AND p.ref LIKE '%".$filteronprojref."%'";
753
-        if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus;
754
-        if ($morewherefilter) $sql.=$morewherefilter;
755
-        $sql.= " ORDER BY p.ref, t.rang, t.dateo";
756
-
757
-        //print $sql;exit;
758
-        dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG);
759
-        $resql = $this->db->query($sql);
760
-        if ($resql)
761
-        {
762
-            $num = $this->db->num_rows($resql);
763
-            $i = 0;
764
-            // Loop on each record found, so each couple (project id, task id)
765
-            while ($i < $num)
766
-            {
767
-                $error=0;
768
-
769
-                $obj = $this->db->fetch_object($resql);
770
-
771
-                if ((! $obj->public) && (is_object($userp)))	// If not public project and we ask a filter on project owned by a user
772
-                {
773
-                    if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
774
-                    {
775
-                        $error++;
776
-                    }
777
-                }
778
-                if (is_object($usert))							// If we ask a filter on a user affected to a task
779
-                {
780
-                    if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
781
-                    {
782
-                        $error++;
783
-                    }
784
-                }
785
-
786
-                if (! $error)
787
-                {
788
-					$tasks[$i] = new Task($this->db);
789
-                    $tasks[$i]->id				= $obj->taskid;
790
-					$tasks[$i]->ref				= $obj->taskref;
791
-                    $tasks[$i]->fk_project		= $obj->projectid;
792
-                    $tasks[$i]->projectref		= $obj->ref;
793
-                    $tasks[$i]->projectlabel	= $obj->plabel;
794
-                    $tasks[$i]->projectstatus	= $obj->projectstatus;
795
-                    $tasks[$i]->label			= $obj->label;
796
-                    $tasks[$i]->description		= $obj->description;
797
-                    $tasks[$i]->fk_parent		= $obj->fk_task_parent;      // deprecated
798
-                    $tasks[$i]->fk_task_parent	= $obj->fk_task_parent;
799
-                    $tasks[$i]->duration		= $obj->duration_effective;
800
-                    $tasks[$i]->planned_workload= $obj->planned_workload;
801
-                    $tasks[$i]->progress		= $obj->progress;
802
-                    $tasks[$i]->fk_statut		= $obj->status;
803
-                    $tasks[$i]->public			= $obj->public;
804
-                    $tasks[$i]->date_start		= $this->db->jdate($obj->date_start);
805
-                    $tasks[$i]->date_end		= $this->db->jdate($obj->date_end);
806
-                    $tasks[$i]->rang	   		= $obj->rang;
807
-
808
-                    $tasks[$i]->thirdparty_id	= $obj->thirdparty_id;
809
-                    $tasks[$i]->thirdparty_name	= $obj->thirdparty_name;
810
-                }
811
-
812
-                $i++;
813
-            }
814
-            $this->db->free($resql);
815
-        }
816
-        else
817
-        {
818
-            dol_print_error($this->db);
819
-        }
820
-
821
-        return $tasks;
822
-    }
823
-
824
-    /**
825
-     * Return list of roles for a user for each projects or each tasks (or a particular project or a particular task).
826
-     *
827
-     * @param	User	$userp			      Return roles on project for this internal user. If set, usert and taskid must not be defined.
828
-     * @param	User	$usert			      Return roles on task for this internal user. If set userp must NOT be defined. -1 means no filter.
829
-     * @param 	int		$projectid		      Project id list separated with , to filter on project
830
-     * @param 	int		$taskid			      Task id to filter on a task
831
-     * @param	integer	$filteronprojstatus	  Filter on project status if userp is set. Not used if userp not defined.
832
-     * @return 	array					      Array (projectid => 'list of roles for project' or taskid => 'list of roles for task')
833
-     */
834
-    function getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1)
835
-    {
836
-        $arrayroles = array();
837
-
838
-        dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid);
839
-
840
-        // We want role of user for a projet or role of user for a task. Both are not possible.
841
-        if (empty($userp) && empty($usert))
842
-        {
843
-            $this->error="CallWithWrongParameters";
844
-            return -1;
845
-        }
846
-        if (! empty($userp) && ! empty($usert))
847
-        {
848
-            $this->error="CallWithWrongParameters";
849
-            return -1;
850
-        }
851
-
852
-        /* Liste des taches et role sur les projets ou taches */
853
-        $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source";
854
-        if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt";
855
-        if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
856
-        if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
857
-        $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
858
-        $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
859
-        $sql.= " WHERE pt.rowid = ec.element_id";
860
-        if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus;
861
-        if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
862
-        if ($userp) $sql.= " AND ctc.element = 'project'";
863
-        if ($usert) $sql.= " AND ctc.element = 'project_task'";
864
-        $sql.= " AND ctc.rowid = ec.fk_c_type_contact";
865
-        if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id;
866
-        if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id;
867
-        $sql.= " AND ec.statut = 4";
868
-        $sql.= " AND ctc.source = 'internal'";
869
-        if ($projectid)
870
-        {
871
-            if ($userp) $sql.= " AND pt.rowid in (".$projectid.")";
872
-            if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")";
873
-        }
874
-        if ($taskid)
875
-        {
876
-            if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS";
877
-            if ($usert) $sql.= " AND pt.rowid = ".$taskid;
878
-        }
879
-        //print $sql;
880
-
881
-        dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG);
882
-        $resql = $this->db->query($sql);
883
-        if ($resql)
884
-        {
885
-            $num = $this->db->num_rows($resql);
886
-            $i = 0;
887
-            while ($i < $num)
888
-            {
889
-                $obj = $this->db->fetch_object($resql);
890
-                if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code;
891
-                else $arrayroles[$obj->pid].=','.$obj->code;
892
-                $i++;
893
-            }
894
-            $this->db->free($resql);
895
-        }
896
-        else
897
-        {
898
-            dol_print_error($this->db);
899
-        }
900
-
901
-        return $arrayroles;
902
-    }
903
-
904
-
905
-    /**
906
-     * 	Return list of id of contacts of task
907
-     *
908
-     *	@param	string	$source		Source
909
-     *  @return array				Array of id of contacts
910
-     */
911
-    function getListContactId($source='internal')
912
-    {
913
-        $contactAlreadySelected = array();
914
-        $tab = $this->liste_contact(-1,$source);
915
-        //var_dump($tab);
916
-        $num=count($tab);
917
-        $i = 0;
918
-        while ($i < $num)
919
-        {
920
-            if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
921
-            else  $contactAlreadySelected[$i] = $tab[$i]['id'];
922
-            $i++;
923
-        }
924
-        return $contactAlreadySelected;
925
-    }
926
-
927
-
928
-    /**
929
-     *  Add time spent
930
-     *
931
-     *  @param	User	$user           User object
932
-     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
933
-     *  @return	int                     <=0 if KO, >0 if OK
934
-     */
935
-    function addTimeSpent($user, $notrigger=0)
936
-    {
937
-        global $conf,$langs;
938
-
939
-        dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
940
-
941
-        $ret = 0;
942
-
943
-        // Check parameters
944
-        if (! is_object($user))
945
-        {
946
-        	dol_print_error('',"Method addTimeSpent was called with wrong parameter user");
947
-        	return -1;
948
-        }
949
-
950
-        // Clean parameters
951
-        if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
906
+	 * 	Return list of id of contacts of task
907
+	 *
908
+	 *	@param	string	$source		Source
909
+	 *  @return array				Array of id of contacts
910
+	 */
911
+	function getListContactId($source='internal')
912
+	{
913
+		$contactAlreadySelected = array();
914
+		$tab = $this->liste_contact(-1,$source);
915
+		//var_dump($tab);
916
+		$num=count($tab);
917
+		$i = 0;
918
+		while ($i < $num)
919
+		{
920
+			if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
921
+			else  $contactAlreadySelected[$i] = $tab[$i]['id'];
922
+			$i++;
923
+		}
924
+		return $contactAlreadySelected;
925
+	}
926
+
927
+
928
+	/**
929
+	 *  Add time spent
930
+	 *
931
+	 *  @param	User	$user           User object
932
+	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
933
+	 *  @return	int                     <=0 if KO, >0 if OK
934
+	 */
935
+	function addTimeSpent($user, $notrigger=0)
936
+	{
937
+		global $conf,$langs;
938
+
939
+		dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
940
+
941
+		$ret = 0;
942
+
943
+		// Check parameters
944
+		if (! is_object($user))
945
+		{
946
+			dol_print_error('',"Method addTimeSpent was called with wrong parameter user");
947
+			return -1;
948
+		}
949
+
950
+		// Clean parameters
951
+		if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
952 952
 		if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
953 953
 
954
-        $this->db->begin();
955
-
956
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time (";
957
-        $sql.= "fk_task";
958
-        $sql.= ", task_date";
959
-        $sql.= ", task_datehour";
960
-        $sql.= ", task_date_withhour";
961
-        $sql.= ", task_duration";
962
-        $sql.= ", fk_user";
963
-        $sql.= ", note";
964
-        $sql.= ") VALUES (";
965
-        $sql.= $this->id;
966
-        $sql.= ", '".$this->db->idate($this->timespent_date)."'";
967
-        $sql.= ", '".$this->db->idate($this->timespent_datehour)."'";
968
-        $sql.= ", ".(empty($this->timespent_withhour)?0:1);
969
-        $sql.= ", ".$this->timespent_duration;
970
-        $sql.= ", ".$this->timespent_fk_user;
971
-        $sql.= ", ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
972
-        $sql.= ")";
973
-
974
-        $resql=$this->db->query($sql);
975
-        if ($resql)
976
-        {
977
-            $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time");
978
-            $ret = $tasktime_id;
954
+		$this->db->begin();
955
+
956
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time (";
957
+		$sql.= "fk_task";
958
+		$sql.= ", task_date";
959
+		$sql.= ", task_datehour";
960
+		$sql.= ", task_date_withhour";
961
+		$sql.= ", task_duration";
962
+		$sql.= ", fk_user";
963
+		$sql.= ", note";
964
+		$sql.= ") VALUES (";
965
+		$sql.= $this->id;
966
+		$sql.= ", '".$this->db->idate($this->timespent_date)."'";
967
+		$sql.= ", '".$this->db->idate($this->timespent_datehour)."'";
968
+		$sql.= ", ".(empty($this->timespent_withhour)?0:1);
969
+		$sql.= ", ".$this->timespent_duration;
970
+		$sql.= ", ".$this->timespent_fk_user;
971
+		$sql.= ", ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
972
+		$sql.= ")";
973
+
974
+		$resql=$this->db->query($sql);
975
+		if ($resql)
976
+		{
977
+			$tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time");
978
+			$ret = $tasktime_id;
979 979
 			$this->timespent_id = $ret;
980 980
 
981
-            if (! $notrigger)
982
-            {
983
-                // Call trigger
984
-                $result=$this->call_trigger('TASK_TIMESPENT_CREATE',$user);
985
-                if ($result < 0) { $ret=-1; }
986
-                // End call triggers
987
-            }
988
-        }
989
-        else
990
-		{
991
-            $this->error=$this->db->lasterror();
992
-            $ret = -1;
993
-        }
994
-
995
-        if ($ret > 0)
996
-        {
997
-        	// Recalculate amount of time spent for task and update denormalized field
998
-            $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
999
-            $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
981
+			if (! $notrigger)
982
+			{
983
+				// Call trigger
984
+				$result=$this->call_trigger('TASK_TIMESPENT_CREATE',$user);
985
+				if ($result < 0) { $ret=-1; }
986
+				// End call triggers
987
+			}
988
+		}
989
+		else
990
+		{
991
+			$this->error=$this->db->lasterror();
992
+			$ret = -1;
993
+		}
994
+
995
+		if ($ret > 0)
996
+		{
997
+			// Recalculate amount of time spent for task and update denormalized field
998
+			$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
999
+			$sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
1000 1000
 			if (isset($this->progress)) $sql.= ", progress = " . $this->progress;	// Do not overwrite value if not provided
1001
-            $sql.= " WHERE rowid = ".$this->id;
1002
-
1003
-            dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1004
-            if (! $this->db->query($sql) )
1005
-            {
1006
-                $this->error=$this->db->lasterror();
1007
-                $ret = -2;
1008
-            }
1009
-
1010
-            $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time";
1011
-            $sql.= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")";	// set average hour rate of user
1012
-            $sql.= " WHERE rowid = ".$tasktime_id;
1013
-
1014
-            dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1015
-            if (! $this->db->query($sql) )
1016
-            {
1017
-                $this->error=$this->db->lasterror();
1018
-                $ret = -2;
1019
-            }
1020
-        }
1021
-
1022
-        if ($ret >0)
1023
-        {
1024
-        	$this->db->commit();
1025
-        }
1026
-        else
1027
-		{
1028
-        	$this->db->rollback();
1029
-        }
1030
-        return $ret;
1031
-    }
1032
-
1033
-    /**
1034
-     *  Calculate total of time spent for task
1035
-     *
1036
-     *  @param  int     $userid     Filter on user id. 0=No filter
1037
-     *  @return array		        Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull')
1038
-     */
1039
-    function getSummaryOfTimeSpent($userid=0)
1040
-    {
1041
-        global $langs;
1042
-
1043
-        $id=$this->id;
1044
-        if (empty($id))
1045
-        {
1046
-            dol_syslog("getSummaryOfTimeSpent called on a not loaded task", LOG_ERR);
1047
-            return -1;
1048
-        }
1049
-
1050
-        $result=array();
1051
-
1052
-        $sql = "SELECT";
1053
-        $sql.= " MIN(t.task_datehour) as min_date,";
1054
-        $sql.= " MAX(t.task_datehour) as max_date,";
1055
-        $sql.= " SUM(t.task_duration) as total_duration,";
1056
-        $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,";
1057
-        $sql.= " COUNT(t.rowid) as nblines,";
1058
-        $sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1059
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1060
-        $sql.= " WHERE t.fk_task = ".$id;
1061
-        if ($userid > 0) $sql.=" AND t.fk_user = ".$userid;
1062
-
1063
-        dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1064
-        $resql=$this->db->query($sql);
1065
-        if ($resql)
1066
-        {
1067
-            $obj = $this->db->fetch_object($resql);
1068
-
1069
-            $result['min_date'] = $obj->min_date;               // deprecated. use the ->timespent_xxx instead
1070
-            $result['max_date'] = $obj->max_date;               // deprecated. use the ->timespent_xxx instead
1071
-            $result['total_duration'] = $obj->total_duration;   // deprecated. use the ->timespent_xxx instead
1072
-
1073
-            $this->timespent_min_date=$this->db->jdate($obj->min_date);
1074
-            $this->timespent_max_date=$this->db->jdate($obj->max_date);
1075
-            $this->timespent_total_duration=$obj->total_duration;
1076
-            $this->timespent_total_amount=$obj->total_amount;
1077
-            $this->timespent_nblinesnull=($obj->nblinesnull?$obj->nblinesnull:0);
1078
-            $this->timespent_nblines=($obj->nblines?$obj->nblines:0);
1079
-
1080
-            $this->db->free($resql);
1081
-        }
1082
-        else
1083
-        {
1084
-            dol_print_error($this->db);
1085
-        }
1086
-        return $result;
1087
-    }
1088
-
1089
-    /**
1090
-     *  Calculate quantity and value of time consumed using the thm (hourly amount value of work for user entering time)
1091
-     *
1092
-     *	@param		User		$fuser		Filter on a dedicated user
1093
-     *  @param		string		$dates		Start date (ex 00:00:00)
1094
-     *  @param		string		$datee		End date (ex 23:59:59)
1095
-     *  @return 	array	        		Array of info for task array('amount','nbseconds','nblinesnull')
1096
-     */
1097
-    function getSumOfAmount($fuser='', $dates='', $datee='')
1098
-    {
1099
-        global $langs;
1100
-
1101
-        if (empty($id)) $id=$this->id;
1102
-
1103
-        $result=array();
1104
-
1105
-        $sql = "SELECT";
1106
-        $sql.= " SUM(t.task_duration) as nbseconds,";
1107
-        $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1108
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1109
-        $sql.= " WHERE t.fk_task = ".$id;
1110
-        if (is_object($fuser) && $fuser->id > 0)
1111
-        {
1112
-        	$sql.=" AND fk_user = ".$fuser->id;
1113
-        }
1114
-    	if ($dates > 0)
1001
+			$sql.= " WHERE rowid = ".$this->id;
1002
+
1003
+			dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1004
+			if (! $this->db->query($sql) )
1005
+			{
1006
+				$this->error=$this->db->lasterror();
1007
+				$ret = -2;
1008
+			}
1009
+
1010
+			$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time";
1011
+			$sql.= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")";	// set average hour rate of user
1012
+			$sql.= " WHERE rowid = ".$tasktime_id;
1013
+
1014
+			dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1015
+			if (! $this->db->query($sql) )
1016
+			{
1017
+				$this->error=$this->db->lasterror();
1018
+				$ret = -2;
1019
+			}
1020
+		}
1021
+
1022
+		if ($ret >0)
1023
+		{
1024
+			$this->db->commit();
1025
+		}
1026
+		else
1027
+		{
1028
+			$this->db->rollback();
1029
+		}
1030
+		return $ret;
1031
+	}
1032
+
1033
+	/**
1034
+	 *  Calculate total of time spent for task
1035
+	 *
1036
+	 *  @param  int     $userid     Filter on user id. 0=No filter
1037
+	 *  @return array		        Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull')
1038
+	 */
1039
+	function getSummaryOfTimeSpent($userid=0)
1040
+	{
1041
+		global $langs;
1042
+
1043
+		$id=$this->id;
1044
+		if (empty($id))
1045
+		{
1046
+			dol_syslog("getSummaryOfTimeSpent called on a not loaded task", LOG_ERR);
1047
+			return -1;
1048
+		}
1049
+
1050
+		$result=array();
1051
+
1052
+		$sql = "SELECT";
1053
+		$sql.= " MIN(t.task_datehour) as min_date,";
1054
+		$sql.= " MAX(t.task_datehour) as max_date,";
1055
+		$sql.= " SUM(t.task_duration) as total_duration,";
1056
+		$sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,";
1057
+		$sql.= " COUNT(t.rowid) as nblines,";
1058
+		$sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1059
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1060
+		$sql.= " WHERE t.fk_task = ".$id;
1061
+		if ($userid > 0) $sql.=" AND t.fk_user = ".$userid;
1062
+
1063
+		dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1064
+		$resql=$this->db->query($sql);
1065
+		if ($resql)
1066
+		{
1067
+			$obj = $this->db->fetch_object($resql);
1068
+
1069
+			$result['min_date'] = $obj->min_date;               // deprecated. use the ->timespent_xxx instead
1070
+			$result['max_date'] = $obj->max_date;               // deprecated. use the ->timespent_xxx instead
1071
+			$result['total_duration'] = $obj->total_duration;   // deprecated. use the ->timespent_xxx instead
1072
+
1073
+			$this->timespent_min_date=$this->db->jdate($obj->min_date);
1074
+			$this->timespent_max_date=$this->db->jdate($obj->max_date);
1075
+			$this->timespent_total_duration=$obj->total_duration;
1076
+			$this->timespent_total_amount=$obj->total_amount;
1077
+			$this->timespent_nblinesnull=($obj->nblinesnull?$obj->nblinesnull:0);
1078
+			$this->timespent_nblines=($obj->nblines?$obj->nblines:0);
1079
+
1080
+			$this->db->free($resql);
1081
+		}
1082
+		else
1083
+		{
1084
+			dol_print_error($this->db);
1085
+		}
1086
+		return $result;
1087
+	}
1088
+
1089
+	/**
1090
+	 *  Calculate quantity and value of time consumed using the thm (hourly amount value of work for user entering time)
1091
+	 *
1092
+	 *	@param		User		$fuser		Filter on a dedicated user
1093
+	 *  @param		string		$dates		Start date (ex 00:00:00)
1094
+	 *  @param		string		$datee		End date (ex 23:59:59)
1095
+	 *  @return 	array	        		Array of info for task array('amount','nbseconds','nblinesnull')
1096
+	 */
1097
+	function getSumOfAmount($fuser='', $dates='', $datee='')
1098
+	{
1099
+		global $langs;
1100
+
1101
+		if (empty($id)) $id=$this->id;
1102
+
1103
+		$result=array();
1104
+
1105
+		$sql = "SELECT";
1106
+		$sql.= " SUM(t.task_duration) as nbseconds,";
1107
+		$sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1108
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1109
+		$sql.= " WHERE t.fk_task = ".$id;
1110
+		if (is_object($fuser) && $fuser->id > 0)
1111
+		{
1112
+			$sql.=" AND fk_user = ".$fuser->id;
1113
+		}
1114
+		if ($dates > 0)
1115 1115
 		{
1116 1116
 			$datefieldname="task_datehour";
1117 1117
 			$sql.=" AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)";
1118 1118
 		}
1119
-    	if ($datee > 0)
1119
+		if ($datee > 0)
1120 1120
 		{
1121 1121
 			$datefieldname="task_datehour";
1122 1122
 			$sql.=" AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)";
1123 1123
 		}
1124 1124
 		//print $sql;
1125 1125
 
1126
-        dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
1127
-        $resql=$this->db->query($sql);
1128
-        if ($resql)
1129
-        {
1130
-            $obj = $this->db->fetch_object($resql);
1131
-
1132
-            $result['amount'] = $obj->amount;
1133
-            $result['nbseconds'] = $obj->nbseconds;
1134
-            $result['nblinesnull'] = $obj->nblinesnull;
1135
-
1136
-            $this->db->free($resql);
1137
-            return $result;
1138
-        }
1139
-        else
1140
-		{
1141
-            dol_print_error($this->db);
1142
-            return $result;
1143
-        }
1144
-    }
1145
-
1146
-    /**
1147
-     *  Load one record of time spent
1148
-     *
1149
-     *  @param	int		$id 	Id object
1150
-     *  @return int		        <0 if KO, >0 if OK
1151
-     */
1152
-    function fetchTimeSpent($id)
1153
-    {
1154
-        global $langs;
1155
-
1156
-        $sql = "SELECT";
1157
-        $sql.= " t.rowid,";
1158
-        $sql.= " t.fk_task,";
1159
-        $sql.= " t.task_date,";
1160
-        $sql.= " t.task_datehour,";
1161
-        $sql.= " t.task_date_withhour,";
1162
-        $sql.= " t.task_duration,";
1163
-        $sql.= " t.fk_user,";
1164
-        $sql.= " t.note";
1165
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1166
-        $sql.= " WHERE t.rowid = ".$id;
1167
-
1168
-        dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
1169
-        $resql=$this->db->query($sql);
1170
-        if ($resql)
1171
-        {
1172
-            if ($this->db->num_rows($resql))
1173
-            {
1174
-                $obj = $this->db->fetch_object($resql);
1175
-
1176
-                $this->timespent_id			= $obj->rowid;
1177
-                $this->id					= $obj->fk_task;
1178
-                $this->timespent_date		= $this->db->jdate($obj->task_date);
1179
-                $this->timespent_datehour   = $this->db->jdate($obj->task_datehour);
1180
-                $this->timespent_withhour   = $obj->task_date_withhour;
1181
-                $this->timespent_duration	= $obj->task_duration;
1182
-                $this->timespent_fk_user	= $obj->fk_user;
1183
-                $this->timespent_note		= $obj->note;
1184
-            }
1185
-
1186
-            $this->db->free($resql);
1187
-
1188
-            return 1;
1189
-        }
1190
-        else
1191
-        {
1192
-            $this->error="Error ".$this->db->lasterror();
1193
-            return -1;
1194
-        }
1195
-    }
1196
-
1197
-    /**
1198
-     *	Update time spent
1199
-     *
1200
-     *  @param	User	$user           User id
1201
-     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1202
-     *  @return	int						<0 if KO, >0 if OK
1203
-     */
1204
-    function updateTimeSpent($user, $notrigger=0)
1205
-    {
1206
-    	global $conf,$langs;
1207
-
1208
-        $ret = 0;
1209
-
1210
-        // Clean parameters
1211
-        if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
1212
-        if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
1213
-
1214
-        $this->db->begin();
1215
-
1216
-        $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
1217
-        $sql.= " task_date = '".$this->db->idate($this->timespent_date)."',";
1218
-        $sql.= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',";
1219
-        $sql.= " task_date_withhour = ".(empty($this->timespent_withhour)?0:1).",";
1220
-        $sql.= " task_duration = ".$this->timespent_duration.",";
1221
-        $sql.= " fk_user = ".$this->timespent_fk_user.",";
1222
-        $sql.= " note = ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
1223
-        $sql.= " WHERE rowid = ".$this->timespent_id;
1224
-
1225
-        dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1226
-        if ($this->db->query($sql) )
1227
-        {
1228
-            if (! $notrigger)
1229
-            {
1230
-                // Call trigger
1231
-                $result=$this->call_trigger('TASK_TIMESPENT_MODIFY',$user);
1232
-                if ($result < 0)
1233
-                {
1234
-                    $this->db->rollback();
1235
-                    $ret = -1;
1236
-                }
1237
-                else $ret = 1;
1238
-                // End call triggers
1239
-            }
1240
-            else $ret = 1;
1241
-        }
1242
-        else
1243
-        {
1244
-            $this->error=$this->db->lasterror();
1245
-            $this->db->rollback();
1246
-            $ret = -1;
1247
-        }
1248
-
1249
-        if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration))
1250
-        {
1251
-            $newDuration = $this->timespent_duration - $this->timespent_old_duration;
1252
-
1253
-            $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1254
-            $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")";
1255
-            $sql.= " WHERE rowid = ".$this->id;
1256
-
1257
-            dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1258
-            if (! $this->db->query($sql) )
1259
-            {
1260
-                $this->error=$this->db->lasterror();
1261
-                $this->db->rollback();
1262
-                $ret = -2;
1263
-            }
1264
-        }
1265
-
1266
-        if ($ret >= 0) $this->db->commit();
1267
-        return $ret;
1268
-    }
1269
-
1270
-    /**
1271
-     *  Delete time spent
1272
-     *
1273
-     *  @param	User	$user        	User that delete
1274
-     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1275
-     *  @return	int						<0 if KO, >0 if OK
1276
-     */
1277
-    function delTimeSpent($user, $notrigger=0)
1278
-    {
1279
-        global $conf, $langs;
1280
-
1281
-        $error=0;
1282
-
1283
-        $this->db->begin();
1284
-
1285
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
1286
-        $sql.= " WHERE rowid = ".$this->timespent_id;
1287
-
1288
-        dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1289
-        $resql = $this->db->query($sql);
1290
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1291
-
1292
-        if (! $error)
1293
-        {
1294
-            if (! $notrigger)
1295
-            {
1296
-                // Call trigger
1297
-                $result=$this->call_trigger('TASK_TIMESPENT_DELETE',$user);
1298
-                if ($result < 0) { $error++; }
1299
-                // End call triggers
1300
-            }
1301
-        }
1302
-
1303
-        if (! $error)
1304
-        {
1305
-            $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1306
-            $sql.= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration?$this->timespent_duration:0);
1307
-            $sql.= " WHERE rowid = ".$this->id;
1308
-
1309
-            dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1310
-            if ($this->db->query($sql) )
1311
-            {
1312
-                $result = 0;
1313
-            }
1314
-            else
1315
-            {
1316
-                $this->error=$this->db->lasterror();
1317
-                $result = -2;
1318
-            }
1319
-        }
1320
-
1321
-        // Commit or rollback
1322
-        if ($error)
1323
-        {
1324
-            foreach($this->errors as $errmsg)
1325
-            {
1326
-                dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
1327
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
1328
-            }
1329
-            $this->db->rollback();
1330
-            return -1*$error;
1331
-        }
1332
-        else
1333
-        {
1334
-            $this->db->commit();
1335
-            return 1;
1336
-        }
1337
-    }
1338
-
1339
-     /**	Load an object from its id and create a new one in database
1126
+		dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
1127
+		$resql=$this->db->query($sql);
1128
+		if ($resql)
1129
+		{
1130
+			$obj = $this->db->fetch_object($resql);
1131
+
1132
+			$result['amount'] = $obj->amount;
1133
+			$result['nbseconds'] = $obj->nbseconds;
1134
+			$result['nblinesnull'] = $obj->nblinesnull;
1135
+
1136
+			$this->db->free($resql);
1137
+			return $result;
1138
+		}
1139
+		else
1140
+		{
1141
+			dol_print_error($this->db);
1142
+			return $result;
1143
+		}
1144
+	}
1145
+
1146
+	/**
1147
+	 *  Load one record of time spent
1148
+	 *
1149
+	 *  @param	int		$id 	Id object
1150
+	 *  @return int		        <0 if KO, >0 if OK
1151
+	 */
1152
+	function fetchTimeSpent($id)
1153
+	{
1154
+		global $langs;
1155
+
1156
+		$sql = "SELECT";
1157
+		$sql.= " t.rowid,";
1158
+		$sql.= " t.fk_task,";
1159
+		$sql.= " t.task_date,";
1160
+		$sql.= " t.task_datehour,";
1161
+		$sql.= " t.task_date_withhour,";
1162
+		$sql.= " t.task_duration,";
1163
+		$sql.= " t.fk_user,";
1164
+		$sql.= " t.note";
1165
+		$sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1166
+		$sql.= " WHERE t.rowid = ".$id;
1167
+
1168
+		dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
1169
+		$resql=$this->db->query($sql);
1170
+		if ($resql)
1171
+		{
1172
+			if ($this->db->num_rows($resql))
1173
+			{
1174
+				$obj = $this->db->fetch_object($resql);
1175
+
1176
+				$this->timespent_id			= $obj->rowid;
1177
+				$this->id					= $obj->fk_task;
1178
+				$this->timespent_date		= $this->db->jdate($obj->task_date);
1179
+				$this->timespent_datehour   = $this->db->jdate($obj->task_datehour);
1180
+				$this->timespent_withhour   = $obj->task_date_withhour;
1181
+				$this->timespent_duration	= $obj->task_duration;
1182
+				$this->timespent_fk_user	= $obj->fk_user;
1183
+				$this->timespent_note		= $obj->note;
1184
+			}
1185
+
1186
+			$this->db->free($resql);
1187
+
1188
+			return 1;
1189
+		}
1190
+		else
1191
+		{
1192
+			$this->error="Error ".$this->db->lasterror();
1193
+			return -1;
1194
+		}
1195
+	}
1196
+
1197
+	/**
1198
+	 *	Update time spent
1199
+	 *
1200
+	 *  @param	User	$user           User id
1201
+	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1202
+	 *  @return	int						<0 if KO, >0 if OK
1203
+	 */
1204
+	function updateTimeSpent($user, $notrigger=0)
1205
+	{
1206
+		global $conf,$langs;
1207
+
1208
+		$ret = 0;
1209
+
1210
+		// Clean parameters
1211
+		if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
1212
+		if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
1213
+
1214
+		$this->db->begin();
1215
+
1216
+		$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
1217
+		$sql.= " task_date = '".$this->db->idate($this->timespent_date)."',";
1218
+		$sql.= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',";
1219
+		$sql.= " task_date_withhour = ".(empty($this->timespent_withhour)?0:1).",";
1220
+		$sql.= " task_duration = ".$this->timespent_duration.",";
1221
+		$sql.= " fk_user = ".$this->timespent_fk_user.",";
1222
+		$sql.= " note = ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
1223
+		$sql.= " WHERE rowid = ".$this->timespent_id;
1224
+
1225
+		dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1226
+		if ($this->db->query($sql) )
1227
+		{
1228
+			if (! $notrigger)
1229
+			{
1230
+				// Call trigger
1231
+				$result=$this->call_trigger('TASK_TIMESPENT_MODIFY',$user);
1232
+				if ($result < 0)
1233
+				{
1234
+					$this->db->rollback();
1235
+					$ret = -1;
1236
+				}
1237
+				else $ret = 1;
1238
+				// End call triggers
1239
+			}
1240
+			else $ret = 1;
1241
+		}
1242
+		else
1243
+		{
1244
+			$this->error=$this->db->lasterror();
1245
+			$this->db->rollback();
1246
+			$ret = -1;
1247
+		}
1248
+
1249
+		if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration))
1250
+		{
1251
+			$newDuration = $this->timespent_duration - $this->timespent_old_duration;
1252
+
1253
+			$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1254
+			$sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")";
1255
+			$sql.= " WHERE rowid = ".$this->id;
1256
+
1257
+			dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1258
+			if (! $this->db->query($sql) )
1259
+			{
1260
+				$this->error=$this->db->lasterror();
1261
+				$this->db->rollback();
1262
+				$ret = -2;
1263
+			}
1264
+		}
1265
+
1266
+		if ($ret >= 0) $this->db->commit();
1267
+		return $ret;
1268
+	}
1269
+
1270
+	/**
1271
+	 *  Delete time spent
1340 1272
 	 *
1341
-	 *	@param	int		$fromid     			Id of object to clone
1342
-	 *  @param	int		$project_id				Id of project to attach clone task
1343
-	 *  @param	int		$parent_task_id			Id of task to attach clone task
1344
-	 *  @param	bool	$clone_change_dt		recalculate date of task regarding new project start date
1345
-	 *	@param	bool	$clone_affectation		clone affectation of project
1346
-	 *	@param	bool	$clone_time				clone time of project
1347
-	 *	@param	bool	$clone_file				clone file of project
1348
-	 *  @param	bool	$clone_note				clone note of project
1349
-	 *	@param	bool	$clone_prog				clone progress of project
1350
-	 * 	@return	int								New id of clone
1273
+	 *  @param	User	$user        	User that delete
1274
+	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1275
+	 *  @return	int						<0 if KO, >0 if OK
1351 1276
 	 */
1277
+	function delTimeSpent($user, $notrigger=0)
1278
+	{
1279
+		global $conf, $langs;
1280
+
1281
+		$error=0;
1282
+
1283
+		$this->db->begin();
1284
+
1285
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
1286
+		$sql.= " WHERE rowid = ".$this->timespent_id;
1287
+
1288
+		dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1289
+		$resql = $this->db->query($sql);
1290
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1291
+
1292
+		if (! $error)
1293
+		{
1294
+			if (! $notrigger)
1295
+			{
1296
+				// Call trigger
1297
+				$result=$this->call_trigger('TASK_TIMESPENT_DELETE',$user);
1298
+				if ($result < 0) { $error++; }
1299
+				// End call triggers
1300
+			}
1301
+		}
1302
+
1303
+		if (! $error)
1304
+		{
1305
+			$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1306
+			$sql.= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration?$this->timespent_duration:0);
1307
+			$sql.= " WHERE rowid = ".$this->id;
1308
+
1309
+			dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1310
+			if ($this->db->query($sql) )
1311
+			{
1312
+				$result = 0;
1313
+			}
1314
+			else
1315
+			{
1316
+				$this->error=$this->db->lasterror();
1317
+				$result = -2;
1318
+			}
1319
+		}
1320
+
1321
+		// Commit or rollback
1322
+		if ($error)
1323
+		{
1324
+			foreach($this->errors as $errmsg)
1325
+			{
1326
+				dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
1327
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
1328
+			}
1329
+			$this->db->rollback();
1330
+			return -1*$error;
1331
+		}
1332
+		else
1333
+		{
1334
+			$this->db->commit();
1335
+			return 1;
1336
+		}
1337
+	}
1338
+
1339
+	 /**	Load an object from its id and create a new one in database
1340
+	  *
1341
+	  *	@param	int		$fromid     			Id of object to clone
1342
+	  *  @param	int		$project_id				Id of project to attach clone task
1343
+	  *  @param	int		$parent_task_id			Id of task to attach clone task
1344
+	  *  @param	bool	$clone_change_dt		recalculate date of task regarding new project start date
1345
+	  *	@param	bool	$clone_affectation		clone affectation of project
1346
+	  *	@param	bool	$clone_time				clone time of project
1347
+	  *	@param	bool	$clone_file				clone file of project
1348
+	  *  @param	bool	$clone_note				clone note of project
1349
+	  *	@param	bool	$clone_prog				clone progress of project
1350
+	  * 	@return	int								New id of clone
1351
+	  */
1352 1352
 	function createFromClone($fromid,$project_id,$parent_task_id,$clone_change_dt=false,$clone_affectation=false,$clone_time=false,$clone_file=false,$clone_note=false,$clone_prog=false)
1353 1353
 	{
1354 1354
 		global $user,$langs,$conf;
@@ -1387,39 +1387,39 @@  discard block
 block discarded – undo
1387 1387
 
1388 1388
 		$clone_task->id					= 0;
1389 1389
 		$clone_task->ref				= $defaultref;
1390
-        $clone_task->fk_project			= $project_id;
1391
-        $clone_task->fk_task_parent		= $parent_task_id;
1392
-        $clone_task->date_c				= $datec;
1393
-        $clone_task->planned_workload	= $origin_task->planned_workload;
1390
+		$clone_task->fk_project			= $project_id;
1391
+		$clone_task->fk_task_parent		= $parent_task_id;
1392
+		$clone_task->date_c				= $datec;
1393
+		$clone_task->planned_workload	= $origin_task->planned_workload;
1394 1394
 		$clone_task->rang				= $origin_task->rang;
1395 1395
 
1396
-        //Manage Task Date
1397
-        if ($clone_change_dt)
1398
-        {
1399
-        	$projectstatic=new Project($this->db);
1400
-        	$projectstatic->fetch($ori_project_id);
1396
+		//Manage Task Date
1397
+		if ($clone_change_dt)
1398
+		{
1399
+			$projectstatic=new Project($this->db);
1400
+			$projectstatic->fetch($ori_project_id);
1401 1401
 
1402
-        	//Origin project strat date
1403
-	    	$orign_project_dt_start = $projectstatic->date_start;
1402
+			//Origin project strat date
1403
+			$orign_project_dt_start = $projectstatic->date_start;
1404 1404
 
1405
-	    	//Calcultate new task start date with difference between origin proj start date and origin task start date
1406
-	    	if (!empty($clone_task->date_start))
1407
-	    	{
1405
+			//Calcultate new task start date with difference between origin proj start date and origin task start date
1406
+			if (!empty($clone_task->date_start))
1407
+			{
1408 1408
 				$clone_task->date_start			= $now + $clone_task->date_start - $orign_project_dt_start;
1409
-	    	}
1409
+			}
1410 1410
 
1411
-	    	//Calcultate new task end date with difference between origin proj end date and origin task end date
1412
-	    	if (!empty($clone_task->date_end))
1413
-	    	{
1411
+			//Calcultate new task end date with difference between origin proj end date and origin task end date
1412
+			if (!empty($clone_task->date_end))
1413
+			{
1414 1414
 				$clone_task->date_end			= $now + $clone_task->date_end - $orign_project_dt_start;
1415
-	    	}
1415
+			}
1416 1416
 
1417
-        }
1417
+		}
1418 1418
 
1419 1419
 		if (!$clone_prog)
1420
-        {
1421
-        	    $clone_task->progress=0;
1422
-        }
1420
+		{
1421
+				$clone_task->progress=0;
1422
+		}
1423 1423
 
1424 1424
 		// Create clone
1425 1425
 		$result=$clone_task->create($user);
@@ -1437,15 +1437,15 @@  discard block
 block discarded – undo
1437 1437
 			$clone_task_id=$clone_task->id;
1438 1438
 			$clone_task_ref = $clone_task->ref;
1439 1439
 
1440
-       		//Note Update
1440
+	   		//Note Update
1441 1441
 			if (!$clone_note)
1442
-       		{
1443
-        	    $clone_task->note_private='';
1444
-    			$clone_task->note_public='';
1445
-        	}
1446
-        	else
1447
-        	{
1448
-        		$this->db->begin();
1442
+	   		{
1443
+				$clone_task->note_private='';
1444
+				$clone_task->note_public='';
1445
+			}
1446
+			else
1447
+			{
1448
+				$this->db->begin();
1449 1449
 				$res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES),'_public');
1450 1450
 				if ($res < 0)
1451 1451
 				{
@@ -1470,7 +1470,7 @@  discard block
 block discarded – undo
1470 1470
 				{
1471 1471
 					$this->db->commit();
1472 1472
 				}
1473
-        	}
1473
+			}
1474 1474
 
1475 1475
 			//Duplicate file
1476 1476
 			if ($clone_file)
@@ -1479,18 +1479,18 @@  discard block
 block discarded – undo
1479 1479
 
1480 1480
 				//retreive project origin ref to know folder to copy
1481 1481
 				$projectstatic=new Project($this->db);
1482
-	        	$projectstatic->fetch($ori_project_id);
1483
-	        	$ori_project_ref=$projectstatic->ref;
1484
-
1485
-	        	if ($ori_project_id!=$project_id)
1486
-	        	{
1487
-	        		$projectstatic->fetch($project_id);
1488
-	        		$clone_project_ref=$projectstatic->ref;
1489
-	        	}
1490
-	        	else
1491
-	        	{
1492
-	        		$clone_project_ref=$ori_project_ref;
1493
-	        	}
1482
+				$projectstatic->fetch($ori_project_id);
1483
+				$ori_project_ref=$projectstatic->ref;
1484
+
1485
+				if ($ori_project_id!=$project_id)
1486
+				{
1487
+					$projectstatic->fetch($project_id);
1488
+					$clone_project_ref=$projectstatic->ref;
1489
+				}
1490
+				else
1491
+				{
1492
+					$clone_project_ref=$ori_project_ref;
1493
+				}
1494 1494
 
1495 1495
 				$clone_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($clone_project_ref). "/" . dol_sanitizeFileName($clone_task_ref);
1496 1496
 				$ori_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($ori_project_ref). "/" . dol_sanitizeFileName($fromid);
@@ -1657,8 +1657,8 @@  discard block
 block discarded – undo
1657 1657
 			if ($statut==3) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1658 1658
 			if ($statut==4) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1659 1659
 			if ($statut==5) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut5');*/
1660
-		    //return $this->progress.' %';
1661
-		    return '&nbsp;';
1660
+			//return $this->progress.' %';
1661
+			return '&nbsp;';
1662 1662
 		}
1663 1663
 	}
1664 1664
 
@@ -1820,16 +1820,16 @@  discard block
 block discarded – undo
1820 1820
 	 */
1821 1821
 	public function hasDelay()
1822 1822
 	{
1823
-	    global $conf;
1823
+		global $conf;
1824 1824
 
1825
-        if (! ($this->progress >= 0 && $this->progress < 100)) {
1826
-            return false;
1827
-        }
1825
+		if (! ($this->progress >= 0 && $this->progress < 100)) {
1826
+			return false;
1827
+		}
1828 1828
 
1829
-        $now = dol_now();
1829
+		$now = dol_now();
1830 1830
 
1831
-        $datetouse = ($this->date_end > 0) ? $this->date_end : ($this->datee > 0 ? $this->datee : 0);
1831
+		$datetouse = ($this->date_end > 0) ? $this->date_end : ($this->datee > 0 ? $this->datee : 0);
1832 1832
 
1833
-        return ($datetouse > 0 && ($datetouse < ($now - $conf->projet->task->warning_delay)));
1833
+		return ($datetouse > 0 && ($datetouse < ($now - $conf->projet->task->warning_delay)));
1834 1834
 	}
1835 1835
 }
1836 1836
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +529 added lines, -529 removed lines patch added patch discarded remove patch
@@ -31,16 +31,16 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class Task extends CommonObject
33 33
 {
34
-    public $element='project_task';		//!< Id that identify managed objects
35
-    public $table_element='projet_task';	//!< Name of table without prefix where object is stored
36
-    public $fk_element='fk_task';
34
+    public $element = 'project_task'; //!< Id that identify managed objects
35
+    public $table_element = 'projet_task'; //!< Name of table without prefix where object is stored
36
+    public $fk_element = 'fk_task';
37 37
     public $picto = 'task';
38
-    protected $childtables=array('projet_task_time','projet_task_comment');    // To test if we can delete object
38
+    protected $childtables = array('projet_task_time', 'projet_task_comment'); // To test if we can delete object
39 39
 
40 40
     var $fk_task_parent;
41 41
     var $label;
42 42
     var $description;
43
-    var $duration_effective;		// total of time spent on this task
43
+    var $duration_effective; // total of time spent on this task
44 44
     var $planned_workload;
45 45
     var $date_c;
46 46
     var $date_start;
@@ -65,8 +65,8 @@  discard block
 block discarded – undo
65 65
     var $timespent_duration;
66 66
     var $timespent_old_duration;
67 67
     var $timespent_date;
68
-    var $timespent_datehour;		// More accurate start date (same than timespent_date but includes hours, minutes and seconds)
69
-    var $timespent_withhour;		// 1 = we entered also start hours for timesheet line
68
+    var $timespent_datehour; // More accurate start date (same than timespent_date but includes hours, minutes and seconds)
69
+    var $timespent_withhour; // 1 = we entered also start hours for timesheet line
70 70
     var $timespent_fk_user;
71 71
     var $timespent_note;
72 72
 
@@ -93,11 +93,11 @@  discard block
 block discarded – undo
93 93
      *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
94 94
      *  @return int 		        	<0 if KO, Id of created object if OK
95 95
      */
96
-    function create($user, $notrigger=0)
96
+    function create($user, $notrigger = 0)
97 97
     {
98 98
         global $conf, $langs;
99 99
 
100
-        $error=0;
100
+        $error = 0;
101 101
 
102 102
         // Clean parameters
103 103
         $this->label = trim($this->label);
@@ -108,56 +108,56 @@  discard block
 block discarded – undo
108 108
 
109 109
         // Insert request
110 110
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
111
-        $sql.= "fk_projet";
112
-		$sql.= ", ref";
113
-        $sql.= ", fk_task_parent";
114
-        $sql.= ", label";
115
-        $sql.= ", description";
116
-        $sql.= ", datec";
117
-        $sql.= ", fk_user_creat";
118
-        $sql.= ", dateo";
119
-        $sql.= ", datee";
120
-        $sql.= ", planned_workload";
121
-        $sql.= ", progress";
122
-        $sql.= ") VALUES (";
123
-        $sql.= $this->fk_project;
124
-		$sql.= ", ".(!empty($this->ref)?"'".$this->db->escape($this->ref)."'":'null');
125
-        $sql.= ", ".$this->fk_task_parent;
126
-        $sql.= ", '".$this->db->escape($this->label)."'";
127
-        $sql.= ", '".$this->db->escape($this->description)."'";
128
-        $sql.= ", '".$this->db->idate($this->date_c)."'";
129
-        $sql.= ", ".$user->id;
130
-        $sql.= ", ".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null');
131
-        $sql.= ", ".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null');
132
-        $sql.= ", ".(($this->planned_workload!='' && $this->planned_workload >= 0)?$this->planned_workload:'null');
133
-        $sql.= ", ".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null');
134
-        $sql.= ")";
111
+        $sql .= "fk_projet";
112
+		$sql .= ", ref";
113
+        $sql .= ", fk_task_parent";
114
+        $sql .= ", label";
115
+        $sql .= ", description";
116
+        $sql .= ", datec";
117
+        $sql .= ", fk_user_creat";
118
+        $sql .= ", dateo";
119
+        $sql .= ", datee";
120
+        $sql .= ", planned_workload";
121
+        $sql .= ", progress";
122
+        $sql .= ") VALUES (";
123
+        $sql .= $this->fk_project;
124
+		$sql .= ", ".(!empty($this->ref) ? "'".$this->db->escape($this->ref)."'" : 'null');
125
+        $sql .= ", ".$this->fk_task_parent;
126
+        $sql .= ", '".$this->db->escape($this->label)."'";
127
+        $sql .= ", '".$this->db->escape($this->description)."'";
128
+        $sql .= ", '".$this->db->idate($this->date_c)."'";
129
+        $sql .= ", ".$user->id;
130
+        $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
131
+        $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
132
+        $sql .= ", ".(($this->planned_workload != '' && $this->planned_workload >= 0) ? $this->planned_workload : 'null');
133
+        $sql .= ", ".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null');
134
+        $sql .= ")";
135 135
 
136 136
         $this->db->begin();
137 137
 
138 138
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
139
-        $resql=$this->db->query($sql);
140
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
139
+        $resql = $this->db->query($sql);
140
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
141 141
 
142
-        if (! $error)
142
+        if (!$error)
143 143
         {
144 144
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task");
145 145
 
146
-            if (! $notrigger)
146
+            if (!$notrigger)
147 147
             {
148 148
                 // Call trigger
149
-                $result=$this->call_trigger('TASK_CREATE',$user);
149
+                $result = $this->call_trigger('TASK_CREATE', $user);
150 150
                 if ($result < 0) { $error++; }
151 151
                 // End call triggers
152 152
             }
153 153
         }
154 154
 
155 155
         // Update extrafield
156
-        if (! $error)
156
+        if (!$error)
157 157
         {
158 158
         	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
159 159
         	{
160
-        		$result=$this->insertExtraFields();
160
+        		$result = $this->insertExtraFields();
161 161
         		if ($result < 0)
162 162
         		{
163 163
         			$error++;
@@ -168,13 +168,13 @@  discard block
 block discarded – undo
168 168
         // Commit or rollback
169 169
         if ($error)
170 170
         {
171
-            foreach($this->errors as $errmsg)
171
+            foreach ($this->errors as $errmsg)
172 172
             {
173 173
                 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
174
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
174
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
175 175
             }
176 176
             $this->db->rollback();
177
-            return -1*$error;
177
+            return -1 * $error;
178 178
         }
179 179
         else
180 180
         {
@@ -191,40 +191,40 @@  discard block
 block discarded – undo
191 191
      *  @param	int		$ref		ref object
192 192
      *  @return int 		        <0 if KO, 0 if not found, >0 if OK
193 193
      */
194
-    function fetch($id,$ref='')
194
+    function fetch($id, $ref = '')
195 195
     {
196 196
         global $langs;
197 197
 
198 198
         $sql = "SELECT";
199
-        $sql.= " t.rowid,";
200
-		$sql.= " t.ref,";
201
-        $sql.= " t.fk_projet,";
202
-        $sql.= " t.fk_task_parent,";
203
-        $sql.= " t.label,";
204
-        $sql.= " t.description,";
205
-        $sql.= " t.duration_effective,";
206
-        $sql.= " t.planned_workload,";
207
-        $sql.= " t.datec,";
208
-        $sql.= " t.dateo,";
209
-        $sql.= " t.datee,";
210
-        $sql.= " t.fk_user_creat,";
211
-        $sql.= " t.fk_user_valid,";
212
-        $sql.= " t.fk_statut,";
213
-        $sql.= " t.progress,";
214
-        $sql.= " t.priority,";
215
-        $sql.= " t.note_private,";
216
-		$sql.= " t.note_public,";
217
-		$sql.= " t.rang";
218
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as t";
219
-        $sql.= " WHERE ";
199
+        $sql .= " t.rowid,";
200
+		$sql .= " t.ref,";
201
+        $sql .= " t.fk_projet,";
202
+        $sql .= " t.fk_task_parent,";
203
+        $sql .= " t.label,";
204
+        $sql .= " t.description,";
205
+        $sql .= " t.duration_effective,";
206
+        $sql .= " t.planned_workload,";
207
+        $sql .= " t.datec,";
208
+        $sql .= " t.dateo,";
209
+        $sql .= " t.datee,";
210
+        $sql .= " t.fk_user_creat,";
211
+        $sql .= " t.fk_user_valid,";
212
+        $sql .= " t.fk_statut,";
213
+        $sql .= " t.progress,";
214
+        $sql .= " t.priority,";
215
+        $sql .= " t.note_private,";
216
+		$sql .= " t.note_public,";
217
+		$sql .= " t.rang";
218
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t";
219
+        $sql .= " WHERE ";
220 220
         if (!empty($ref)) {
221
-        	$sql.="t.ref = '".$this->db->escape($ref)."'";
222
-        }else {
223
-        	$sql.="t.rowid = ".$id;
221
+        	$sql .= "t.ref = '".$this->db->escape($ref)."'";
222
+        } else {
223
+        	$sql .= "t.rowid = ".$id;
224 224
         }
225 225
 
226 226
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
227
-        $resql=$this->db->query($sql);
227
+        $resql = $this->db->query($sql);
228 228
         if ($resql)
229 229
         {
230 230
             $num_rows = $this->db->num_rows($resql);
@@ -233,25 +233,25 @@  discard block
 block discarded – undo
233 233
             {
234 234
                 $obj = $this->db->fetch_object($resql);
235 235
 
236
-                $this->id					= $obj->rowid;
237
-				$this->ref					= $obj->ref;
238
-                $this->fk_project			= $obj->fk_projet;
239
-                $this->fk_task_parent		= $obj->fk_task_parent;
240
-                $this->label				= $obj->label;
241
-                $this->description			= $obj->description;
242
-                $this->duration_effective	= $obj->duration_effective;
243
-                $this->planned_workload		= $obj->planned_workload;
244
-                $this->date_c				= $this->db->jdate($obj->datec);
245
-                $this->date_start			= $this->db->jdate($obj->dateo);
236
+                $this->id = $obj->rowid;
237
+				$this->ref = $obj->ref;
238
+                $this->fk_project = $obj->fk_projet;
239
+                $this->fk_task_parent = $obj->fk_task_parent;
240
+                $this->label = $obj->label;
241
+                $this->description = $obj->description;
242
+                $this->duration_effective = $obj->duration_effective;
243
+                $this->planned_workload = $obj->planned_workload;
244
+                $this->date_c = $this->db->jdate($obj->datec);
245
+                $this->date_start = $this->db->jdate($obj->dateo);
246 246
                 $this->date_end				= $this->db->jdate($obj->datee);
247 247
                 $this->fk_user_creat		= $obj->fk_user_creat;
248 248
                 $this->fk_user_valid		= $obj->fk_user_valid;
249 249
                 $this->fk_statut			= $obj->fk_statut;
250 250
                 $this->progress				= $obj->progress;
251 251
                 $this->priority				= $obj->priority;
252
-                $this->note_private			= $obj->note_private;
253
-                $this->note_public			= $obj->note_public;
254
-				$this->rang					= $obj->rang;
252
+                $this->note_private = $obj->note_private;
253
+                $this->note_public = $obj->note_public;
254
+				$this->rang = $obj->rang;
255 255
 
256 256
                 // Retreive all extrafield for thirdparty
257 257
                	$this->fetch_optionals();
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
             if ($num_rows) {
263 263
             	$this->fetchComments();
264 264
             	return 1;
265
-            }else {
265
+            } else {
266 266
             	return 0;
267 267
             }
268 268
         }
269 269
         else
270 270
         {
271
-            $this->error="Error ".$this->db->lasterror();
271
+            $this->error = "Error ".$this->db->lasterror();
272 272
             return -1;
273 273
         }
274 274
     }
@@ -281,50 +281,50 @@  discard block
 block discarded – undo
281 281
      *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
282 282
      *  @return int			         	<=0 if KO, >0 if OK
283 283
      */
284
-    function update($user=null, $notrigger=0)
284
+    function update($user = null, $notrigger = 0)
285 285
     {
286 286
         global $conf, $langs;
287
-        $error=0;
287
+        $error = 0;
288 288
 
289 289
         // Clean parameters
290
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
291
-		if (isset($this->ref)) $this->ref=trim($this->ref);
292
-        if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent);
293
-        if (isset($this->label)) $this->label=trim($this->label);
294
-        if (isset($this->description)) $this->description=trim($this->description);
295
-        if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective);
296
-        if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload);
290
+        if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project);
291
+		if (isset($this->ref)) $this->ref = trim($this->ref);
292
+        if (isset($this->fk_task_parent)) $this->fk_task_parent = trim($this->fk_task_parent);
293
+        if (isset($this->label)) $this->label = trim($this->label);
294
+        if (isset($this->description)) $this->description = trim($this->description);
295
+        if (isset($this->duration_effective)) $this->duration_effective = trim($this->duration_effective);
296
+        if (isset($this->planned_workload)) $this->planned_workload = trim($this->planned_workload);
297 297
 
298 298
         // Check parameters
299 299
         // Put here code to add control on parameters values
300 300
 
301 301
         // Update request
302 302
         $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
303
-        $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
304
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"'".$this->db->escape($this->id)."'").",";
305
-        $sql.= " fk_task_parent=".(isset($this->fk_task_parent)?$this->fk_task_parent:"null").",";
306
-        $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
307
-        $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
308
-        $sql.= " duration_effective=".(isset($this->duration_effective)?$this->duration_effective:"null").",";
309
-        $sql.= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '')?$this->planned_workload:"null").",";
310
-        $sql.= " dateo=".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null').",";
311
-        $sql.= " datee=".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null').",";
312
-        $sql.= " progress=".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null').",";
313
-        $sql.= " rang=".((!empty($this->rang))?$this->rang:"0");
314
-        $sql.= " WHERE rowid=".$this->id;
303
+        $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
304
+		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "'".$this->db->escape($this->id)."'").",";
305
+        $sql .= " fk_task_parent=".(isset($this->fk_task_parent) ? $this->fk_task_parent : "null").",";
306
+        $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
307
+        $sql .= " description=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
308
+        $sql .= " duration_effective=".(isset($this->duration_effective) ? $this->duration_effective : "null").",";
309
+        $sql .= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '') ? $this->planned_workload : "null").",";
310
+        $sql .= " dateo=".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null').",";
311
+        $sql .= " datee=".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null').",";
312
+        $sql .= " progress=".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null').",";
313
+        $sql .= " rang=".((!empty($this->rang)) ? $this->rang : "0");
314
+        $sql .= " WHERE rowid=".$this->id;
315 315
 
316 316
         $this->db->begin();
317 317
 
318 318
         dol_syslog(get_class($this)."::update", LOG_DEBUG);
319 319
         $resql = $this->db->query($sql);
320
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
320
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
321 321
 
322
-        if (! $error)
322
+        if (!$error)
323 323
         {
324
-            if (! $notrigger)
324
+            if (!$notrigger)
325 325
             {
326 326
                 // Call trigger
327
-                $result=$this->call_trigger('TASK_MODIFY',$user);
327
+                $result = $this->call_trigger('TASK_MODIFY', $user);
328 328
                 if ($result < 0) { $error++; }
329 329
                 // End call triggers
330 330
             }
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
         if (!$error) {
335 335
         	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
336 336
         	{
337
-        		$result=$this->insertExtraFields();
337
+        		$result = $this->insertExtraFields();
338 338
         		if ($result < 0)
339 339
         		{
340 340
         			$error++;
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
         	}
343 343
         }
344 344
 
345
-        if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref))
345
+        if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref))
346 346
         {
347 347
             // We remove directory
348 348
             if ($conf->projet->dir_output)
@@ -354,12 +354,12 @@  discard block
 block discarded – undo
354 354
                 $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref);
355 355
                 if (file_exists($olddir))
356 356
                 {
357
-                    include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
358
-                    $res=dol_move($olddir, $newdir);
359
-                    if (! $res)
357
+                    include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
358
+                    $res = dol_move($olddir, $newdir);
359
+                    if (!$res)
360 360
                     {
361 361
                         $langs->load("errors");
362
-                        $this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir);
362
+                        $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
363 363
                         $error++;
364 364
                     }
365 365
                 }
@@ -369,13 +369,13 @@  discard block
 block discarded – undo
369 369
         // Commit or rollback
370 370
         if ($error)
371 371
         {
372
-            foreach($this->errors as $errmsg)
372
+            foreach ($this->errors as $errmsg)
373 373
             {
374 374
                 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
375
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
375
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
376 376
             }
377 377
             $this->db->rollback();
378
-            return -1*$error;
378
+            return -1 * $error;
379 379
         }
380 380
         else
381 381
         {
@@ -392,79 +392,79 @@  discard block
 block discarded – undo
392 392
      *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
393 393
      *	@return	int						<0 if KO, >0 if OK
394 394
      */
395
-    function delete($user, $notrigger=0)
395
+    function delete($user, $notrigger = 0)
396 396
     {
397 397
 
398 398
         global $conf, $langs;
399
-        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
399
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
400 400
 
401
-        $error=0;
401
+        $error = 0;
402 402
 
403 403
         $this->db->begin();
404 404
 
405 405
         if ($this->hasChildren() > 0)
406 406
         {
407 407
             dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING);
408
-            $this->error='ErrorRecordHasSubTasks';
408
+            $this->error = 'ErrorRecordHasSubTasks';
409 409
             $this->db->rollback();
410 410
             return 0;
411 411
         }
412 412
 
413 413
         $objectisused = $this->isObjectUsed($this->id);
414
-        if (! empty($objectisused))
414
+        if (!empty($objectisused))
415 415
         {
416 416
             dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING);
417
-            $this->error='ErrorRecordHasChildren';
417
+            $this->error = 'ErrorRecordHasChildren';
418 418
             $this->db->rollback();
419 419
             return 0;
420 420
         }
421 421
 
422
-        if (! $error)
422
+        if (!$error)
423 423
         {
424 424
             // Delete linked contacts
425 425
             $res = $this->delete_linked_contact();
426 426
             if ($res < 0)
427 427
             {
428
-                $this->error='ErrorFailToDeleteLinkedContact';
428
+                $this->error = 'ErrorFailToDeleteLinkedContact';
429 429
                 //$error++;
430 430
                 $this->db->rollback();
431 431
                 return 0;
432 432
             }
433 433
         }
434 434
 
435
-        if (! $error)
435
+        if (!$error)
436 436
         {
437 437
 	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
438
-	        $sql.= " WHERE fk_task=".$this->id;
438
+	        $sql .= " WHERE fk_task=".$this->id;
439 439
 
440 440
 	        $resql = $this->db->query($sql);
441
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
441
+	        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
442 442
         }
443 443
 
444
-        if (! $error)
444
+        if (!$error)
445 445
         {
446 446
 	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields";
447
-	        $sql.= " WHERE fk_object=".$this->id;
447
+	        $sql .= " WHERE fk_object=".$this->id;
448 448
 
449 449
 	        $resql = $this->db->query($sql);
450
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
450
+	        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
451 451
         }
452 452
 
453
-        if (! $error)
453
+        if (!$error)
454 454
         {
455 455
 	        $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task";
456
-	        $sql.= " WHERE rowid=".$this->id;
456
+	        $sql .= " WHERE rowid=".$this->id;
457 457
 
458 458
 	        $resql = $this->db->query($sql);
459
-	        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
459
+	        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
460 460
         }
461 461
 
462
-        if (! $error)
462
+        if (!$error)
463 463
         {
464
-            if (! $notrigger)
464
+            if (!$notrigger)
465 465
             {
466 466
                 // Call trigger
467
-                $result=$this->call_trigger('TASK_DELETE',$user);
467
+                $result = $this->call_trigger('TASK_DELETE', $user);
468 468
                 if ($result < 0) { $error++; }
469 469
                 // End call triggers
470 470
             }
@@ -473,27 +473,27 @@  discard block
 block discarded – undo
473 473
         // Commit or rollback
474 474
         if ($error)
475 475
         {
476
-            foreach($this->errors as $errmsg)
476
+            foreach ($this->errors as $errmsg)
477 477
             {
478 478
                 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
479
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
479
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
480 480
             }
481 481
             $this->db->rollback();
482
-            return -1*$error;
482
+            return -1 * $error;
483 483
         }
484 484
         else
485 485
 		{
486 486
 			//Delete associated link file
487 487
 	        if ($conf->projet->dir_output)
488 488
 	        {
489
-	        	$projectstatic=new Project($this->db);
489
+	        	$projectstatic = new Project($this->db);
490 490
 	        	$projectstatic->fetch($this->fk_project);
491 491
 
492
-	            $dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($projectstatic->ref) . '/' . dol_sanitizeFileName($this->id);
492
+	            $dir = $conf->projet->dir_output."/".dol_sanitizeFileName($projectstatic->ref).'/'.dol_sanitizeFileName($this->id);
493 493
 	            dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG);
494 494
 	            if (file_exists($dir))
495 495
 	            {
496
-	            	require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
496
+	            	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
497 497
 	                $res = @dol_delete_dir_recursive($dir);
498 498
 	                if (!$res)
499 499
 	                {
@@ -517,24 +517,24 @@  discard block
 block discarded – undo
517 517
      */
518 518
     function hasChildren()
519 519
     {
520
-    	$error=0;
521
-        $ret=0;
520
+    	$error = 0;
521
+        $ret = 0;
522 522
 
523 523
         $sql = "SELECT COUNT(*) as nb";
524
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task";
525
-        $sql.= " WHERE fk_task_parent=".$this->id;
524
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task";
525
+        $sql .= " WHERE fk_task_parent=".$this->id;
526 526
 
527 527
         dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
528 528
         $resql = $this->db->query($sql);
529
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
529
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
530 530
         else
531 531
         {
532
-            $obj=$this->db->fetch_object($resql);
533
-            if ($obj) $ret=$obj->nb;
532
+            $obj = $this->db->fetch_object($resql);
533
+            if ($obj) $ret = $obj->nb;
534 534
             $this->db->free($resql);
535 535
         }
536 536
 
537
-        if (! $error)
537
+        if (!$error)
538 538
         {
539 539
             return $ret;
540 540
         }
@@ -551,24 +551,24 @@  discard block
 block discarded – undo
551 551
      */
552 552
     function hasTimeSpent()
553 553
     {
554
-    	$error=0;
555
-        $ret=0;
554
+    	$error = 0;
555
+        $ret = 0;
556 556
 
557 557
         $sql = "SELECT COUNT(*) as nb";
558
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time";
559
-        $sql.= " WHERE fk_task=".$this->id;
558
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time";
559
+        $sql .= " WHERE fk_task=".$this->id;
560 560
 
561 561
         dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
562 562
         $resql = $this->db->query($sql);
563
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
563
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
564 564
         else
565 565
         {
566
-            $obj=$this->db->fetch_object($resql);
567
-            if ($obj) $ret=$obj->nb;
566
+            $obj = $this->db->fetch_object($resql);
567
+            if ($obj) $ret = $obj->nb;
568 568
             $this->db->free($resql);
569 569
         }
570 570
 
571
-        if (! $error)
571
+        if (!$error)
572 572
         {
573 573
             return $ret;
574 574
         }
@@ -591,50 +591,50 @@  discard block
 block discarded – undo
591 591
      *  @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
592 592
      *	@return	string					Chaine avec URL
593 593
      */
594
-    function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1)
594
+    function getNomUrl($withpicto = 0, $option = '', $mode = 'task', $addlabel = 0, $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1)
595 595
     {
596 596
         global $conf, $langs, $user;
597 597
 
598
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
598
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
599 599
 
600
-        $result='';
601
-        $label = '<u>' . $langs->trans("ShowTask") . '</u>';
602
-        if (! empty($this->ref))
603
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
604
-        if (! empty($this->label))
605
-            $label .= '<br><b>' . $langs->trans('LabelTask') . ':</b> ' . $this->label;
600
+        $result = '';
601
+        $label = '<u>'.$langs->trans("ShowTask").'</u>';
602
+        if (!empty($this->ref))
603
+            $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
604
+        if (!empty($this->label))
605
+            $label .= '<br><b>'.$langs->trans('LabelTask').':</b> '.$this->label;
606 606
         if ($this->date_start || $this->date_end)
607 607
         {
608
-        	$label .= "<br>".get_date_range($this->date_start,$this->date_end,'',$langs,0);
608
+        	$label .= "<br>".get_date_range($this->date_start, $this->date_end, '', $langs, 0);
609 609
         }
610 610
 
611
-        $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':'');
611
+        $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option == 'withproject' ? '&withproject=1' : '');
612 612
         // Add param to save lastsearch_values or not
613
-        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
614
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
615
-        if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
613
+        $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
614
+        if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
615
+        if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
616 616
 
617 617
         $linkclose = '';
618 618
         if (empty($notooltip))
619 619
         {
620
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
620
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
621 621
             {
622
-                $label=$langs->trans("ShowTask");
623
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
622
+                $label = $langs->trans("ShowTask");
623
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
624 624
             }
625
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
626
-            $linkclose.=' class="classfortooltip"';
625
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
626
+            $linkclose .= ' class="classfortooltip"';
627 627
         }
628 628
 
629 629
         $linkstart = '<a href="'.$url.'"';
630
-        $linkstart.=$linkclose.'>';
631
-        $linkend='</a>';
630
+        $linkstart .= $linkclose.'>';
631
+        $linkend = '</a>';
632 632
 
633
-        $picto='projecttask';
633
+        $picto = 'projecttask';
634 634
 
635
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
636
-        if ($withpicto && $withpicto != 2) $result.=' ';
637
-        if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
635
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
636
+        if ($withpicto && $withpicto != 2) $result .= ' ';
637
+        if ($withpicto != 2) $result .= $linkstart.$this->ref.$linkend.(($addlabel && $this->label) ? $sep.dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
638 638
         return $result;
639 639
     }
640 640
 
@@ -647,17 +647,17 @@  discard block
 block discarded – undo
647 647
      */
648 648
     function initAsSpecimen()
649 649
     {
650
-        $this->id=0;
651
-
652
-        $this->fk_projet='';
653
-		$this->ref='TK01';
654
-        $this->fk_task_parent='';
655
-        $this->label='Specimen task TK01';
656
-        $this->duration_effective='';
657
-        $this->fk_user_creat='';
658
-        $this->progress='25';
659
-        $this->fk_statut='';
660
-        $this->note='This is a specimen task not';
650
+        $this->id = 0;
651
+
652
+        $this->fk_projet = '';
653
+		$this->ref = 'TK01';
654
+        $this->fk_task_parent = '';
655
+        $this->label = 'Specimen task TK01';
656
+        $this->duration_effective = '';
657
+        $this->fk_user_creat = '';
658
+        $this->progress = '25';
659
+        $this->fk_statut = '';
660
+        $this->note = 'This is a specimen task not';
661 661
     }
662 662
 
663 663
     /**
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
      * @param	string	$filterontaskuser	Filter on user assigned to task
677 677
      * @return 	array						Array of tasks
678 678
      */
679
-    function getTasksArray($usert=0, $userp=0, $projectid=0, $socid=0, $mode=0, $filteronprojref='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0)
679
+    function getTasksArray($usert = 0, $userp = 0, $projectid = 0, $socid = 0, $mode = 0, $filteronprojref = '', $filteronprojstatus = -1, $morewherefilter = '', $filteronprojuser = 0, $filterontaskuser = 0)
680 680
     {
681 681
         global $conf;
682 682
 
@@ -686,73 +686,73 @@  discard block
 block discarded – undo
686 686
 
687 687
         // List of tasks (does not care about permissions. Filtering will be done later)
688 688
         $sql = "SELECT p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,";
689
-        $sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
690
-        $sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,";
691
-        $sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name";
692
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
693
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
689
+        $sql .= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
690
+        $sql .= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,";
691
+        $sql .= " s.rowid as thirdparty_id, s.nom as thirdparty_name";
692
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
693
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
694 694
         if ($mode == 0)
695 695
         {
696 696
             if ($filteronprojuser > 0)
697 697
             {
698
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
699
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
698
+                $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
699
+                $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
700 700
             }
701
-            $sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
701
+            $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
702 702
             if ($filterontaskuser > 0)
703 703
             {
704
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
705
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
704
+                $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
705
+                $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
706 706
             }
707
-            $sql.= " WHERE p.entity IN (".getEntity('project').")";
708
-            $sql.= " AND t.fk_projet = p.rowid";
707
+            $sql .= " WHERE p.entity IN (".getEntity('project').")";
708
+            $sql .= " AND t.fk_projet = p.rowid";
709 709
         }
710 710
         elseif ($mode == 1)
711 711
         {
712 712
             if ($filteronprojuser > 0)
713 713
             {
714
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
715
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
714
+                $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
715
+                $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
716 716
             }
717 717
             if ($filterontaskuser > 0)
718 718
             {
719
-                $sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
720
-                $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
721
-                $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
719
+                $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
720
+                $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
721
+                $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
722 722
             }
723 723
             else
724 724
             {
725
-                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
725
+                $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
726 726
             }
727
-            $sql.= " WHERE p.entity IN (".getEntity('project').")";
727
+            $sql .= " WHERE p.entity IN (".getEntity('project').")";
728 728
         }
729 729
         else return 'BadValueForParameterMode';
730 730
 
731 731
         if ($filteronprojuser > 0)
732 732
         {
733
-            $sql.= " AND p.rowid = ec.element_id";
734
-            $sql.= " AND ctc.rowid = ec.fk_c_type_contact";
735
-            $sql.= " AND ctc.element = 'project'";
736
-            $sql.= " AND ec.fk_socpeople = ".$filteronprojuser;
737
-            $sql.= " AND ec.statut = 4";
738
-            $sql.= " AND ctc.source = 'internal'";
733
+            $sql .= " AND p.rowid = ec.element_id";
734
+            $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
735
+            $sql .= " AND ctc.element = 'project'";
736
+            $sql .= " AND ec.fk_socpeople = ".$filteronprojuser;
737
+            $sql .= " AND ec.statut = 4";
738
+            $sql .= " AND ctc.source = 'internal'";
739 739
         }
740 740
         if ($filterontaskuser > 0)
741 741
         {
742
-            $sql.= " AND t.fk_projet = p.rowid";
743
-            $sql.= " AND p.rowid = ec2.element_id";
744
-            $sql.= " AND ctc2.rowid = ec2.fk_c_type_contact";
745
-            $sql.= " AND ctc2.element = 'project_task'";
746
-            $sql.= " AND ec2.fk_socpeople = ".$filterontaskuser;
747
-            $sql.= " AND ec2.statut = 4";
748
-            $sql.= " AND ctc2.source = 'internal'";
749
-        }
750
-        if ($socid)	$sql.= " AND p.fk_soc = ".$socid;
751
-        if ($projectid) $sql.= " AND p.rowid in (".$projectid.")";
752
-        if ($filteronprojref) $sql.= " AND p.ref LIKE '%".$filteronprojref."%'";
753
-        if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus;
754
-        if ($morewherefilter) $sql.=$morewherefilter;
755
-        $sql.= " ORDER BY p.ref, t.rang, t.dateo";
742
+            $sql .= " AND t.fk_projet = p.rowid";
743
+            $sql .= " AND p.rowid = ec2.element_id";
744
+            $sql .= " AND ctc2.rowid = ec2.fk_c_type_contact";
745
+            $sql .= " AND ctc2.element = 'project_task'";
746
+            $sql .= " AND ec2.fk_socpeople = ".$filterontaskuser;
747
+            $sql .= " AND ec2.statut = 4";
748
+            $sql .= " AND ctc2.source = 'internal'";
749
+        }
750
+        if ($socid)	$sql .= " AND p.fk_soc = ".$socid;
751
+        if ($projectid) $sql .= " AND p.rowid in (".$projectid.")";
752
+        if ($filteronprojref) $sql .= " AND p.ref LIKE '%".$filteronprojref."%'";
753
+        if ($filteronprojstatus > -1) $sql .= " AND p.fk_statut = ".$filteronprojstatus;
754
+        if ($morewherefilter) $sql .= $morewherefilter;
755
+        $sql .= " ORDER BY p.ref, t.rang, t.dateo";
756 756
 
757 757
         //print $sql;exit;
758 758
         dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG);
@@ -764,49 +764,49 @@  discard block
 block discarded – undo
764 764
             // Loop on each record found, so each couple (project id, task id)
765 765
             while ($i < $num)
766 766
             {
767
-                $error=0;
767
+                $error = 0;
768 768
 
769 769
                 $obj = $this->db->fetch_object($resql);
770 770
 
771
-                if ((! $obj->public) && (is_object($userp)))	// If not public project and we ask a filter on project owned by a user
771
+                if ((!$obj->public) && (is_object($userp)))	// If not public project and we ask a filter on project owned by a user
772 772
                 {
773
-                    if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
773
+                    if (!$this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
774 774
                     {
775 775
                         $error++;
776 776
                     }
777 777
                 }
778 778
                 if (is_object($usert))							// If we ask a filter on a user affected to a task
779 779
                 {
780
-                    if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
780
+                    if (!$this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
781 781
                     {
782 782
                         $error++;
783 783
                     }
784 784
                 }
785 785
 
786
-                if (! $error)
786
+                if (!$error)
787 787
                 {
788 788
 					$tasks[$i] = new Task($this->db);
789
-                    $tasks[$i]->id				= $obj->taskid;
790
-					$tasks[$i]->ref				= $obj->taskref;
789
+                    $tasks[$i]->id = $obj->taskid;
790
+					$tasks[$i]->ref = $obj->taskref;
791 791
                     $tasks[$i]->fk_project		= $obj->projectid;
792 792
                     $tasks[$i]->projectref		= $obj->ref;
793 793
                     $tasks[$i]->projectlabel	= $obj->plabel;
794
-                    $tasks[$i]->projectstatus	= $obj->projectstatus;
795
-                    $tasks[$i]->label			= $obj->label;
794
+                    $tasks[$i]->projectstatus = $obj->projectstatus;
795
+                    $tasks[$i]->label = $obj->label;
796 796
                     $tasks[$i]->description		= $obj->description;
797
-                    $tasks[$i]->fk_parent		= $obj->fk_task_parent;      // deprecated
798
-                    $tasks[$i]->fk_task_parent	= $obj->fk_task_parent;
797
+                    $tasks[$i]->fk_parent = $obj->fk_task_parent; // deprecated
798
+                    $tasks[$i]->fk_task_parent = $obj->fk_task_parent;
799 799
                     $tasks[$i]->duration		= $obj->duration_effective;
800
-                    $tasks[$i]->planned_workload= $obj->planned_workload;
800
+                    $tasks[$i]->planned_workload = $obj->planned_workload;
801 801
                     $tasks[$i]->progress		= $obj->progress;
802
-                    $tasks[$i]->fk_statut		= $obj->status;
803
-                    $tasks[$i]->public			= $obj->public;
804
-                    $tasks[$i]->date_start		= $this->db->jdate($obj->date_start);
802
+                    $tasks[$i]->fk_statut = $obj->status;
803
+                    $tasks[$i]->public = $obj->public;
804
+                    $tasks[$i]->date_start = $this->db->jdate($obj->date_start);
805 805
                     $tasks[$i]->date_end		= $this->db->jdate($obj->date_end);
806 806
                     $tasks[$i]->rang	   		= $obj->rang;
807 807
 
808
-                    $tasks[$i]->thirdparty_id	= $obj->thirdparty_id;
809
-                    $tasks[$i]->thirdparty_name	= $obj->thirdparty_name;
808
+                    $tasks[$i]->thirdparty_id = $obj->thirdparty_id;
809
+                    $tasks[$i]->thirdparty_name = $obj->thirdparty_name;
810 810
                 }
811 811
 
812 812
                 $i++;
@@ -831,7 +831,7 @@  discard block
 block discarded – undo
831 831
      * @param	integer	$filteronprojstatus	  Filter on project status if userp is set. Not used if userp not defined.
832 832
      * @return 	array					      Array (projectid => 'list of roles for project' or taskid => 'list of roles for task')
833 833
      */
834
-    function getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1)
834
+    function getUserRolesForProjectsOrTasks($userp, $usert, $projectid = '', $taskid = 0, $filteronprojstatus = -1)
835 835
     {
836 836
         $arrayroles = array();
837 837
 
@@ -840,41 +840,41 @@  discard block
 block discarded – undo
840 840
         // We want role of user for a projet or role of user for a task. Both are not possible.
841 841
         if (empty($userp) && empty($usert))
842 842
         {
843
-            $this->error="CallWithWrongParameters";
843
+            $this->error = "CallWithWrongParameters";
844 844
             return -1;
845 845
         }
846
-        if (! empty($userp) && ! empty($usert))
846
+        if (!empty($userp) && !empty($usert))
847 847
         {
848
-            $this->error="CallWithWrongParameters";
848
+            $this->error = "CallWithWrongParameters";
849 849
             return -1;
850 850
         }
851 851
 
852 852
         /* Liste des taches et role sur les projets ou taches */
853 853
         $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source";
854
-        if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt";
855
-        if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
856
-        if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
857
-        $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
858
-        $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
859
-        $sql.= " WHERE pt.rowid = ec.element_id";
860
-        if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus;
861
-        if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
862
-        if ($userp) $sql.= " AND ctc.element = 'project'";
863
-        if ($usert) $sql.= " AND ctc.element = 'project_task'";
864
-        $sql.= " AND ctc.rowid = ec.fk_c_type_contact";
865
-        if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id;
866
-        if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id;
867
-        $sql.= " AND ec.statut = 4";
868
-        $sql.= " AND ctc.source = 'internal'";
854
+        if ($userp) $sql .= " FROM ".MAIN_DB_PREFIX."projet as pt";
855
+        if ($usert && $filteronprojstatus > -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
856
+        if ($usert && $filteronprojstatus <= -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
857
+        $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
858
+        $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
859
+        $sql .= " WHERE pt.rowid = ec.element_id";
860
+        if ($userp && $filteronprojstatus > -1) $sql .= " AND pt.fk_statut = ".$filteronprojstatus;
861
+        if ($usert && $filteronprojstatus > -1) $sql .= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
862
+        if ($userp) $sql .= " AND ctc.element = 'project'";
863
+        if ($usert) $sql .= " AND ctc.element = 'project_task'";
864
+        $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
865
+        if ($userp) $sql .= " AND ec.fk_socpeople = ".$userp->id;
866
+        if ($usert) $sql .= " AND ec.fk_socpeople = ".$usert->id;
867
+        $sql .= " AND ec.statut = 4";
868
+        $sql .= " AND ctc.source = 'internal'";
869 869
         if ($projectid)
870 870
         {
871
-            if ($userp) $sql.= " AND pt.rowid in (".$projectid.")";
872
-            if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")";
871
+            if ($userp) $sql .= " AND pt.rowid in (".$projectid.")";
872
+            if ($usert) $sql .= " AND pt.fk_projet in (".$projectid.")";
873 873
         }
874 874
         if ($taskid)
875 875
         {
876
-            if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS";
877
-            if ($usert) $sql.= " AND pt.rowid = ".$taskid;
876
+            if ($userp) $sql .= " ERROR SHOULD NOT HAPPENS";
877
+            if ($usert) $sql .= " AND pt.rowid = ".$taskid;
878 878
         }
879 879
         //print $sql;
880 880
 
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
             {
889 889
                 $obj = $this->db->fetch_object($resql);
890 890
                 if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code;
891
-                else $arrayroles[$obj->pid].=','.$obj->code;
891
+                else $arrayroles[$obj->pid] .= ','.$obj->code;
892 892
                 $i++;
893 893
             }
894 894
             $this->db->free($resql);
@@ -908,12 +908,12 @@  discard block
 block discarded – undo
908 908
      *	@param	string	$source		Source
909 909
      *  @return array				Array of id of contacts
910 910
      */
911
-    function getListContactId($source='internal')
911
+    function getListContactId($source = 'internal')
912 912
     {
913 913
         $contactAlreadySelected = array();
914
-        $tab = $this->liste_contact(-1,$source);
914
+        $tab = $this->liste_contact(-1, $source);
915 915
         //var_dump($tab);
916
-        $num=count($tab);
916
+        $num = count($tab);
917 917
         $i = 0;
918 918
         while ($i < $num)
919 919
         {
@@ -932,18 +932,18 @@  discard block
 block discarded – undo
932 932
      *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
933 933
      *  @return	int                     <=0 if KO, >0 if OK
934 934
      */
935
-    function addTimeSpent($user, $notrigger=0)
935
+    function addTimeSpent($user, $notrigger = 0)
936 936
     {
937
-        global $conf,$langs;
937
+        global $conf, $langs;
938 938
 
939 939
         dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
940 940
 
941 941
         $ret = 0;
942 942
 
943 943
         // Check parameters
944
-        if (! is_object($user))
944
+        if (!is_object($user))
945 945
         {
946
-        	dol_print_error('',"Method addTimeSpent was called with wrong parameter user");
946
+        	dol_print_error('', "Method addTimeSpent was called with wrong parameter user");
947 947
         	return -1;
948 948
         }
949 949
 
@@ -954,41 +954,41 @@  discard block
 block discarded – undo
954 954
         $this->db->begin();
955 955
 
956 956
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time (";
957
-        $sql.= "fk_task";
958
-        $sql.= ", task_date";
959
-        $sql.= ", task_datehour";
960
-        $sql.= ", task_date_withhour";
961
-        $sql.= ", task_duration";
962
-        $sql.= ", fk_user";
963
-        $sql.= ", note";
964
-        $sql.= ") VALUES (";
965
-        $sql.= $this->id;
966
-        $sql.= ", '".$this->db->idate($this->timespent_date)."'";
967
-        $sql.= ", '".$this->db->idate($this->timespent_datehour)."'";
968
-        $sql.= ", ".(empty($this->timespent_withhour)?0:1);
969
-        $sql.= ", ".$this->timespent_duration;
970
-        $sql.= ", ".$this->timespent_fk_user;
971
-        $sql.= ", ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
972
-        $sql.= ")";
973
-
974
-        $resql=$this->db->query($sql);
957
+        $sql .= "fk_task";
958
+        $sql .= ", task_date";
959
+        $sql .= ", task_datehour";
960
+        $sql .= ", task_date_withhour";
961
+        $sql .= ", task_duration";
962
+        $sql .= ", fk_user";
963
+        $sql .= ", note";
964
+        $sql .= ") VALUES (";
965
+        $sql .= $this->id;
966
+        $sql .= ", '".$this->db->idate($this->timespent_date)."'";
967
+        $sql .= ", '".$this->db->idate($this->timespent_datehour)."'";
968
+        $sql .= ", ".(empty($this->timespent_withhour) ? 0 : 1);
969
+        $sql .= ", ".$this->timespent_duration;
970
+        $sql .= ", ".$this->timespent_fk_user;
971
+        $sql .= ", ".(isset($this->timespent_note) ? "'".$this->db->escape($this->timespent_note)."'" : "null");
972
+        $sql .= ")";
973
+
974
+        $resql = $this->db->query($sql);
975 975
         if ($resql)
976 976
         {
977 977
             $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time");
978 978
             $ret = $tasktime_id;
979 979
 			$this->timespent_id = $ret;
980 980
 
981
-            if (! $notrigger)
981
+            if (!$notrigger)
982 982
             {
983 983
                 // Call trigger
984
-                $result=$this->call_trigger('TASK_TIMESPENT_CREATE',$user);
985
-                if ($result < 0) { $ret=-1; }
984
+                $result = $this->call_trigger('TASK_TIMESPENT_CREATE', $user);
985
+                if ($result < 0) { $ret = -1; }
986 986
                 // End call triggers
987 987
             }
988 988
         }
989 989
         else
990 990
 		{
991
-            $this->error=$this->db->lasterror();
991
+            $this->error = $this->db->lasterror();
992 992
             $ret = -1;
993 993
         }
994 994
 
@@ -996,30 +996,30 @@  discard block
 block discarded – undo
996 996
         {
997 997
         	// Recalculate amount of time spent for task and update denormalized field
998 998
             $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
999
-            $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
1000
-			if (isset($this->progress)) $sql.= ", progress = " . $this->progress;	// Do not overwrite value if not provided
1001
-            $sql.= " WHERE rowid = ".$this->id;
999
+            $sql .= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
1000
+			if (isset($this->progress)) $sql .= ", progress = ".$this->progress; // Do not overwrite value if not provided
1001
+            $sql .= " WHERE rowid = ".$this->id;
1002 1002
 
1003 1003
             dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1004
-            if (! $this->db->query($sql) )
1004
+            if (!$this->db->query($sql))
1005 1005
             {
1006
-                $this->error=$this->db->lasterror();
1006
+                $this->error = $this->db->lasterror();
1007 1007
                 $ret = -2;
1008 1008
             }
1009 1009
 
1010 1010
             $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time";
1011
-            $sql.= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")";	// set average hour rate of user
1012
-            $sql.= " WHERE rowid = ".$tasktime_id;
1011
+            $sql .= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")"; // set average hour rate of user
1012
+            $sql .= " WHERE rowid = ".$tasktime_id;
1013 1013
 
1014 1014
             dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1015
-            if (! $this->db->query($sql) )
1015
+            if (!$this->db->query($sql))
1016 1016
             {
1017
-                $this->error=$this->db->lasterror();
1017
+                $this->error = $this->db->lasterror();
1018 1018
                 $ret = -2;
1019 1019
             }
1020 1020
         }
1021 1021
 
1022
-        if ($ret >0)
1022
+        if ($ret > 0)
1023 1023
         {
1024 1024
         	$this->db->commit();
1025 1025
         }
@@ -1036,46 +1036,46 @@  discard block
 block discarded – undo
1036 1036
      *  @param  int     $userid     Filter on user id. 0=No filter
1037 1037
      *  @return array		        Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull')
1038 1038
      */
1039
-    function getSummaryOfTimeSpent($userid=0)
1039
+    function getSummaryOfTimeSpent($userid = 0)
1040 1040
     {
1041 1041
         global $langs;
1042 1042
 
1043
-        $id=$this->id;
1043
+        $id = $this->id;
1044 1044
         if (empty($id))
1045 1045
         {
1046 1046
             dol_syslog("getSummaryOfTimeSpent called on a not loaded task", LOG_ERR);
1047 1047
             return -1;
1048 1048
         }
1049 1049
 
1050
-        $result=array();
1050
+        $result = array();
1051 1051
 
1052 1052
         $sql = "SELECT";
1053
-        $sql.= " MIN(t.task_datehour) as min_date,";
1054
-        $sql.= " MAX(t.task_datehour) as max_date,";
1055
-        $sql.= " SUM(t.task_duration) as total_duration,";
1056
-        $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,";
1057
-        $sql.= " COUNT(t.rowid) as nblines,";
1058
-        $sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1059
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1060
-        $sql.= " WHERE t.fk_task = ".$id;
1061
-        if ($userid > 0) $sql.=" AND t.fk_user = ".$userid;
1053
+        $sql .= " MIN(t.task_datehour) as min_date,";
1054
+        $sql .= " MAX(t.task_datehour) as max_date,";
1055
+        $sql .= " SUM(t.task_duration) as total_duration,";
1056
+        $sql .= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,";
1057
+        $sql .= " COUNT(t.rowid) as nblines,";
1058
+        $sql .= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1059
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1060
+        $sql .= " WHERE t.fk_task = ".$id;
1061
+        if ($userid > 0) $sql .= " AND t.fk_user = ".$userid;
1062 1062
 
1063 1063
         dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1064
-        $resql=$this->db->query($sql);
1064
+        $resql = $this->db->query($sql);
1065 1065
         if ($resql)
1066 1066
         {
1067 1067
             $obj = $this->db->fetch_object($resql);
1068 1068
 
1069
-            $result['min_date'] = $obj->min_date;               // deprecated. use the ->timespent_xxx instead
1070
-            $result['max_date'] = $obj->max_date;               // deprecated. use the ->timespent_xxx instead
1071
-            $result['total_duration'] = $obj->total_duration;   // deprecated. use the ->timespent_xxx instead
1069
+            $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead
1070
+            $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead
1071
+            $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead
1072 1072
 
1073
-            $this->timespent_min_date=$this->db->jdate($obj->min_date);
1074
-            $this->timespent_max_date=$this->db->jdate($obj->max_date);
1075
-            $this->timespent_total_duration=$obj->total_duration;
1076
-            $this->timespent_total_amount=$obj->total_amount;
1077
-            $this->timespent_nblinesnull=($obj->nblinesnull?$obj->nblinesnull:0);
1078
-            $this->timespent_nblines=($obj->nblines?$obj->nblines:0);
1073
+            $this->timespent_min_date = $this->db->jdate($obj->min_date);
1074
+            $this->timespent_max_date = $this->db->jdate($obj->max_date);
1075
+            $this->timespent_total_duration = $obj->total_duration;
1076
+            $this->timespent_total_amount = $obj->total_amount;
1077
+            $this->timespent_nblinesnull = ($obj->nblinesnull ? $obj->nblinesnull : 0);
1078
+            $this->timespent_nblines = ($obj->nblines ? $obj->nblines : 0);
1079 1079
 
1080 1080
             $this->db->free($resql);
1081 1081
         }
@@ -1094,37 +1094,37 @@  discard block
 block discarded – undo
1094 1094
      *  @param		string		$datee		End date (ex 23:59:59)
1095 1095
      *  @return 	array	        		Array of info for task array('amount','nbseconds','nblinesnull')
1096 1096
      */
1097
-    function getSumOfAmount($fuser='', $dates='', $datee='')
1097
+    function getSumOfAmount($fuser = '', $dates = '', $datee = '')
1098 1098
     {
1099 1099
         global $langs;
1100 1100
 
1101
-        if (empty($id)) $id=$this->id;
1101
+        if (empty($id)) $id = $this->id;
1102 1102
 
1103
-        $result=array();
1103
+        $result = array();
1104 1104
 
1105 1105
         $sql = "SELECT";
1106
-        $sql.= " SUM(t.task_duration) as nbseconds,";
1107
-        $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1108
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1109
-        $sql.= " WHERE t.fk_task = ".$id;
1106
+        $sql .= " SUM(t.task_duration) as nbseconds,";
1107
+        $sql .= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1108
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1109
+        $sql .= " WHERE t.fk_task = ".$id;
1110 1110
         if (is_object($fuser) && $fuser->id > 0)
1111 1111
         {
1112
-        	$sql.=" AND fk_user = ".$fuser->id;
1112
+        	$sql .= " AND fk_user = ".$fuser->id;
1113 1113
         }
1114 1114
     	if ($dates > 0)
1115 1115
 		{
1116
-			$datefieldname="task_datehour";
1117
-			$sql.=" AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)";
1116
+			$datefieldname = "task_datehour";
1117
+			$sql .= " AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)";
1118 1118
 		}
1119 1119
     	if ($datee > 0)
1120 1120
 		{
1121
-			$datefieldname="task_datehour";
1122
-			$sql.=" AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)";
1121
+			$datefieldname = "task_datehour";
1122
+			$sql .= " AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)";
1123 1123
 		}
1124 1124
 		//print $sql;
1125 1125
 
1126 1126
         dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
1127
-        $resql=$this->db->query($sql);
1127
+        $resql = $this->db->query($sql);
1128 1128
         if ($resql)
1129 1129
         {
1130 1130
             $obj = $this->db->fetch_object($resql);
@@ -1154,33 +1154,33 @@  discard block
 block discarded – undo
1154 1154
         global $langs;
1155 1155
 
1156 1156
         $sql = "SELECT";
1157
-        $sql.= " t.rowid,";
1158
-        $sql.= " t.fk_task,";
1159
-        $sql.= " t.task_date,";
1160
-        $sql.= " t.task_datehour,";
1161
-        $sql.= " t.task_date_withhour,";
1162
-        $sql.= " t.task_duration,";
1163
-        $sql.= " t.fk_user,";
1164
-        $sql.= " t.note";
1165
-        $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1166
-        $sql.= " WHERE t.rowid = ".$id;
1157
+        $sql .= " t.rowid,";
1158
+        $sql .= " t.fk_task,";
1159
+        $sql .= " t.task_date,";
1160
+        $sql .= " t.task_datehour,";
1161
+        $sql .= " t.task_date_withhour,";
1162
+        $sql .= " t.task_duration,";
1163
+        $sql .= " t.fk_user,";
1164
+        $sql .= " t.note";
1165
+        $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1166
+        $sql .= " WHERE t.rowid = ".$id;
1167 1167
 
1168 1168
         dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
1169
-        $resql=$this->db->query($sql);
1169
+        $resql = $this->db->query($sql);
1170 1170
         if ($resql)
1171 1171
         {
1172 1172
             if ($this->db->num_rows($resql))
1173 1173
             {
1174 1174
                 $obj = $this->db->fetch_object($resql);
1175 1175
 
1176
-                $this->timespent_id			= $obj->rowid;
1177
-                $this->id					= $obj->fk_task;
1178
-                $this->timespent_date		= $this->db->jdate($obj->task_date);
1176
+                $this->timespent_id = $obj->rowid;
1177
+                $this->id = $obj->fk_task;
1178
+                $this->timespent_date = $this->db->jdate($obj->task_date);
1179 1179
                 $this->timespent_datehour   = $this->db->jdate($obj->task_datehour);
1180 1180
                 $this->timespent_withhour   = $obj->task_date_withhour;
1181
-                $this->timespent_duration	= $obj->task_duration;
1182
-                $this->timespent_fk_user	= $obj->fk_user;
1183
-                $this->timespent_note		= $obj->note;
1181
+                $this->timespent_duration = $obj->task_duration;
1182
+                $this->timespent_fk_user = $obj->fk_user;
1183
+                $this->timespent_note = $obj->note;
1184 1184
             }
1185 1185
 
1186 1186
             $this->db->free($resql);
@@ -1189,7 +1189,7 @@  discard block
 block discarded – undo
1189 1189
         }
1190 1190
         else
1191 1191
         {
1192
-            $this->error="Error ".$this->db->lasterror();
1192
+            $this->error = "Error ".$this->db->lasterror();
1193 1193
             return -1;
1194 1194
         }
1195 1195
     }
@@ -1201,9 +1201,9 @@  discard block
 block discarded – undo
1201 1201
      *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1202 1202
      *  @return	int						<0 if KO, >0 if OK
1203 1203
      */
1204
-    function updateTimeSpent($user, $notrigger=0)
1204
+    function updateTimeSpent($user, $notrigger = 0)
1205 1205
     {
1206
-    	global $conf,$langs;
1206
+    	global $conf, $langs;
1207 1207
 
1208 1208
         $ret = 0;
1209 1209
 
@@ -1214,21 +1214,21 @@  discard block
 block discarded – undo
1214 1214
         $this->db->begin();
1215 1215
 
1216 1216
         $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
1217
-        $sql.= " task_date = '".$this->db->idate($this->timespent_date)."',";
1218
-        $sql.= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',";
1219
-        $sql.= " task_date_withhour = ".(empty($this->timespent_withhour)?0:1).",";
1220
-        $sql.= " task_duration = ".$this->timespent_duration.",";
1221
-        $sql.= " fk_user = ".$this->timespent_fk_user.",";
1222
-        $sql.= " note = ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null");
1223
-        $sql.= " WHERE rowid = ".$this->timespent_id;
1217
+        $sql .= " task_date = '".$this->db->idate($this->timespent_date)."',";
1218
+        $sql .= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',";
1219
+        $sql .= " task_date_withhour = ".(empty($this->timespent_withhour) ? 0 : 1).",";
1220
+        $sql .= " task_duration = ".$this->timespent_duration.",";
1221
+        $sql .= " fk_user = ".$this->timespent_fk_user.",";
1222
+        $sql .= " note = ".(isset($this->timespent_note) ? "'".$this->db->escape($this->timespent_note)."'" : "null");
1223
+        $sql .= " WHERE rowid = ".$this->timespent_id;
1224 1224
 
1225 1225
         dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1226
-        if ($this->db->query($sql) )
1226
+        if ($this->db->query($sql))
1227 1227
         {
1228
-            if (! $notrigger)
1228
+            if (!$notrigger)
1229 1229
             {
1230 1230
                 // Call trigger
1231
-                $result=$this->call_trigger('TASK_TIMESPENT_MODIFY',$user);
1231
+                $result = $this->call_trigger('TASK_TIMESPENT_MODIFY', $user);
1232 1232
                 if ($result < 0)
1233 1233
                 {
1234 1234
                     $this->db->rollback();
@@ -1241,7 +1241,7 @@  discard block
 block discarded – undo
1241 1241
         }
1242 1242
         else
1243 1243
         {
1244
-            $this->error=$this->db->lasterror();
1244
+            $this->error = $this->db->lasterror();
1245 1245
             $this->db->rollback();
1246 1246
             $ret = -1;
1247 1247
         }
@@ -1251,13 +1251,13 @@  discard block
 block discarded – undo
1251 1251
             $newDuration = $this->timespent_duration - $this->timespent_old_duration;
1252 1252
 
1253 1253
             $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1254
-            $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")";
1255
-            $sql.= " WHERE rowid = ".$this->id;
1254
+            $sql .= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")";
1255
+            $sql .= " WHERE rowid = ".$this->id;
1256 1256
 
1257 1257
             dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
1258
-            if (! $this->db->query($sql) )
1258
+            if (!$this->db->query($sql))
1259 1259
             {
1260
-                $this->error=$this->db->lasterror();
1260
+                $this->error = $this->db->lasterror();
1261 1261
                 $this->db->rollback();
1262 1262
                 $ret = -2;
1263 1263
             }
@@ -1274,46 +1274,46 @@  discard block
 block discarded – undo
1274 1274
      *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1275 1275
      *  @return	int						<0 if KO, >0 if OK
1276 1276
      */
1277
-    function delTimeSpent($user, $notrigger=0)
1277
+    function delTimeSpent($user, $notrigger = 0)
1278 1278
     {
1279 1279
         global $conf, $langs;
1280 1280
 
1281
-        $error=0;
1281
+        $error = 0;
1282 1282
 
1283 1283
         $this->db->begin();
1284 1284
 
1285 1285
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time";
1286
-        $sql.= " WHERE rowid = ".$this->timespent_id;
1286
+        $sql .= " WHERE rowid = ".$this->timespent_id;
1287 1287
 
1288 1288
         dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1289 1289
         $resql = $this->db->query($sql);
1290
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1290
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
1291 1291
 
1292
-        if (! $error)
1292
+        if (!$error)
1293 1293
         {
1294
-            if (! $notrigger)
1294
+            if (!$notrigger)
1295 1295
             {
1296 1296
                 // Call trigger
1297
-                $result=$this->call_trigger('TASK_TIMESPENT_DELETE',$user);
1297
+                $result = $this->call_trigger('TASK_TIMESPENT_DELETE', $user);
1298 1298
                 if ($result < 0) { $error++; }
1299 1299
                 // End call triggers
1300 1300
             }
1301 1301
         }
1302 1302
 
1303
-        if (! $error)
1303
+        if (!$error)
1304 1304
         {
1305 1305
             $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1306
-            $sql.= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration?$this->timespent_duration:0);
1307
-            $sql.= " WHERE rowid = ".$this->id;
1306
+            $sql .= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration ? $this->timespent_duration : 0);
1307
+            $sql .= " WHERE rowid = ".$this->id;
1308 1308
 
1309 1309
             dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
1310
-            if ($this->db->query($sql) )
1310
+            if ($this->db->query($sql))
1311 1311
             {
1312 1312
                 $result = 0;
1313 1313
             }
1314 1314
             else
1315 1315
             {
1316
-                $this->error=$this->db->lasterror();
1316
+                $this->error = $this->db->lasterror();
1317 1317
                 $result = -2;
1318 1318
             }
1319 1319
         }
@@ -1321,13 +1321,13 @@  discard block
 block discarded – undo
1321 1321
         // Commit or rollback
1322 1322
         if ($error)
1323 1323
         {
1324
-            foreach($this->errors as $errmsg)
1324
+            foreach ($this->errors as $errmsg)
1325 1325
             {
1326 1326
                 dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
1327
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
1327
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1328 1328
             }
1329 1329
             $this->db->rollback();
1330
-            return -1*$error;
1330
+            return -1 * $error;
1331 1331
         }
1332 1332
         else
1333 1333
         {
@@ -1349,21 +1349,21 @@  discard block
 block discarded – undo
1349 1349
 	 *	@param	bool	$clone_prog				clone progress of project
1350 1350
 	 * 	@return	int								New id of clone
1351 1351
 	 */
1352
-	function createFromClone($fromid,$project_id,$parent_task_id,$clone_change_dt=false,$clone_affectation=false,$clone_time=false,$clone_file=false,$clone_note=false,$clone_prog=false)
1352
+	function createFromClone($fromid, $project_id, $parent_task_id, $clone_change_dt = false, $clone_affectation = false, $clone_time = false, $clone_file = false, $clone_note = false, $clone_prog = false)
1353 1353
 	{
1354
-		global $user,$langs,$conf;
1354
+		global $user, $langs, $conf;
1355 1355
 
1356
-		$error=0;
1356
+		$error = 0;
1357 1357
 
1358 1358
 		//Use 00:00 of today if time is use on task.
1359
-		$now=dol_mktime(0,0,0,dol_print_date(dol_now(),'%m'),dol_print_date(dol_now(),'%d'),dol_print_date(dol_now(),'%Y'));
1359
+		$now = dol_mktime(0, 0, 0, dol_print_date(dol_now(), '%m'), dol_print_date(dol_now(), '%d'), dol_print_date(dol_now(), '%Y'));
1360 1360
 
1361 1361
 		$datec = $now;
1362 1362
 
1363
-		$clone_task=new Task($this->db);
1364
-		$origin_task=new Task($this->db);
1363
+		$clone_task = new Task($this->db);
1364
+		$origin_task = new Task($this->db);
1365 1365
 
1366
-		$clone_task->context['createfromclone']='createfromclone';
1366
+		$clone_task->context['createfromclone'] = 'createfromclone';
1367 1367
 
1368 1368
 		$this->db->begin();
1369 1369
 
@@ -1374,29 +1374,29 @@  discard block
 block discarded – undo
1374 1374
 
1375 1375
 		$origin_task->fetch($fromid);
1376 1376
 
1377
-		$defaultref='';
1378
-		$obj = empty($conf->global->PROJECT_TASK_ADDON)?'mod_task_simple':$conf->global->PROJECT_TASK_ADDON;
1379
-		if (! empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
1377
+		$defaultref = '';
1378
+		$obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
1379
+		if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
1380 1380
 		{
1381
-			require_once DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
1381
+			require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
1382 1382
 			$modTask = new $obj;
1383
-			$defaultref = $modTask->getNextValue(0,$clone_task);
1383
+			$defaultref = $modTask->getNextValue(0, $clone_task);
1384 1384
 		}
1385 1385
 
1386 1386
 		$ori_project_id					= $clone_task->fk_project;
1387 1387
 
1388 1388
 		$clone_task->id					= 0;
1389 1389
 		$clone_task->ref				= $defaultref;
1390
-        $clone_task->fk_project			= $project_id;
1391
-        $clone_task->fk_task_parent		= $parent_task_id;
1392
-        $clone_task->date_c				= $datec;
1393
-        $clone_task->planned_workload	= $origin_task->planned_workload;
1394
-		$clone_task->rang				= $origin_task->rang;
1390
+        $clone_task->fk_project = $project_id;
1391
+        $clone_task->fk_task_parent = $parent_task_id;
1392
+        $clone_task->date_c = $datec;
1393
+        $clone_task->planned_workload = $origin_task->planned_workload;
1394
+		$clone_task->rang = $origin_task->rang;
1395 1395
 
1396 1396
         //Manage Task Date
1397 1397
         if ($clone_change_dt)
1398 1398
         {
1399
-        	$projectstatic=new Project($this->db);
1399
+        	$projectstatic = new Project($this->db);
1400 1400
         	$projectstatic->fetch($ori_project_id);
1401 1401
 
1402 1402
         	//Origin project strat date
@@ -1405,51 +1405,51 @@  discard block
 block discarded – undo
1405 1405
 	    	//Calcultate new task start date with difference between origin proj start date and origin task start date
1406 1406
 	    	if (!empty($clone_task->date_start))
1407 1407
 	    	{
1408
-				$clone_task->date_start			= $now + $clone_task->date_start - $orign_project_dt_start;
1408
+				$clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start;
1409 1409
 	    	}
1410 1410
 
1411 1411
 	    	//Calcultate new task end date with difference between origin proj end date and origin task end date
1412 1412
 	    	if (!empty($clone_task->date_end))
1413 1413
 	    	{
1414
-				$clone_task->date_end			= $now + $clone_task->date_end - $orign_project_dt_start;
1414
+				$clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start;
1415 1415
 	    	}
1416 1416
 
1417 1417
         }
1418 1418
 
1419 1419
 		if (!$clone_prog)
1420 1420
         {
1421
-        	    $clone_task->progress=0;
1421
+        	    $clone_task->progress = 0;
1422 1422
         }
1423 1423
 
1424 1424
 		// Create clone
1425
-		$result=$clone_task->create($user);
1425
+		$result = $clone_task->create($user);
1426 1426
 
1427 1427
 		// Other options
1428 1428
 		if ($result < 0)
1429 1429
 		{
1430
-			$this->error=$clone_task->error;
1430
+			$this->error = $clone_task->error;
1431 1431
 			$error++;
1432 1432
 		}
1433 1433
 
1434 1434
 		// End
1435
-		if (! $error)
1435
+		if (!$error)
1436 1436
 		{
1437
-			$clone_task_id=$clone_task->id;
1437
+			$clone_task_id = $clone_task->id;
1438 1438
 			$clone_task_ref = $clone_task->ref;
1439 1439
 
1440 1440
        		//Note Update
1441 1441
 			if (!$clone_note)
1442 1442
        		{
1443
-        	    $clone_task->note_private='';
1444
-    			$clone_task->note_public='';
1443
+        	    $clone_task->note_private = '';
1444
+    			$clone_task->note_public = '';
1445 1445
         	}
1446 1446
         	else
1447 1447
         	{
1448 1448
         		$this->db->begin();
1449
-				$res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES),'_public');
1449
+				$res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES), '_public');
1450 1450
 				if ($res < 0)
1451 1451
 				{
1452
-					$this->error.=$clone_task->error;
1452
+					$this->error .= $clone_task->error;
1453 1453
 					$error++;
1454 1454
 					$this->db->rollback();
1455 1455
 				}
@@ -1459,10 +1459,10 @@  discard block
 block discarded – undo
1459 1459
 				}
1460 1460
 
1461 1461
 				$this->db->begin();
1462
-				$res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES), '_private');
1462
+				$res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES), '_private');
1463 1463
 				if ($res < 0)
1464 1464
 				{
1465
-					$this->error.=$clone_task->error;
1465
+					$this->error .= $clone_task->error;
1466 1466
 					$error++;
1467 1467
 					$this->db->rollback();
1468 1468
 				}
@@ -1478,39 +1478,39 @@  discard block
 block discarded – undo
1478 1478
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1479 1479
 
1480 1480
 				//retreive project origin ref to know folder to copy
1481
-				$projectstatic=new Project($this->db);
1481
+				$projectstatic = new Project($this->db);
1482 1482
 	        	$projectstatic->fetch($ori_project_id);
1483
-	        	$ori_project_ref=$projectstatic->ref;
1483
+	        	$ori_project_ref = $projectstatic->ref;
1484 1484
 
1485
-	        	if ($ori_project_id!=$project_id)
1485
+	        	if ($ori_project_id != $project_id)
1486 1486
 	        	{
1487 1487
 	        		$projectstatic->fetch($project_id);
1488
-	        		$clone_project_ref=$projectstatic->ref;
1488
+	        		$clone_project_ref = $projectstatic->ref;
1489 1489
 	        	}
1490 1490
 	        	else
1491 1491
 	        	{
1492
-	        		$clone_project_ref=$ori_project_ref;
1492
+	        		$clone_project_ref = $ori_project_ref;
1493 1493
 	        	}
1494 1494
 
1495
-				$clone_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($clone_project_ref). "/" . dol_sanitizeFileName($clone_task_ref);
1496
-				$ori_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($ori_project_ref). "/" . dol_sanitizeFileName($fromid);
1495
+				$clone_task_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($clone_project_ref)."/".dol_sanitizeFileName($clone_task_ref);
1496
+				$ori_task_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($ori_project_ref)."/".dol_sanitizeFileName($fromid);
1497 1497
 
1498
-				$filearray=dol_dir_list($ori_task_dir,"files",0,'','(\.meta|_preview.*\.png)$','',SORT_ASC,1);
1499
-				foreach($filearray as $key => $file)
1498
+				$filearray = dol_dir_list($ori_task_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
1499
+				foreach ($filearray as $key => $file)
1500 1500
 				{
1501 1501
 					if (!file_exists($clone_task_dir))
1502 1502
 					{
1503 1503
 						if (dol_mkdir($clone_task_dir) < 0)
1504 1504
 						{
1505
-							$this->error.=$langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1505
+							$this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1506 1506
 							$error++;
1507 1507
 						}
1508 1508
 					}
1509 1509
 
1510
-					$rescopy = dol_copy($ori_task_dir . '/' . $file['name'], $clone_task_dir . '/' . $file['name'],0,1);
1510
+					$rescopy = dol_copy($ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name'], 0, 1);
1511 1511
 					if (is_numeric($rescopy) && $rescopy < 0)
1512 1512
 					{
1513
-						$this->error.=$langs->trans("ErrorFailToCopyFile",$ori_task_dir . '/' . $file['name'],$clone_task_dir . '/' . $file['name']);
1513
+						$this->error .= $langs->trans("ErrorFailToCopyFile", $ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name']);
1514 1514
 						$error++;
1515 1515
 					}
1516 1516
 				}
@@ -1522,10 +1522,10 @@  discard block
 block discarded – undo
1522 1522
 				$origin_task = new Task($this->db);
1523 1523
 				$origin_task->fetch($fromid);
1524 1524
 
1525
-				foreach(array('internal','external') as $source)
1525
+				foreach (array('internal', 'external') as $source)
1526 1526
 				{
1527
-					$tab = $origin_task->liste_contact(-1,$source);
1528
-					$num=count($tab);
1527
+					$tab = $origin_task->liste_contact(-1, $source);
1528
+					$num = count($tab);
1529 1529
 					$i = 0;
1530 1530
 					while ($i < $num)
1531 1531
 					{
@@ -1533,14 +1533,14 @@  discard block
 block discarded – undo
1533 1533
 						if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1534 1534
 						{
1535 1535
 							$langs->load("errors");
1536
-							$this->error.=$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1536
+							$this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1537 1537
 							$error++;
1538 1538
 						}
1539 1539
 						else
1540 1540
 						{
1541
-							if ($clone_task->error!='')
1541
+							if ($clone_task->error != '')
1542 1542
 							{
1543
-								$this->error.=$clone_task->error;
1543
+								$this->error .= $clone_task->error;
1544 1544
 								$error++;
1545 1545
 							}
1546 1546
 						}
@@ -1549,7 +1549,7 @@  discard block
 block discarded – undo
1549 1549
 				}
1550 1550
 			}
1551 1551
 
1552
-			if($clone_time)
1552
+			if ($clone_time)
1553 1553
 			{
1554 1554
 				//TODO clone time of affectation
1555 1555
 			}
@@ -1557,7 +1557,7 @@  discard block
 block discarded – undo
1557 1557
 
1558 1558
 		unset($clone_task->context['createfromclone']);
1559 1559
 
1560
-		if (! $error)
1560
+		if (!$error)
1561 1561
 		{
1562 1562
 			$this->db->commit();
1563 1563
 			return $clone_task_id;
@@ -1565,7 +1565,7 @@  discard block
 block discarded – undo
1565 1565
 		else
1566 1566
 		{
1567 1567
 			$this->db->rollback();
1568
-			dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : " . $this->error, LOG_ERR);
1568
+			dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
1569 1569
 			return -1;
1570 1570
 		}
1571 1571
 	}
@@ -1577,9 +1577,9 @@  discard block
 block discarded – undo
1577 1577
 	 *	@param	integer	$mode		0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1578 1578
 	 * 	@return	string	  			Label
1579 1579
 	 */
1580
-	function getLibStatut($mode=0)
1580
+	function getLibStatut($mode = 0)
1581 1581
 	{
1582
-		return $this->LibStatut($this->fk_statut,$mode);
1582
+		return $this->LibStatut($this->fk_statut, $mode);
1583 1583
 	}
1584 1584
 
1585 1585
 	/**
@@ -1589,19 +1589,19 @@  discard block
 block discarded – undo
1589 1589
 	 *	@param	integer		$mode		0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1590 1590
 	 * 	@return	string	  				Label
1591 1591
 	 */
1592
-	function LibStatut($statut,$mode=0)
1592
+	function LibStatut($statut, $mode = 0)
1593 1593
 	{
1594 1594
 		// list of Statut of the task
1595
-		$this->statuts[0]='Draft';
1596
-		$this->statuts[1]='Validated';
1597
-		$this->statuts[2]='Running';
1598
-		$this->statuts[3]='Finish';
1599
-		$this->statuts[4]='Transfered';
1600
-		$this->statuts_short[0]='Draft';
1601
-		$this->statuts_short[1]='Validated';
1602
-		$this->statuts_short[2]='Running';
1603
-		$this->statuts_short[3]='Finish';
1604
-		$this->statuts_short[4]='Transfered';
1595
+		$this->statuts[0] = 'Draft';
1596
+		$this->statuts[1] = 'Validated';
1597
+		$this->statuts[2] = 'Running';
1598
+		$this->statuts[3] = 'Finish';
1599
+		$this->statuts[4] = 'Transfered';
1600
+		$this->statuts_short[0] = 'Draft';
1601
+		$this->statuts_short[1] = 'Validated';
1602
+		$this->statuts_short[2] = 'Running';
1603
+		$this->statuts_short[3] = 'Finish';
1604
+		$this->statuts_short[4] = 'Transfered';
1605 1605
 
1606 1606
 		global $langs;
1607 1607
 
@@ -1615,39 +1615,39 @@  discard block
 block discarded – undo
1615 1615
 		}
1616 1616
 		if ($mode == 2)
1617 1617
 		{
1618
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts_short[$statut]);
1619
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts_short[$statut]);
1620
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts_short[$statut]);
1621
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
1622
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts_short[$statut]);
1623
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts_short[$statut]);
1618
+			if ($statut == 0) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0').' '.$langs->trans($this->statuts_short[$statut]);
1619
+			if ($statut == 1) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1').' '.$langs->trans($this->statuts_short[$statut]);
1620
+			if ($statut == 2) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3').' '.$langs->trans($this->statuts_short[$statut]);
1621
+			if ($statut == 3) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4').' '.$langs->trans($this->statuts_short[$statut]);
1622
+			if ($statut == 4) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6').' '.$langs->trans($this->statuts_short[$statut]);
1623
+			if ($statut == 5) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5').' '.$langs->trans($this->statuts_short[$statut]);
1624 1624
 		}
1625 1625
 		if ($mode == 3)
1626 1626
 		{
1627
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1628
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1629
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1630
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1631
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1632
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1627
+			if ($statut == 0) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0');
1628
+			if ($statut == 1) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1');
1629
+			if ($statut == 2) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3');
1630
+			if ($statut == 3) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4');
1631
+			if ($statut == 4) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6');
1632
+			if ($statut == 5) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5');
1633 1633
 		}
1634 1634
 		if ($mode == 4)
1635 1635
 		{
1636
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]);
1637
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]);
1638
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]);
1639
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
1640
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]);
1641
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]);
1636
+			if ($statut == 0) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0').' '.$langs->trans($this->statuts[$statut]);
1637
+			if ($statut == 1) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1').' '.$langs->trans($this->statuts[$statut]);
1638
+			if ($statut == 2) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3').' '.$langs->trans($this->statuts[$statut]);
1639
+			if ($statut == 3) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4').' '.$langs->trans($this->statuts[$statut]);
1640
+			if ($statut == 4) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6').' '.$langs->trans($this->statuts[$statut]);
1641
+			if ($statut == 5) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5').' '.$langs->trans($this->statuts[$statut]);
1642 1642
 		}
1643 1643
 		if ($mode == 5)
1644 1644
 		{
1645
-			if ($statut==0) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1646
-			if ($statut==1) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1647
-			if ($statut==2) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1648
-			if ($statut==3) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1649
-			if ($statut==4) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1650
-			if ($statut==5) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1645
+			if ($statut == 0) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut0');
1646
+			if ($statut == 1) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut1');
1647
+			if ($statut == 2) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut3');
1648
+			if ($statut == 3) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut4');
1649
+			if ($statut == 4) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut6');
1650
+			if ($statut == 5) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut5');
1651 1651
 		}
1652 1652
 		if ($mode == 6)
1653 1653
 		{
@@ -1672,19 +1672,19 @@  discard block
 block discarded – undo
1672 1672
 	 *  @param  int			$hideref        Hide ref
1673 1673
 	 *  @return int         				0 if KO, 1 if OK
1674 1674
 	 */
1675
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
1675
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1676 1676
 	{
1677
-		global $conf,$langs;
1677
+		global $conf, $langs;
1678 1678
 
1679 1679
 		$langs->load("projects");
1680 1680
 
1681
-		if (! dol_strlen($modele)) {
1681
+		if (!dol_strlen($modele)) {
1682 1682
 
1683 1683
 			$modele = 'nodefault';
1684 1684
 
1685 1685
 			if ($this->modelpdf) {
1686 1686
 				$modele = $this->modelpdf;
1687
-			} elseif (! empty($conf->global->PROJECT_TASK_ADDON_PDF)) {
1687
+			} elseif (!empty($conf->global->PROJECT_TASK_ADDON_PDF)) {
1688 1688
 				$modele = $conf->global->PROJECT_TASK_ADDON_PDF;
1689 1689
 			}
1690 1690
 		}
@@ -1705,43 +1705,43 @@  discard block
 block discarded – undo
1705 1705
 	{
1706 1706
 		global $conf, $langs;
1707 1707
 		
1708
-		$mine=0; $socid=$user->societe_id;
1708
+		$mine = 0; $socid = $user->societe_id;
1709 1709
 		
1710 1710
 		$projectstatic = new Project($this->db);
1711
-		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,$mine,1,$socid);
1711
+		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine, 1, $socid);
1712 1712
 		
1713 1713
 		// List of tasks (does not care about permissions. Filtering will be done later)
1714 1714
 		$sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,";
1715
-		$sql.= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,";
1716
-		$sql.= " t.dateo as date_start, t.datee as datee";
1717
-		$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
1718
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1719
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1720
-		$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
1721
-		$sql.= " WHERE p.entity IN (".getEntity('project', 0).')';
1722
-		$sql.= " AND p.fk_statut = 1";
1723
-		$sql.= " AND t.fk_projet = p.rowid";
1724
-		$sql.= " AND t.progress < 100";         // tasks to do
1725
-		if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")";
1715
+		$sql .= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,";
1716
+		$sql .= " t.dateo as date_start, t.datee as datee";
1717
+		$sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1718
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1719
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1720
+		$sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
1721
+		$sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
1722
+		$sql .= " AND p.fk_statut = 1";
1723
+		$sql .= " AND t.fk_projet = p.rowid";
1724
+		$sql .= " AND t.progress < 100"; // tasks to do
1725
+		if ($mine || !$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")";
1726 1726
 		// No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
1727 1727
 		//if ($socid || ! $user->rights->societe->client->voir)	$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1728
-		if ($socid) $sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1729
-		if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1728
+		if ($socid) $sql .= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1729
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id.") OR (s.rowid IS NULL))";
1730 1730
 		//print $sql;
1731
-		$resql=$this->db->query($sql);
1731
+		$resql = $this->db->query($sql);
1732 1732
 		if ($resql)
1733 1733
 		{
1734 1734
 			$task_static = new Task($this->db);
1735 1735
 			
1736 1736
 			$response = new WorkboardResponse();
1737
-			$response->warning_delay = $conf->projet->task->warning_delay/60/60/24;
1737
+			$response->warning_delay = $conf->projet->task->warning_delay / 60 / 60 / 24;
1738 1738
 			$response->label = $langs->trans("OpenedTasks");
1739 1739
 			if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
1740 1740
 			else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
1741
-			$response->img = img_object('',"task");
1741
+			$response->img = img_object('', "task");
1742 1742
 			
1743 1743
 			// This assignment in condition is not a bug. It allows walking the results.
1744
-			while ($obj=$this->db->fetch_object($resql))
1744
+			while ($obj = $this->db->fetch_object($resql))
1745 1745
 			{
1746 1746
 				$response->nbtodo++;
1747 1747
 				
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
 		}
1760 1760
 		else
1761 1761
 		{
1762
-			$this->error=$this->db->error();
1762
+			$this->error = $this->db->error();
1763 1763
 			return -1;
1764 1764
 		}
1765 1765
 	}
@@ -1774,33 +1774,33 @@  discard block
 block discarded – undo
1774 1774
 	{
1775 1775
 		global $user;
1776 1776
 		
1777
-		$mine=0; $socid=$user->societe_id;
1777
+		$mine = 0; $socid = $user->societe_id;
1778 1778
 		
1779 1779
 		$projectstatic = new Project($this->db);
1780
-		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,$mine,1,$socid);
1780
+		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine, 1, $socid);
1781 1781
 		
1782 1782
 		// List of tasks (does not care about permissions. Filtering will be done later)
1783 1783
 		$sql = "SELECT count(p.rowid) as nb";
1784
-		$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
1785
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1786
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1787
-		$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
1788
-		$sql.= " WHERE p.entity IN (".getEntity('project', 0).')';
1789
-		$sql.= " AND t.fk_projet = p.rowid";         // tasks to do
1790
-		if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")";
1784
+		$sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1785
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1786
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1787
+		$sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
1788
+		$sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
1789
+		$sql .= " AND t.fk_projet = p.rowid"; // tasks to do
1790
+		if ($mine || !$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")";
1791 1791
 		// No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
1792 1792
 		//if ($socid || ! $user->rights->societe->client->voir)	$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1793
-		if ($socid) $sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1794
-		if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1793
+		if ($socid) $sql .= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1794
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id.") OR (s.rowid IS NULL))";
1795 1795
 		
1796
-		$resql=$this->db->query($sql);
1796
+		$resql = $this->db->query($sql);
1797 1797
 		if ($resql)
1798 1798
 		{
1799 1799
 			
1800 1800
 			// This assignment in condition is not a bug. It allows walking the results.
1801
-			while ($obj=$this->db->fetch_object($resql))
1801
+			while ($obj = $this->db->fetch_object($resql))
1802 1802
 			{
1803
-				$this->nb["tasks"]=$obj->nb;
1803
+				$this->nb["tasks"] = $obj->nb;
1804 1804
 			}
1805 1805
 			$this->db->free($resql);
1806 1806
 			return 1;
@@ -1808,7 +1808,7 @@  discard block
 block discarded – undo
1808 1808
 		else
1809 1809
 		{
1810 1810
 			dol_print_error($this->db);
1811
-			$this->error=$this->db->error();
1811
+			$this->error = $this->db->error();
1812 1812
 			return -1;
1813 1813
 		}
1814 1814
 	}
@@ -1822,7 +1822,7 @@  discard block
 block discarded – undo
1822 1822
 	{
1823 1823
 	    global $conf;
1824 1824
 
1825
-        if (! ($this->progress >= 0 && $this->progress < 100)) {
1825
+        if (!($this->progress >= 0 && $this->progress < 100)) {
1826 1826
             return false;
1827 1827
         }
1828 1828
 
Please login to merge, or discard this patch.
Braces   +290 added lines, -148 removed lines patch added patch discarded remove patch
@@ -155,9 +155,11 @@  discard block
 block discarded – undo
155 155
         // Update extrafield
156 156
         if (! $error)
157 157
         {
158
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
158
+        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
159
+        		// For avoid conflicts if trigger used
159 160
         	{
160 161
         		$result=$this->insertExtraFields();
162
+        	}
161 163
         		if ($result < 0)
162 164
         		{
163 165
         			$error++;
@@ -175,8 +177,7 @@  discard block
 block discarded – undo
175 177
             }
176 178
             $this->db->rollback();
177 179
             return -1*$error;
178
-        }
179
-        else
180
+        } else
180 181
         {
181 182
             $this->db->commit();
182 183
             return $this->id;
@@ -219,7 +220,7 @@  discard block
 block discarded – undo
219 220
         $sql.= " WHERE ";
220 221
         if (!empty($ref)) {
221 222
         	$sql.="t.ref = '".$this->db->escape($ref)."'";
222
-        }else {
223
+        } else {
223 224
         	$sql.="t.rowid = ".$id;
224 225
         }
225 226
 
@@ -262,11 +263,10 @@  discard block
 block discarded – undo
262 263
             if ($num_rows) {
263 264
             	$this->fetchComments();
264 265
             	return 1;
265
-            }else {
266
+            } else {
266 267
             	return 0;
267 268
             }
268
-        }
269
-        else
269
+        } else
270 270
         {
271 271
             $this->error="Error ".$this->db->lasterror();
272 272
             return -1;
@@ -287,13 +287,27 @@  discard block
 block discarded – undo
287 287
         $error=0;
288 288
 
289 289
         // Clean parameters
290
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
291
-		if (isset($this->ref)) $this->ref=trim($this->ref);
292
-        if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent);
293
-        if (isset($this->label)) $this->label=trim($this->label);
294
-        if (isset($this->description)) $this->description=trim($this->description);
295
-        if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective);
296
-        if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload);
290
+        if (isset($this->fk_project)) {
291
+        	$this->fk_project=trim($this->fk_project);
292
+        }
293
+		if (isset($this->ref)) {
294
+			$this->ref=trim($this->ref);
295
+		}
296
+        if (isset($this->fk_task_parent)) {
297
+        	$this->fk_task_parent=trim($this->fk_task_parent);
298
+        }
299
+        if (isset($this->label)) {
300
+        	$this->label=trim($this->label);
301
+        }
302
+        if (isset($this->description)) {
303
+        	$this->description=trim($this->description);
304
+        }
305
+        if (isset($this->duration_effective)) {
306
+        	$this->duration_effective=trim($this->duration_effective);
307
+        }
308
+        if (isset($this->planned_workload)) {
309
+        	$this->planned_workload=trim($this->planned_workload);
310
+        }
297 311
 
298 312
         // Check parameters
299 313
         // Put here code to add control on parameters values
@@ -332,9 +346,11 @@  discard block
 block discarded – undo
332 346
 
333 347
         //Update extrafield
334 348
         if (!$error) {
335
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
349
+        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
350
+        		// For avoid conflicts if trigger used
336 351
         	{
337 352
         		$result=$this->insertExtraFields();
353
+        	}
338 354
         		if ($result < 0)
339 355
         		{
340 356
         			$error++;
@@ -376,8 +392,7 @@  discard block
 block discarded – undo
376 392
             }
377 393
             $this->db->rollback();
378 394
             return -1*$error;
379
-        }
380
-        else
395
+        } else
381 396
         {
382 397
             $this->db->commit();
383 398
             return 1;
@@ -480,8 +495,7 @@  discard block
 block discarded – undo
480 495
             }
481 496
             $this->db->rollback();
482 497
             return -1*$error;
483
-        }
484
-        else
498
+        } else
485 499
 		{
486 500
 			//Delete associated link file
487 501
 	        if ($conf->projet->dir_output)
@@ -526,19 +540,19 @@  discard block
 block discarded – undo
526 540
 
527 541
         dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
528 542
         $resql = $this->db->query($sql);
529
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
530
-        else
543
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } else
531 544
         {
532 545
             $obj=$this->db->fetch_object($resql);
533
-            if ($obj) $ret=$obj->nb;
546
+            if ($obj) {
547
+            	$ret=$obj->nb;
548
+            }
534 549
             $this->db->free($resql);
535 550
         }
536 551
 
537 552
         if (! $error)
538 553
         {
539 554
             return $ret;
540
-        }
541
-        else
555
+        } else
542 556
         {
543 557
             return -1;
544 558
         }
@@ -560,19 +574,19 @@  discard block
 block discarded – undo
560 574
 
561 575
         dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
562 576
         $resql = $this->db->query($sql);
563
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
564
-        else
577
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } else
565 578
         {
566 579
             $obj=$this->db->fetch_object($resql);
567
-            if ($obj) $ret=$obj->nb;
580
+            if ($obj) {
581
+            	$ret=$obj->nb;
582
+            }
568 583
             $this->db->free($resql);
569 584
         }
570 585
 
571 586
         if (! $error)
572 587
         {
573 588
             return $ret;
574
-        }
575
-        else
589
+        } else
576 590
         {
577 591
             return -1;
578 592
         }
@@ -595,14 +609,19 @@  discard block
 block discarded – undo
595 609
     {
596 610
         global $conf, $langs, $user;
597 611
 
598
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
612
+        if (! empty($conf->dol_no_mouse_hover)) {
613
+        	$notooltip=1;
614
+        }
615
+        // Force disable tooltips
599 616
 
600 617
         $result='';
601 618
         $label = '<u>' . $langs->trans("ShowTask") . '</u>';
602
-        if (! empty($this->ref))
603
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
604
-        if (! empty($this->label))
605
-            $label .= '<br><b>' . $langs->trans('LabelTask') . ':</b> ' . $this->label;
619
+        if (! empty($this->ref)) {
620
+                    $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
621
+        }
622
+        if (! empty($this->label)) {
623
+                    $label .= '<br><b>' . $langs->trans('LabelTask') . ':</b> ' . $this->label;
624
+        }
606 625
         if ($this->date_start || $this->date_end)
607 626
         {
608 627
         	$label .= "<br>".get_date_range($this->date_start,$this->date_end,'',$langs,0);
@@ -611,8 +630,12 @@  discard block
 block discarded – undo
611 630
         $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':'');
612 631
         // Add param to save lastsearch_values or not
613 632
         $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
614
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
615
-        if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
633
+        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
634
+        	$add_save_lastsearch_values=1;
635
+        }
636
+        if ($add_save_lastsearch_values) {
637
+        	$url.='&save_lastsearch_values=1';
638
+        }
616 639
 
617 640
         $linkclose = '';
618 641
         if (empty($notooltip))
@@ -632,9 +655,15 @@  discard block
 block discarded – undo
632 655
 
633 656
         $picto='projecttask';
634 657
 
635
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
636
-        if ($withpicto && $withpicto != 2) $result.=' ';
637
-        if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
658
+        if ($withpicto) {
659
+        	$result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
660
+        }
661
+        if ($withpicto && $withpicto != 2) {
662
+        	$result.=' ';
663
+        }
664
+        if ($withpicto != 2) {
665
+        	$result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
666
+        }
638 667
         return $result;
639 668
     }
640 669
 
@@ -706,8 +735,7 @@  discard block
 block discarded – undo
706 735
             }
707 736
             $sql.= " WHERE p.entity IN (".getEntity('project').")";
708 737
             $sql.= " AND t.fk_projet = p.rowid";
709
-        }
710
-        elseif ($mode == 1)
738
+        } elseif ($mode == 1)
711 739
         {
712 740
             if ($filteronprojuser > 0)
713 741
             {
@@ -719,14 +747,14 @@  discard block
 block discarded – undo
719 747
                 $sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
720 748
                 $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2";
721 749
                 $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
722
-            }
723
-            else
750
+            } else
724 751
             {
725 752
                 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
726 753
             }
727 754
             $sql.= " WHERE p.entity IN (".getEntity('project').")";
755
+        } else {
756
+        	return 'BadValueForParameterMode';
728 757
         }
729
-        else return 'BadValueForParameterMode';
730 758
 
731 759
         if ($filteronprojuser > 0)
732 760
         {
@@ -747,11 +775,21 @@  discard block
 block discarded – undo
747 775
             $sql.= " AND ec2.statut = 4";
748 776
             $sql.= " AND ctc2.source = 'internal'";
749 777
         }
750
-        if ($socid)	$sql.= " AND p.fk_soc = ".$socid;
751
-        if ($projectid) $sql.= " AND p.rowid in (".$projectid.")";
752
-        if ($filteronprojref) $sql.= " AND p.ref LIKE '%".$filteronprojref."%'";
753
-        if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus;
754
-        if ($morewherefilter) $sql.=$morewherefilter;
778
+        if ($socid) {
779
+        	$sql.= " AND p.fk_soc = ".$socid;
780
+        }
781
+        if ($projectid) {
782
+        	$sql.= " AND p.rowid in (".$projectid.")";
783
+        }
784
+        if ($filteronprojref) {
785
+        	$sql.= " AND p.ref LIKE '%".$filteronprojref."%'";
786
+        }
787
+        if ($filteronprojstatus > -1) {
788
+        	$sql.= " AND p.fk_statut = ".$filteronprojstatus;
789
+        }
790
+        if ($morewherefilter) {
791
+        	$sql.=$morewherefilter;
792
+        }
755 793
         $sql.= " ORDER BY p.ref, t.rang, t.dateo";
756 794
 
757 795
         //print $sql;exit;
@@ -768,18 +806,22 @@  discard block
 block discarded – undo
768 806
 
769 807
                 $obj = $this->db->fetch_object($resql);
770 808
 
771
-                if ((! $obj->public) && (is_object($userp)))	// If not public project and we ask a filter on project owned by a user
809
+                if ((! $obj->public) && (is_object($userp))) {
810
+                	// If not public project and we ask a filter on project owned by a user
772 811
                 {
773 812
                     if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0))
774 813
                     {
775 814
                         $error++;
815
+                }
776 816
                     }
777 817
                 }
778
-                if (is_object($usert))							// If we ask a filter on a user affected to a task
818
+                if (is_object($usert)) {
819
+                	// If we ask a filter on a user affected to a task
779 820
                 {
780 821
                     if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid))
781 822
                     {
782 823
                         $error++;
824
+                }
783 825
                     }
784 826
                 }
785 827
 
@@ -812,8 +854,7 @@  discard block
 block discarded – undo
812 854
                 $i++;
813 855
             }
814 856
             $this->db->free($resql);
815
-        }
816
-        else
857
+        } else
817 858
         {
818 859
             dol_print_error($this->db);
819 860
         }
@@ -851,30 +892,56 @@  discard block
 block discarded – undo
851 892
 
852 893
         /* Liste des taches et role sur les projets ou taches */
853 894
         $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source";
854
-        if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt";
855
-        if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
856
-        if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
895
+        if ($userp) {
896
+        	$sql.= " FROM ".MAIN_DB_PREFIX."projet as pt";
897
+        }
898
+        if ($usert && $filteronprojstatus > -1) {
899
+        	$sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
900
+        }
901
+        if ($usert && $filteronprojstatus <= -1) {
902
+        	$sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
903
+        }
857 904
         $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
858 905
         $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
859 906
         $sql.= " WHERE pt.rowid = ec.element_id";
860
-        if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus;
861
-        if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
862
-        if ($userp) $sql.= " AND ctc.element = 'project'";
863
-        if ($usert) $sql.= " AND ctc.element = 'project_task'";
907
+        if ($userp && $filteronprojstatus > -1) {
908
+        	$sql.= " AND pt.fk_statut = ".$filteronprojstatus;
909
+        }
910
+        if ($usert && $filteronprojstatus > -1) {
911
+        	$sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus;
912
+        }
913
+        if ($userp) {
914
+        	$sql.= " AND ctc.element = 'project'";
915
+        }
916
+        if ($usert) {
917
+        	$sql.= " AND ctc.element = 'project_task'";
918
+        }
864 919
         $sql.= " AND ctc.rowid = ec.fk_c_type_contact";
865
-        if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id;
866
-        if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id;
920
+        if ($userp) {
921
+        	$sql.= " AND ec.fk_socpeople = ".$userp->id;
922
+        }
923
+        if ($usert) {
924
+        	$sql.= " AND ec.fk_socpeople = ".$usert->id;
925
+        }
867 926
         $sql.= " AND ec.statut = 4";
868 927
         $sql.= " AND ctc.source = 'internal'";
869 928
         if ($projectid)
870 929
         {
871
-            if ($userp) $sql.= " AND pt.rowid in (".$projectid.")";
872
-            if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")";
930
+            if ($userp) {
931
+            	$sql.= " AND pt.rowid in (".$projectid.")";
932
+            }
933
+            if ($usert) {
934
+            	$sql.= " AND pt.fk_projet in (".$projectid.")";
935
+            }
873 936
         }
874 937
         if ($taskid)
875 938
         {
876
-            if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS";
877
-            if ($usert) $sql.= " AND pt.rowid = ".$taskid;
939
+            if ($userp) {
940
+            	$sql.= " ERROR SHOULD NOT HAPPENS";
941
+            }
942
+            if ($usert) {
943
+            	$sql.= " AND pt.rowid = ".$taskid;
944
+            }
878 945
         }
879 946
         //print $sql;
880 947
 
@@ -887,13 +954,15 @@  discard block
 block discarded – undo
887 954
             while ($i < $num)
888 955
             {
889 956
                 $obj = $this->db->fetch_object($resql);
890
-                if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code;
891
-                else $arrayroles[$obj->pid].=','.$obj->code;
957
+                if (empty($arrayroles[$obj->pid])) {
958
+                	$arrayroles[$obj->pid] = $obj->code;
959
+                } else {
960
+                	$arrayroles[$obj->pid].=','.$obj->code;
961
+                }
892 962
                 $i++;
893 963
             }
894 964
             $this->db->free($resql);
895
-        }
896
-        else
965
+        } else
897 966
         {
898 967
             dol_print_error($this->db);
899 968
         }
@@ -917,8 +986,11 @@  discard block
 block discarded – undo
917 986
         $i = 0;
918 987
         while ($i < $num)
919 988
         {
920
-            if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
921
-            else  $contactAlreadySelected[$i] = $tab[$i]['id'];
989
+            if ($source == 'thirdparty') {
990
+            	$contactAlreadySelected[$i] = $tab[$i]['socid'];
991
+            } else {
992
+            	$contactAlreadySelected[$i] = $tab[$i]['id'];
993
+            }
922 994
             $i++;
923 995
         }
924 996
         return $contactAlreadySelected;
@@ -948,8 +1020,12 @@  discard block
 block discarded – undo
948 1020
         }
949 1021
 
950 1022
         // Clean parameters
951
-        if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
952
-		if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
1023
+        if (isset($this->timespent_note)) {
1024
+        	$this->timespent_note = trim($this->timespent_note);
1025
+        }
1026
+		if (empty($this->timespent_datehour)) {
1027
+			$this->timespent_datehour = $this->timespent_date;
1028
+		}
953 1029
 
954 1030
         $this->db->begin();
955 1031
 
@@ -985,8 +1061,7 @@  discard block
 block discarded – undo
985 1061
                 if ($result < 0) { $ret=-1; }
986 1062
                 // End call triggers
987 1063
             }
988
-        }
989
-        else
1064
+        } else
990 1065
 		{
991 1066
             $this->error=$this->db->lasterror();
992 1067
             $ret = -1;
@@ -997,7 +1072,10 @@  discard block
 block discarded – undo
997 1072
         	// Recalculate amount of time spent for task and update denormalized field
998 1073
             $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
999 1074
             $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")";
1000
-			if (isset($this->progress)) $sql.= ", progress = " . $this->progress;	// Do not overwrite value if not provided
1075
+			if (isset($this->progress)) {
1076
+				$sql.= ", progress = " . $this->progress;
1077
+			}
1078
+			// Do not overwrite value if not provided
1001 1079
             $sql.= " WHERE rowid = ".$this->id;
1002 1080
 
1003 1081
             dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
@@ -1022,8 +1100,7 @@  discard block
 block discarded – undo
1022 1100
         if ($ret >0)
1023 1101
         {
1024 1102
         	$this->db->commit();
1025
-        }
1026
-        else
1103
+        } else
1027 1104
 		{
1028 1105
         	$this->db->rollback();
1029 1106
         }
@@ -1058,7 +1135,9 @@  discard block
 block discarded – undo
1058 1135
         $sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull";
1059 1136
         $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
1060 1137
         $sql.= " WHERE t.fk_task = ".$id;
1061
-        if ($userid > 0) $sql.=" AND t.fk_user = ".$userid;
1138
+        if ($userid > 0) {
1139
+        	$sql.=" AND t.fk_user = ".$userid;
1140
+        }
1062 1141
 
1063 1142
         dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1064 1143
         $resql=$this->db->query($sql);
@@ -1078,8 +1157,7 @@  discard block
 block discarded – undo
1078 1157
             $this->timespent_nblines=($obj->nblines?$obj->nblines:0);
1079 1158
 
1080 1159
             $this->db->free($resql);
1081
-        }
1082
-        else
1160
+        } else
1083 1161
         {
1084 1162
             dol_print_error($this->db);
1085 1163
         }
@@ -1098,7 +1176,9 @@  discard block
 block discarded – undo
1098 1176
     {
1099 1177
         global $langs;
1100 1178
 
1101
-        if (empty($id)) $id=$this->id;
1179
+        if (empty($id)) {
1180
+        	$id=$this->id;
1181
+        }
1102 1182
 
1103 1183
         $result=array();
1104 1184
 
@@ -1135,8 +1215,7 @@  discard block
 block discarded – undo
1135 1215
 
1136 1216
             $this->db->free($resql);
1137 1217
             return $result;
1138
-        }
1139
-        else
1218
+        } else
1140 1219
 		{
1141 1220
             dol_print_error($this->db);
1142 1221
             return $result;
@@ -1186,8 +1265,7 @@  discard block
 block discarded – undo
1186 1265
             $this->db->free($resql);
1187 1266
 
1188 1267
             return 1;
1189
-        }
1190
-        else
1268
+        } else
1191 1269
         {
1192 1270
             $this->error="Error ".$this->db->lasterror();
1193 1271
             return -1;
@@ -1208,8 +1286,12 @@  discard block
 block discarded – undo
1208 1286
         $ret = 0;
1209 1287
 
1210 1288
         // Clean parameters
1211
-        if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date;
1212
-        if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note);
1289
+        if (empty($this->timespent_datehour)) {
1290
+        	$this->timespent_datehour = $this->timespent_date;
1291
+        }
1292
+        if (isset($this->timespent_note)) {
1293
+        	$this->timespent_note = trim($this->timespent_note);
1294
+        }
1213 1295
 
1214 1296
         $this->db->begin();
1215 1297
 
@@ -1233,13 +1315,14 @@  discard block
 block discarded – undo
1233 1315
                 {
1234 1316
                     $this->db->rollback();
1235 1317
                     $ret = -1;
1318
+                } else {
1319
+                	$ret = 1;
1236 1320
                 }
1237
-                else $ret = 1;
1238 1321
                 // End call triggers
1322
+            } else {
1323
+            	$ret = 1;
1239 1324
             }
1240
-            else $ret = 1;
1241
-        }
1242
-        else
1325
+        } else
1243 1326
         {
1244 1327
             $this->error=$this->db->lasterror();
1245 1328
             $this->db->rollback();
@@ -1263,7 +1346,9 @@  discard block
 block discarded – undo
1263 1346
             }
1264 1347
         }
1265 1348
 
1266
-        if ($ret >= 0) $this->db->commit();
1349
+        if ($ret >= 0) {
1350
+        	$this->db->commit();
1351
+        }
1267 1352
         return $ret;
1268 1353
     }
1269 1354
 
@@ -1310,8 +1395,7 @@  discard block
 block discarded – undo
1310 1395
             if ($this->db->query($sql) )
1311 1396
             {
1312 1397
                 $result = 0;
1313
-            }
1314
-            else
1398
+            } else
1315 1399
             {
1316 1400
                 $this->error=$this->db->lasterror();
1317 1401
                 $result = -2;
@@ -1328,8 +1412,7 @@  discard block
 block discarded – undo
1328 1412
             }
1329 1413
             $this->db->rollback();
1330 1414
             return -1*$error;
1331
-        }
1332
-        else
1415
+        } else
1333 1416
         {
1334 1417
             $this->db->commit();
1335 1418
             return 1;
@@ -1442,8 +1525,7 @@  discard block
 block discarded – undo
1442 1525
        		{
1443 1526
         	    $clone_task->note_private='';
1444 1527
     			$clone_task->note_public='';
1445
-        	}
1446
-        	else
1528
+        	} else
1447 1529
         	{
1448 1530
         		$this->db->begin();
1449 1531
 				$res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES),'_public');
@@ -1452,8 +1534,7 @@  discard block
 block discarded – undo
1452 1534
 					$this->error.=$clone_task->error;
1453 1535
 					$error++;
1454 1536
 					$this->db->rollback();
1455
-				}
1456
-				else
1537
+				} else
1457 1538
 				{
1458 1539
 					$this->db->commit();
1459 1540
 				}
@@ -1465,8 +1546,7 @@  discard block
 block discarded – undo
1465 1546
 					$this->error.=$clone_task->error;
1466 1547
 					$error++;
1467 1548
 					$this->db->rollback();
1468
-				}
1469
-				else
1549
+				} else
1470 1550
 				{
1471 1551
 					$this->db->commit();
1472 1552
 				}
@@ -1486,8 +1566,7 @@  discard block
 block discarded – undo
1486 1566
 	        	{
1487 1567
 	        		$projectstatic->fetch($project_id);
1488 1568
 	        		$clone_project_ref=$projectstatic->ref;
1489
-	        	}
1490
-	        	else
1569
+	        	} else
1491 1570
 	        	{
1492 1571
 	        		$clone_project_ref=$ori_project_ref;
1493 1572
 	        	}
@@ -1535,8 +1614,7 @@  discard block
 block discarded – undo
1535 1614
 							$langs->load("errors");
1536 1615
 							$this->error.=$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1537 1616
 							$error++;
1538
-						}
1539
-						else
1617
+						} else
1540 1618
 						{
1541 1619
 							if ($clone_task->error!='')
1542 1620
 							{
@@ -1561,8 +1639,7 @@  discard block
 block discarded – undo
1561 1639
 		{
1562 1640
 			$this->db->commit();
1563 1641
 			return $clone_task_id;
1564
-		}
1565
-		else
1642
+		} else
1566 1643
 		{
1567 1644
 			$this->db->rollback();
1568 1645
 			dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : " . $this->error, LOG_ERR);
@@ -1615,39 +1692,87 @@  discard block
 block discarded – undo
1615 1692
 		}
1616 1693
 		if ($mode == 2)
1617 1694
 		{
1618
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts_short[$statut]);
1619
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts_short[$statut]);
1620
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts_short[$statut]);
1621
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
1622
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts_short[$statut]);
1623
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts_short[$statut]);
1695
+			if ($statut==0) {
1696
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts_short[$statut]);
1697
+			}
1698
+			if ($statut==1) {
1699
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts_short[$statut]);
1700
+			}
1701
+			if ($statut==2) {
1702
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts_short[$statut]);
1703
+			}
1704
+			if ($statut==3) {
1705
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
1706
+			}
1707
+			if ($statut==4) {
1708
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts_short[$statut]);
1709
+			}
1710
+			if ($statut==5) {
1711
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts_short[$statut]);
1712
+			}
1624 1713
 		}
1625 1714
 		if ($mode == 3)
1626 1715
 		{
1627
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1628
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1629
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1630
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1631
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1632
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1716
+			if ($statut==0) {
1717
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1718
+			}
1719
+			if ($statut==1) {
1720
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1721
+			}
1722
+			if ($statut==2) {
1723
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1724
+			}
1725
+			if ($statut==3) {
1726
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1727
+			}
1728
+			if ($statut==4) {
1729
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1730
+			}
1731
+			if ($statut==5) {
1732
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1733
+			}
1633 1734
 		}
1634 1735
 		if ($mode == 4)
1635 1736
 		{
1636
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]);
1637
-			if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]);
1638
-			if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]);
1639
-			if ($statut==3) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
1640
-			if ($statut==4) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]);
1641
-			if ($statut==5) return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]);
1737
+			if ($statut==0) {
1738
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]);
1739
+			}
1740
+			if ($statut==1) {
1741
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]);
1742
+			}
1743
+			if ($statut==2) {
1744
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]);
1745
+			}
1746
+			if ($statut==3) {
1747
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
1748
+			}
1749
+			if ($statut==4) {
1750
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]);
1751
+			}
1752
+			if ($statut==5) {
1753
+				return img_picto($langs->trans($this->statuts_short[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]);
1754
+			}
1642 1755
 		}
1643 1756
 		if ($mode == 5)
1644 1757
 		{
1645
-			if ($statut==0) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1646
-			if ($statut==1) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1647
-			if ($statut==2) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1648
-			if ($statut==3) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1649
-			if ($statut==4) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1650
-			if ($statut==5) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1758
+			if ($statut==0) {
1759
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut0');
1760
+			}
1761
+			if ($statut==1) {
1762
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut1');
1763
+			}
1764
+			if ($statut==2) {
1765
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut3');
1766
+			}
1767
+			if ($statut==3) {
1768
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
1769
+			}
1770
+			if ($statut==4) {
1771
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
1772
+			}
1773
+			if ($statut==5) {
1774
+				return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut5');
1775
+			}
1651 1776
 		}
1652 1777
 		if ($mode == 6)
1653 1778
 		{
@@ -1716,17 +1841,25 @@  discard block
 block discarded – undo
1716 1841
 		$sql.= " t.dateo as date_start, t.datee as datee";
1717 1842
 		$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
1718 1843
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1719
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1844
+		if (! $user->rights->societe->client->voir && ! $socid) {
1845
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1846
+		}
1720 1847
 		$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
1721 1848
 		$sql.= " WHERE p.entity IN (".getEntity('project', 0).')';
1722 1849
 		$sql.= " AND p.fk_statut = 1";
1723 1850
 		$sql.= " AND t.fk_projet = p.rowid";
1724 1851
 		$sql.= " AND t.progress < 100";         // tasks to do
1725
-		if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")";
1852
+		if ($mine || ! $user->rights->projet->all->lire) {
1853
+			$sql.= " AND p.rowid IN (".$projectsListId.")";
1854
+		}
1726 1855
 		// No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
1727 1856
 		//if ($socid || ! $user->rights->societe->client->voir)	$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1728
-		if ($socid) $sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1729
-		if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1857
+		if ($socid) {
1858
+			$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1859
+		}
1860
+		if (! $user->rights->societe->client->voir && ! $socid) {
1861
+			$sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1862
+		}
1730 1863
 		//print $sql;
1731 1864
 		$resql=$this->db->query($sql);
1732 1865
 		if ($resql)
@@ -1736,8 +1869,11 @@  discard block
 block discarded – undo
1736 1869
 			$response = new WorkboardResponse();
1737 1870
 			$response->warning_delay = $conf->projet->task->warning_delay/60/60/24;
1738 1871
 			$response->label = $langs->trans("OpenedTasks");
1739
-			if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
1740
-			else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
1872
+			if ($user->rights->projet->all->lire) {
1873
+				$response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
1874
+			} else {
1875
+				$response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
1876
+			}
1741 1877
 			$response->img = img_object('',"task");
1742 1878
 			
1743 1879
 			// This assignment in condition is not a bug. It allows walking the results.
@@ -1756,8 +1892,7 @@  discard block
 block discarded – undo
1756 1892
 			}
1757 1893
 			
1758 1894
 			return $response;
1759
-		}
1760
-		else
1895
+		} else
1761 1896
 		{
1762 1897
 			$this->error=$this->db->error();
1763 1898
 			return -1;
@@ -1783,15 +1918,23 @@  discard block
 block discarded – undo
1783 1918
 		$sql = "SELECT count(p.rowid) as nb";
1784 1919
 		$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
1785 1920
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
1786
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1921
+		if (! $user->rights->societe->client->voir && ! $socid) {
1922
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
1923
+		}
1787 1924
 		$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
1788 1925
 		$sql.= " WHERE p.entity IN (".getEntity('project', 0).')';
1789 1926
 		$sql.= " AND t.fk_projet = p.rowid";         // tasks to do
1790
-		if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")";
1927
+		if ($mine || ! $user->rights->projet->all->lire) {
1928
+			$sql.= " AND p.rowid IN (".$projectsListId.")";
1929
+		}
1791 1930
 		// No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
1792 1931
 		//if ($socid || ! $user->rights->societe->client->voir)	$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1793
-		if ($socid) $sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1794
-		if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1932
+		if ($socid) {
1933
+			$sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1934
+		}
1935
+		if (! $user->rights->societe->client->voir && ! $socid) {
1936
+			$sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))";
1937
+		}
1795 1938
 		
1796 1939
 		$resql=$this->db->query($sql);
1797 1940
 		if ($resql)
@@ -1804,8 +1947,7 @@  discard block
 block discarded – undo
1804 1947
 			}
1805 1948
 			$this->db->free($resql);
1806 1949
 			return 1;
1807
-		}
1808
-		else
1950
+		} else
1809 1951
 		{
1810 1952
 			dol_print_error($this->db);
1811 1953
 			$this->error=$this->db->error();
Please login to merge, or discard this patch.
htdocs/user/class/api_deprecated_user.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -232,7 +232,7 @@
 block discarded – undo
232 232
 	 * Delete account <b>Warning: Deprecated</b>
233 233
 	 *
234 234
 	 * @param   int     $id Account ID
235
-	 * @return  array
235
+	 * @return  integer
236 236
      * 
237 237
 	 * @url	DELETE user/{id}
238 238
 	 */
Please login to merge, or discard this patch.
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -90,41 +90,41 @@  discard block
 block discarded – undo
90 90
 	 * @param   int   $contactid   Id of contact
91 91
 	 * @param   array   $request_data   Request datas
92 92
 	 * @return  int     ID of user
93
-     * 
93
+	 * 
94 94
 	 * @url	POST /contact/{contactid}/createUser
95 95
 	 */
96 96
 	function createFromContact($contactid, $request_data = NULL) {
97 97
 		//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
98 98
 			//throw new RestException(401);
99
-        //}
99
+		//}
100 100
         
101
-        if (!isset($request_data["login"]))
102
-    				throw new RestException(400, "login field missing");
103
-        if (!isset($request_data["password"]))
104
-    				throw new RestException(400, "password field missing");
105
-        if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
106
-          throw new RestException(401);
107
-        }
108
-    		$contact = new Contact($this->db);
109
-        $contact->fetch($contactid);
110
-        if ($contact->id <= 0) {
111
-          throw new RestException(404, 'Contact not found');
112
-        }
101
+		if (!isset($request_data["login"]))
102
+					throw new RestException(400, "login field missing");
103
+		if (!isset($request_data["password"]))
104
+					throw new RestException(400, "password field missing");
105
+		if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
106
+		  throw new RestException(401);
107
+		}
108
+			$contact = new Contact($this->db);
109
+		$contact->fetch($contactid);
110
+		if ($contact->id <= 0) {
111
+		  throw new RestException(404, 'Contact not found');
112
+		}
113 113
     
114
-        if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
115
-          throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
116
-        }
117
-        // Check mandatory fields
118
-        $login = $request_data["login"];
119
-        $password = $request_data["password"];
120
-        $result = $this->useraccount->create_from_contact($contact,$login,$password);
121
-        if ($result <= 0) {
122
-          throw new RestException(500, "User not created");
123
-        }
124
-        // password parameter not used in create_from_contact
125
-        $this->useraccount->setPassword($this->useraccount,$password);
114
+		if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
115
+		  throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
116
+		}
117
+		// Check mandatory fields
118
+		$login = $request_data["login"];
119
+		$password = $request_data["password"];
120
+		$result = $this->useraccount->create_from_contact($contact,$login,$password);
121
+		if ($result <= 0) {
122
+		  throw new RestException(500, "User not created");
123
+		}
124
+		// password parameter not used in create_from_contact
125
+		$this->useraccount->setPassword($this->useraccount,$password);
126 126
         
127
-        return $result;
127
+		return $result;
128 128
 	}
129 129
 	
130 130
 	
@@ -137,31 +137,31 @@  discard block
 block discarded – undo
137 137
 	 * @url POST user/
138 138
 	 */
139 139
 	function post($request_data = NULL) {
140
-	    // check user authorization
141
-	    //if(! DolibarrApiAccess::$user->rights->user->creer) {
142
-	    //   throw new RestException(401, "User creation not allowed");
143
-	    //}
144
-	    // check mandatory fields
145
-	    /*if (!isset($request_data["login"]))
140
+		// check user authorization
141
+		//if(! DolibarrApiAccess::$user->rights->user->creer) {
142
+		//   throw new RestException(401, "User creation not allowed");
143
+		//}
144
+		// check mandatory fields
145
+		/*if (!isset($request_data["login"]))
146 146
 	        throw new RestException(400, "login field missing");
147 147
 	    if (!isset($request_data["password"]))
148 148
 	        throw new RestException(400, "password field missing");
149 149
 	    if (!isset($request_data["lastname"]))
150 150
 	         throw new RestException(400, "lastname field missing");*/
151
-	    //assign field values
152
-        $xxx=var_export($request_data, true);
153
-        dol_syslog("xxx=".$xxx);
154
-        foreach ($request_data as $field => $value)
155
-	    {
156
-	          $this->useraccount->$field = $value;
157
-	    }
151
+		//assign field values
152
+		$xxx=var_export($request_data, true);
153
+		dol_syslog("xxx=".$xxx);
154
+		foreach ($request_data as $field => $value)
155
+		{
156
+			  $this->useraccount->$field = $value;
157
+		}
158 158
 	    
159
-        $result = $this->useraccount->create(DolibarrApiAccess::$user);
160
-	    if ($result <=0) {
161
-	         throw new RestException(500, "User not created : ".$this->useraccount->error);
162
-	    }
163
-	    return array('id'=>$result);
164
-    }                
159
+		$result = $this->useraccount->create(DolibarrApiAccess::$user);
160
+		if ($result <=0) {
161
+			 throw new RestException(500, "User not created : ".$this->useraccount->error);
162
+		}
163
+		return array('id'=>$result);
164
+	}                
165 165
 	
166 166
     
167 167
 	/**
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	 * @param int   $id             Id of account to update
171 171
 	 * @param array $request_data   Datas   
172 172
 	 * @return int 
173
-     * 
173
+	 * 
174 174
 	 * @url	PUT user/{id}
175 175
 	 */
176 176
 	function put($id, $request_data = NULL) {
@@ -191,49 +191,49 @@  discard block
 block discarded – undo
191 191
 
192 192
 		foreach ($request_data as $field => $value)
193 193
 		{
194
-            if ($field == 'id') continue;
195
-		    $this->useraccount->$field = $value;
194
+			if ($field == 'id') continue;
195
+			$this->useraccount->$field = $value;
196 196
 		}
197 197
 
198 198
 		if ($this->useraccount->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
199 199
 			return $this->get($id);
200 200
 
201
-        return false;
202
-    }
201
+		return false;
202
+	}
203 203
 
204
-    /**
204
+	/**
205 205
 	 * add user to group <b>Warning: Deprecated</b>
206 206
 	 *
207 207
 	 * @param   int     $id User ID
208 208
 	 * @param   int     $group Group ID
209 209
 	 * @return  int
210
-     * 
210
+	 * 
211 211
 	 * @url	GET user/{id}/setGroup/{group}
212 212
 	 */
213 213
 	function setGroup($id,$group) {
214 214
 		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
215 215
 			//throw new RestException(401);
216 216
 		//}
217
-        $result = $this->useraccount->fetch($id);
218
-        if (!$result)
219
-        {
220
-          throw new RestException(404, 'User not found');
221
-        }
217
+		$result = $this->useraccount->fetch($id);
218
+		if (!$result)
219
+		{
220
+		  throw new RestException(404, 'User not found');
221
+		}
222 222
     
223
-        if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
224
-        {
225
-          throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
226
-        }
223
+		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
224
+		{
225
+		  throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
226
+		}
227 227
     
228
-        return $this->useraccount->SetInGroup($group,1);
229
-    }
228
+		return $this->useraccount->SetInGroup($group,1);
229
+	}
230 230
 
231 231
 	/**
232 232
 	 * Delete account <b>Warning: Deprecated</b>
233 233
 	 *
234 234
 	 * @param   int     $id Account ID
235 235
 	 * @return  array
236
-     * 
236
+	 * 
237 237
 	 * @url	DELETE user/{id}
238 238
 	 */
239 239
 	function delete($id) {
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 
257 257
 	/**
258 258
 	 * Validate fields before create or update object
259
-     * 
259
+	 * 
260 260
 	 * @param   array|null     $data   Data to validate
261 261
 	 * @return  array
262 262
 	 * @throws RestException
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 
79 79
 		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
80 80
 		{
81
-			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
81
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
82 82
 		}
83 83
 
84 84
 		return $this->_cleanObjectDatas($this->useraccount);
@@ -112,17 +112,17 @@  discard block
 block discarded – undo
112 112
         }
113 113
     
114 114
         if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
115
-          throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
115
+          throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
116 116
         }
117 117
         // Check mandatory fields
118 118
         $login = $request_data["login"];
119 119
         $password = $request_data["password"];
120
-        $result = $this->useraccount->create_from_contact($contact,$login,$password);
120
+        $result = $this->useraccount->create_from_contact($contact, $login, $password);
121 121
         if ($result <= 0) {
122 122
           throw new RestException(500, "User not created");
123 123
         }
124 124
         // password parameter not used in create_from_contact
125
-        $this->useraccount->setPassword($this->useraccount,$password);
125
+        $this->useraccount->setPassword($this->useraccount, $password);
126 126
         
127 127
         return $result;
128 128
 	}
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	    if (!isset($request_data["lastname"]))
150 150
 	         throw new RestException(400, "lastname field missing");*/
151 151
 	    //assign field values
152
-        $xxx=var_export($request_data, true);
152
+        $xxx = var_export($request_data, true);
153 153
         dol_syslog("xxx=".$xxx);
154 154
         foreach ($request_data as $field => $value)
155 155
 	    {
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 	    }
158 158
 	    
159 159
         $result = $this->useraccount->create(DolibarrApiAccess::$user);
160
-	    if ($result <=0) {
160
+	    if ($result <= 0) {
161 161
 	         throw new RestException(500, "User not created : ".$this->useraccount->error);
162 162
 	    }
163 163
 	    return array('id'=>$result);
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 
187 187
 		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
188 188
 		{
189
-			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
189
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
190 190
 		}
191 191
 
192 192
 		foreach ($request_data as $field => $value)
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
      * 
211 211
 	 * @url	GET user/{id}/setGroup/{group}
212 212
 	 */
213
-	function setGroup($id,$group) {
213
+	function setGroup($id, $group) {
214 214
 		//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
215 215
 			//throw new RestException(401);
216 216
 		//}
@@ -222,10 +222,10 @@  discard block
 block discarded – undo
222 222
     
223 223
         if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
224 224
         {
225
-          throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
225
+          throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
226 226
         }
227 227
     
228
-        return $this->useraccount->SetInGroup($group,1);
228
+        return $this->useraccount->SetInGroup($group, 1);
229 229
     }
230 230
 
231 231
 	/**
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 
249 249
 		if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
250 250
 		{
251
-			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
251
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
252 252
 		}
253 253
 
254 254
 		return $this->useraccount->delete($id);
Please login to merge, or discard this patch.
Braces   +15 added lines, -9 removed lines patch added patch discarded remove patch
@@ -98,10 +98,12 @@  discard block
 block discarded – undo
98 98
 			//throw new RestException(401);
99 99
         //}
100 100
         
101
-        if (!isset($request_data["login"]))
102
-    				throw new RestException(400, "login field missing");
103
-        if (!isset($request_data["password"]))
104
-    				throw new RestException(400, "password field missing");
101
+        if (!isset($request_data["login"])) {
102
+            				throw new RestException(400, "login field missing");
103
+        }
104
+        if (!isset($request_data["password"])) {
105
+            				throw new RestException(400, "password field missing");
106
+        }
105 107
         if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
106 108
           throw new RestException(401);
107 109
         }
@@ -191,12 +193,15 @@  discard block
 block discarded – undo
191 193
 
192 194
 		foreach ($request_data as $field => $value)
193 195
 		{
194
-            if ($field == 'id') continue;
196
+            if ($field == 'id') {
197
+            	continue;
198
+            }
195 199
 		    $this->useraccount->$field = $value;
196 200
 		}
197 201
 
198
-		if ($this->useraccount->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
199
-			return $this->get($id);
202
+		if ($this->useraccount->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) {
203
+					return $this->get($id);
204
+		}
200 205
 
201 206
         return false;
202 207
     }
@@ -265,8 +270,9 @@  discard block
 block discarded – undo
265 270
 		$account = array();
266 271
 		foreach (UserApi::$FIELDS as $field)
267 272
 		{
268
-			if (!isset($data[$field]))
269
-				throw new RestException(400, "$field field missing");
273
+			if (!isset($data[$field])) {
274
+							throw new RestException(400, "$field field missing");
275
+			}
270 276
 			$account[$field] = $data[$field];
271 277
 		}
272 278
 		return $account;
Please login to merge, or discard this patch.
htdocs/fourn/class/fournisseur.commande.class.php 4 patches
Doc Comments   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
      *  Returns the following order reference not used depending on the numbering model activated
644 644
      *                  defined within COMMANDE_SUPPLIER_ADDON_NUMBER
645 645
      *
646
-     *  @param	    Company		$soc  		company object
646
+     *  @param	    Societe		$soc  		company object
647 647
      *  @return     string                  free reference for the invoice
648 648
      */
649 649
     public function getNextNumRef($soc)
@@ -1337,9 +1337,9 @@  discard block
 block discarded – undo
1337 1337
      *  @param		bool	$notrigger				Disable triggers
1338 1338
      *  @param		int		$date_start				Date start of service
1339 1339
      *  @param		int		$date_end				Date end of service
1340
-	 *  @param		array	$array_options			extrafields array
1340
+	 *  @param		integer	$array_options			extrafields array
1341 1341
      *  @param 		string	$fk_unit 				Code of the unit to use. Null to use the default one
1342
-	 *  @param 		string	$pu_ht_devise			Amount in currency
1342
+	 *  @param 		integer	$pu_ht_devise			Amount in currency
1343 1343
 	 *  @param		string	$origin					'order', ...
1344 1344
 	 *  @param		int		$origin_id				Id of origin object
1345 1345
      *	@return     int             				<=0 if KO, >0 if OK
@@ -1580,7 +1580,7 @@  discard block
 block discarded – undo
1580 1580
      * @param 	int			$product				Id of product to dispatch
1581 1581
      * @param 	double		$qty					Qty to dispatch
1582 1582
      * @param 	int			$entrepot				Id of warehouse to add product
1583
-     * @param 	double		$price					Unit Price for PMP value calculation (Unit price without Tax and taking into account discount)
1583
+     * @param 	integer		$price					Unit Price for PMP value calculation (Unit price without Tax and taking into account discount)
1584 1584
      * @param	string		$comment				Comment for stock movement
1585 1585
 	 * @param	date		$eatby					eat-by date
1586 1586
 	 * @param	date		$sellby					sell-by date
@@ -2267,17 +2267,17 @@  discard block
 block discarded – undo
2267 2267
      *	@param     	double		$qty             	Quantity
2268 2268
      *	@param     	double		$remise_percent  	Pourcentage de remise de la ligne
2269 2269
      *	@param     	double		$txtva          	Taux TVA
2270
-     *  @param     	double		$txlocaltax1	    Localtax1 tax
2271
-     *  @param     	double		$txlocaltax2   		Localtax2 tax
2270
+     *  @param     	integer		$txlocaltax1	    Localtax1 tax
2271
+     *  @param     	integer		$txlocaltax2   		Localtax2 tax
2272 2272
      *  @param     	double		$price_base_type 	Type of price base
2273 2273
      *	@param		int			$info_bits			Miscellaneous informations
2274 2274
      *	@param		int			$type				Type of line (0=product, 1=service)
2275 2275
      *  @param		int			$notrigger			Disable triggers
2276 2276
      *  @param      timestamp   $date_start     	Date start of service
2277 2277
      *  @param      timestamp   $date_end       	Date end of service
2278
-	 *  @param		array		$array_options		Extrafields array
2278
+	 *  @param		integer		$array_options		Extrafields array
2279 2279
      * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2280
-	 * 	@param		double		$pu_ht_devise		Unit price in currency
2280
+	 * 	@param		integer		$pu_ht_devise		Unit price in currency
2281 2281
      *	@return    	int         	    			< 0 if error, > 0 if ok
2282 2282
      */
2283 2283
     public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0)
@@ -2720,7 +2720,7 @@  discard block
 block discarded – undo
2720 2720
      * Return the max number delivery delay in day
2721 2721
      *
2722 2722
      * @param	Translate	$langs		Language object
2723
-     * @return 							Translated string
2723
+     * @return 							string string
2724 2724
      */
2725 2725
     public function getMaxDeliveryTimeDay($langs)
2726 2726
 	{
Please login to merge, or discard this patch.
Indentation   +2954 added lines, -2954 removed lines patch added patch discarded remove patch
@@ -39,217 +39,217 @@  discard block
 block discarded – undo
39 39
  */
40 40
 class CommandeFournisseur extends CommonOrder
41 41
 {
42
-    public $element='order_supplier';
43
-    public $table_element='commande_fournisseur';
44
-    public $table_element_line = 'commande_fournisseurdet';
45
-    public $fk_element = 'fk_commande';
46
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
-    public $picto='order';
42
+	public $element='order_supplier';
43
+	public $table_element='commande_fournisseur';
44
+	public $table_element_line = 'commande_fournisseurdet';
45
+	public $fk_element = 'fk_commande';
46
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
+	public $picto='order';
48 48
 
49
-    /**
50
-     * {@inheritdoc}
51
-     */
52
-    protected $table_ref_field = 'ref';
49
+	/**
50
+	 * {@inheritdoc}
51
+	 */
52
+	protected $table_ref_field = 'ref';
53 53
 
54
-    public $id;
54
+	public $id;
55 55
 
56 56
 	/**
57 57
 	 * Supplier order reference
58 58
 	 * @var string
59 59
 	 */
60
-    public $ref;
61
-    public $ref_supplier;
62
-    public $brouillon;
63
-    public $statut;			// 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
64
-    //                                                              -> 7=Canceled/Never received -> (reopen) 3=Process runing
65
-    //									              -> 6=Canceled -> (reopen) 2=Approved
66
-    //  		                                      -> 9=Refused  -> (reopen) 1=Validated
67
-    //  Note: billed or not is on another field "billed"
68
-    public $statuts;           // List of status
69
-
70
-    public $socid;
71
-    public $fourn_id;
72
-    public $date;
73
-    public $date_valid;
74
-    public $date_approve;
75
-    public $date_approve2;		// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
76
-    public $date_commande;
77
-
78
-    /**
79
-     * Delivery date
80
-     */
81
-    public $date_livraison;
82
-    public $total_ht;
83
-    public $total_tva;
84
-    public $total_localtax1;   // Total Local tax 1
85
-    public $total_localtax2;   // Total Local tax 2
86
-    public $total_ttc;
87
-    public $source;
60
+	public $ref;
61
+	public $ref_supplier;
62
+	public $brouillon;
63
+	public $statut;			// 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
64
+	//                                                              -> 7=Canceled/Never received -> (reopen) 3=Process runing
65
+	//									              -> 6=Canceled -> (reopen) 2=Approved
66
+	//  		                                      -> 9=Refused  -> (reopen) 1=Validated
67
+	//  Note: billed or not is on another field "billed"
68
+	public $statuts;           // List of status
69
+
70
+	public $socid;
71
+	public $fourn_id;
72
+	public $date;
73
+	public $date_valid;
74
+	public $date_approve;
75
+	public $date_approve2;		// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
76
+	public $date_commande;
77
+
78
+	/**
79
+	 * Delivery date
80
+	 */
81
+	public $date_livraison;
82
+	public $total_ht;
83
+	public $total_tva;
84
+	public $total_localtax1;   // Total Local tax 1
85
+	public $total_localtax2;   // Total Local tax 2
86
+	public $total_ttc;
87
+	public $source;
88 88
 	/**
89 89
 	 * @deprecated
90 90
 	 * @see note_private, note_public
91 91
 	 */
92
-    public $note;
92
+	public $note;
93 93
 	public $note_private;
94
-    public $note_public;
95
-    public $model_pdf;
96
-    public $fk_project;
97
-    public $cond_reglement_id;
98
-    public $cond_reglement_code;
99
-    public $fk_account;
100
-    public $mode_reglement_id;
101
-    public $mode_reglement_code;
102
-    public $user_author_id;
103
-    public $user_valid_id;
104
-    public $user_approve_id;
105
-    public $user_approve_id2;	// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
94
+	public $note_public;
95
+	public $model_pdf;
96
+	public $fk_project;
97
+	public $cond_reglement_id;
98
+	public $cond_reglement_code;
99
+	public $fk_account;
100
+	public $mode_reglement_id;
101
+	public $mode_reglement_code;
102
+	public $user_author_id;
103
+	public $user_valid_id;
104
+	public $user_approve_id;
105
+	public $user_approve_id2;	// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
106 106
 
107 107
 	//Incoterms
108
-    public $fk_incoterms;
109
-    public $location_incoterms;
110
-    public $libelle_incoterms;  //Used into tooltip
108
+	public $fk_incoterms;
109
+	public $location_incoterms;
110
+	public $libelle_incoterms;  //Used into tooltip
111 111
 
112
-    public $extraparams=array();
112
+	public $extraparams=array();
113 113
 
114 114
 	/**
115 115
 	 * @var CommandeFournisseurLigne[]
116 116
 	 */
117 117
 	public $lines = array();
118 118
 	//Add for supplier_proposal
119
-    public $origin;
120
-    public $origin_id;
121
-    public $linked_objects=array();
119
+	public $origin;
120
+	public $origin_id;
121
+	public $linked_objects=array();
122 122
 
123 123
 	// Multicurrency
124
-    public $fk_multicurrency;
125
-    public $multicurrency_code;
126
-    public $multicurrency_tx;
127
-    public $multicurrency_total_ht;
128
-    public $multicurrency_total_tva;
129
-    public $multicurrency_total_ttc;
124
+	public $fk_multicurrency;
125
+	public $multicurrency_code;
126
+	public $multicurrency_tx;
127
+	public $multicurrency_total_ht;
128
+	public $multicurrency_total_tva;
129
+	public $multicurrency_total_ttc;
130
+
131
+	/**
132
+	 * Draft status
133
+	 */
134
+	const STATUS_DRAFT = 0;
130 135
 
131
-    /**
132
-     * Draft status
133
-     */
134
-    const STATUS_DRAFT = 0;
135 136
 
136 137
 
138
+	/**
139
+	 * 	Constructor
140
+	 *
141
+	 *  @param      DoliDB		$db      Database handler
142
+	 */
143
+	public function __construct($db)
144
+	{
145
+		global $conf;
146
+
147
+		$this->db = $db;
148
+		$this->products = array();
149
+
150
+		// List of language codes for status
151
+		$this->statuts[0] = 'StatusOrderDraft';
152
+		$this->statuts[1] = 'StatusOrderValidated';
153
+		$this->statuts[2] = 'StatusOrderApproved';
154
+		if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusOrderOnProcess';
155
+		else $this->statuts[3] = 'StatusOrderOnProcessWithValidation';
156
+		$this->statuts[4] = 'StatusOrderReceivedPartially';
157
+		$this->statuts[5] = 'StatusOrderReceivedAll';
158
+		$this->statuts[6] = 'StatusOrderCanceled';	// Approved->Canceled
159
+		$this->statuts[7] = 'StatusOrderCanceled';	// Process running->canceled
160
+		//$this->statuts[8] = 'StatusOrderBilled';	// Everything is finished, order received totally and bill received
161
+		$this->statuts[9] = 'StatusOrderRefused';
162
+	}
163
+
137 164
 
138 165
 	/**
139
-     * 	Constructor
140
-     *
141
-     *  @param      DoliDB		$db      Database handler
142
-     */
143
-    public function __construct($db)
144
-    {
145
-    	global $conf;
146
-
147
-        $this->db = $db;
148
-        $this->products = array();
149
-
150
-        // List of language codes for status
151
-        $this->statuts[0] = 'StatusOrderDraft';
152
-        $this->statuts[1] = 'StatusOrderValidated';
153
-        $this->statuts[2] = 'StatusOrderApproved';
154
-        if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusOrderOnProcess';
155
-        else $this->statuts[3] = 'StatusOrderOnProcessWithValidation';
156
-        $this->statuts[4] = 'StatusOrderReceivedPartially';
157
-        $this->statuts[5] = 'StatusOrderReceivedAll';
158
-        $this->statuts[6] = 'StatusOrderCanceled';	// Approved->Canceled
159
-        $this->statuts[7] = 'StatusOrderCanceled';	// Process running->canceled
160
-        //$this->statuts[8] = 'StatusOrderBilled';	// Everything is finished, order received totally and bill received
161
-        $this->statuts[9] = 'StatusOrderRefused';
162
-    }
163
-
164
-
165
-    /**
166
-     *	Get object and lines from database
167
-     *
168
-     * 	@param	int		$id			Id of order to load
169
-     * 	@param	string	$ref		Ref of object
170
-     *	@return int 		        >0 if OK, <0 if KO, 0 if not found
171
-     */
172
-    public function fetch($id,$ref='')
173
-    {
174
-        global $conf;
175
-
176
-        // Check parameters
177
-        if (empty($id) && empty($ref)) return -1;
178
-
179
-        $sql = "SELECT c.rowid, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,";
180
-        $sql.= " c.localtax1, c.localtax2, ";
181
-        $sql.= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
182
-        $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
183
-        $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
184
-        $sql.= " c.fk_account,";
185
-        $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
166
+	 *	Get object and lines from database
167
+	 *
168
+	 * 	@param	int		$id			Id of order to load
169
+	 * 	@param	string	$ref		Ref of object
170
+	 *	@return int 		        >0 if OK, <0 if KO, 0 if not found
171
+	 */
172
+	public function fetch($id,$ref='')
173
+	{
174
+		global $conf;
175
+
176
+		// Check parameters
177
+		if (empty($id) && empty($ref)) return -1;
178
+
179
+		$sql = "SELECT c.rowid, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,";
180
+		$sql.= " c.localtax1, c.localtax2, ";
181
+		$sql.= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
182
+		$sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
183
+		$sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
184
+		$sql.= " c.fk_account,";
185
+		$sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
186 186
 		$sql.= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
187
-        $sql.= " cm.libelle as methode_commande,";
188
-        $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
189
-        $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
190
-        $sql.= ', c.fk_incoterms, c.location_incoterms';
191
-        $sql.= ', i.libelle as libelle_incoterms';
192
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
193
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
194
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
195
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
187
+		$sql.= " cm.libelle as methode_commande,";
188
+		$sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
189
+		$sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
190
+		$sql.= ', c.fk_incoterms, c.location_incoterms';
191
+		$sql.= ', i.libelle as libelle_incoterms';
192
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
193
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
194
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
195
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
196 196
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
197
-        $sql.= " WHERE c.entity = ".$conf->entity;
198
-        if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
199
-        else $sql.= " AND c.rowid=".$id;
200
-
201
-        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
202
-        $resql = $this->db->query($sql);
203
-        if ($resql)
204
-        {
205
-            $obj = $this->db->fetch_object($resql);
206
-            if (! $obj)
207
-            {
208
-                $this->error='Bill with id '.$id.' not found';
209
-                dol_syslog(get_class($this).'::fetch '.$this->error);
210
-                return 0;
211
-            }
212
-
213
-            $this->id					= $obj->rowid;
214
-            $this->ref					= $obj->ref;
215
-            $this->ref_supplier			= $obj->ref_supplier;
216
-            $this->socid				= $obj->fk_soc;
217
-            $this->fourn_id				= $obj->fk_soc;
218
-            $this->statut				= $obj->fk_statut;
219
-            $this->billed				= $obj->billed;
220
-            $this->user_author_id		= $obj->fk_user_author;
221
-            $this->user_valid_id		= $obj->fk_user_valid;
222
-            $this->user_approve_id		= $obj->fk_user_approve;
223
-            $this->user_approve_id2		= $obj->fk_user_approve2;
224
-            $this->total_ht				= $obj->total_ht;
225
-            $this->total_tva			= $obj->total_vat;
226
-            $this->total_localtax1		= $obj->localtax1;
227
-            $this->total_localtax2		= $obj->localtax2;
228
-            $this->total_ttc			= $obj->total_ttc;
229
-            $this->date					= $this->db->jdate($obj->date_creation);
230
-            $this->date_valid			= $this->db->jdate($obj->date_valid);
231
-            $this->date_approve			= $this->db->jdate($obj->date_approve);
232
-            $this->date_approve2		= $this->db->jdate($obj->date_approve2);
233
-            $this->date_commande		= $this->db->jdate($obj->date_commande); // date we make the order to supplier
197
+		$sql.= " WHERE c.entity = ".$conf->entity;
198
+		if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
199
+		else $sql.= " AND c.rowid=".$id;
200
+
201
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
202
+		$resql = $this->db->query($sql);
203
+		if ($resql)
204
+		{
205
+			$obj = $this->db->fetch_object($resql);
206
+			if (! $obj)
207
+			{
208
+				$this->error='Bill with id '.$id.' not found';
209
+				dol_syslog(get_class($this).'::fetch '.$this->error);
210
+				return 0;
211
+			}
212
+
213
+			$this->id					= $obj->rowid;
214
+			$this->ref					= $obj->ref;
215
+			$this->ref_supplier			= $obj->ref_supplier;
216
+			$this->socid				= $obj->fk_soc;
217
+			$this->fourn_id				= $obj->fk_soc;
218
+			$this->statut				= $obj->fk_statut;
219
+			$this->billed				= $obj->billed;
220
+			$this->user_author_id		= $obj->fk_user_author;
221
+			$this->user_valid_id		= $obj->fk_user_valid;
222
+			$this->user_approve_id		= $obj->fk_user_approve;
223
+			$this->user_approve_id2		= $obj->fk_user_approve2;
224
+			$this->total_ht				= $obj->total_ht;
225
+			$this->total_tva			= $obj->total_vat;
226
+			$this->total_localtax1		= $obj->localtax1;
227
+			$this->total_localtax2		= $obj->localtax2;
228
+			$this->total_ttc			= $obj->total_ttc;
229
+			$this->date					= $this->db->jdate($obj->date_creation);
230
+			$this->date_valid			= $this->db->jdate($obj->date_valid);
231
+			$this->date_approve			= $this->db->jdate($obj->date_approve);
232
+			$this->date_approve2		= $this->db->jdate($obj->date_approve2);
233
+			$this->date_commande		= $this->db->jdate($obj->date_commande); // date we make the order to supplier
234 234
 			$this->date_livraison       = $this->db->jdate($obj->date_livraison);
235
-            $this->remise_percent		= $obj->remise_percent;
236
-            $this->methode_commande_id	= $obj->fk_input_method;
237
-            $this->methode_commande		= $obj->methode_commande;
238
-
239
-            $this->source				= $obj->source;
240
-            $this->fk_project			= $obj->fk_project;
241
-            $this->cond_reglement_id	= $obj->fk_cond_reglement;
242
-            $this->cond_reglement_code	= $obj->cond_reglement_code;
243
-            $this->cond_reglement		= $obj->cond_reglement_libelle;
244
-            $this->cond_reglement_doc	= $obj->cond_reglement_libelle;
245
-            $this->fk_account           = $obj->fk_account;
246
-            $this->mode_reglement_id	= $obj->fk_mode_reglement;
247
-            $this->mode_reglement_code	= $obj->mode_reglement_code;
248
-            $this->mode_reglement		= $obj->mode_reglement_libelle;
249
-            $this->note					= $obj->note_private;    // deprecated
250
-            $this->note_private			= $obj->note_private;
251
-            $this->note_public			= $obj->note_public;
252
-            $this->modelpdf				= $obj->model_pdf;
235
+			$this->remise_percent		= $obj->remise_percent;
236
+			$this->methode_commande_id	= $obj->fk_input_method;
237
+			$this->methode_commande		= $obj->methode_commande;
238
+
239
+			$this->source				= $obj->source;
240
+			$this->fk_project			= $obj->fk_project;
241
+			$this->cond_reglement_id	= $obj->fk_cond_reglement;
242
+			$this->cond_reglement_code	= $obj->cond_reglement_code;
243
+			$this->cond_reglement		= $obj->cond_reglement_libelle;
244
+			$this->cond_reglement_doc	= $obj->cond_reglement_libelle;
245
+			$this->fk_account           = $obj->fk_account;
246
+			$this->mode_reglement_id	= $obj->fk_mode_reglement;
247
+			$this->mode_reglement_code	= $obj->mode_reglement_code;
248
+			$this->mode_reglement		= $obj->mode_reglement_libelle;
249
+			$this->note					= $obj->note_private;    // deprecated
250
+			$this->note_private			= $obj->note_private;
251
+			$this->note_public			= $obj->note_public;
252
+			$this->modelpdf				= $obj->model_pdf;
253 253
 
254 254
 			//Incoterms
255 255
 			$this->fk_incoterms = $obj->fk_incoterms;
@@ -264,86 +264,86 @@  discard block
 block discarded – undo
264 264
 			$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
265 265
 			$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
266 266
 
267
-            $this->extraparams			= (array) json_decode($obj->extraparams, true);
267
+			$this->extraparams			= (array) json_decode($obj->extraparams, true);
268 268
 
269
-            $this->db->free($resql);
269
+			$this->db->free($resql);
270 270
 
271
-            // Retrieve all extrafields
272
-            // fetch optionals attributes and labels
273
-            require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
274
-            $extrafields=new ExtraFields($this->db);
275
-            $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
276
-            $this->fetch_optionals($this->id,$extralabels);
271
+			// Retrieve all extrafields
272
+			// fetch optionals attributes and labels
273
+			require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
274
+			$extrafields=new ExtraFields($this->db);
275
+			$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
276
+			$this->fetch_optionals($this->id,$extralabels);
277 277
 
278
-            if ($this->statut == 0) $this->brouillon = 1;
278
+			if ($this->statut == 0) $this->brouillon = 1;
279 279
 
280 280
 			$this->fetchObjectLinked();
281 281
 
282 282
 			//$result=$this->fetch_lines();
283
-            $this->lines=array();
284
-
285
-            $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
286
-            $sql.= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
287
-            $sql.= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
288
-            $sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
289
-            $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,";
290
-	        $sql.= " l.fk_unit,";
291
-            $sql.= " l.date_start, l.date_end,";
283
+			$this->lines=array();
284
+
285
+			$sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
286
+			$sql.= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
287
+			$sql.= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
288
+			$sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
289
+			$sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,";
290
+			$sql.= " l.fk_unit,";
291
+			$sql.= " l.date_start, l.date_end,";
292 292
 			$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
293
-            $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet	as l";
294
-            $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
295
-            $sql.= " WHERE l.fk_commande = ".$this->id;
296
-            $sql.= " ORDER BY l.rang, l.rowid";
297
-            //print $sql;
298
-
299
-            dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG);
300
-            $result = $this->db->query($sql);
301
-            if ($result)
302
-            {
303
-                $num = $this->db->num_rows($result);
304
-                $i = 0;
305
-
306
-                while ($i < $num)
307
-                {
308
-                    $objp                  = $this->db->fetch_object($result);
309
-
310
-                    $line                 = new CommandeFournisseurLigne($this->db);
311
-
312
-                    $line->id                  = $objp->rowid;
313
-                    $line->desc                = $objp->description;
314
-                    $line->description         = $objp->description;
315
-                    $line->qty                 = $objp->qty;
316
-                    $line->tva_tx              = $objp->tva_tx;
317
-                    $line->localtax1_tx		   = $objp->localtax1_tx;
318
-                    $line->localtax2_tx		   = $objp->localtax2_tx;
319
-                    $line->localtax1_type	   = $objp->localtax1_type;
320
-                    $line->localtax2_type	   = $objp->localtax2_type;
321
-                    $line->subprice            = $objp->subprice;
322
-                    $line->pu_ht	           = $objp->subprice;
323
-                    $line->remise_percent      = $objp->remise_percent;
324
-
325
-                    $line->vat_src_code        = $objp->vat_src_code;
326
-                    $line->total_ht            = $objp->total_ht;
327
-                    $line->total_tva           = $objp->total_tva;
328
-                    $line->total_localtax1	   = $objp->total_localtax1;
329
-                    $line->total_localtax2	   = $objp->total_localtax2;
330
-                    $line->total_ttc           = $objp->total_ttc;
331
-                    $line->product_type        = $objp->product_type;
332
-
333
-                    $line->fk_product          = $objp->fk_product;
334
-
335
-                    $line->libelle             = $objp->product_label;
336
-                    $line->product_label       = $objp->product_label;
337
-                    $line->product_desc        = $objp->product_desc;
338
-
339
-                    $line->ref                 = $objp->product_ref;    // Ref of product
340
-                    $line->product_ref         = $objp->product_ref;    // Ref of product
341
-                    $line->ref_fourn           = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
342
-                    $line->ref_supplier        = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
343
-
344
-                    $line->date_start          = $this->db->jdate($objp->date_start);
345
-                    $line->date_end            = $this->db->jdate($objp->date_end);
346
-	                $line->fk_unit             = $objp->fk_unit;
293
+			$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet	as l";
294
+			$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
295
+			$sql.= " WHERE l.fk_commande = ".$this->id;
296
+			$sql.= " ORDER BY l.rang, l.rowid";
297
+			//print $sql;
298
+
299
+			dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG);
300
+			$result = $this->db->query($sql);
301
+			if ($result)
302
+			{
303
+				$num = $this->db->num_rows($result);
304
+				$i = 0;
305
+
306
+				while ($i < $num)
307
+				{
308
+					$objp                  = $this->db->fetch_object($result);
309
+
310
+					$line                 = new CommandeFournisseurLigne($this->db);
311
+
312
+					$line->id                  = $objp->rowid;
313
+					$line->desc                = $objp->description;
314
+					$line->description         = $objp->description;
315
+					$line->qty                 = $objp->qty;
316
+					$line->tva_tx              = $objp->tva_tx;
317
+					$line->localtax1_tx		   = $objp->localtax1_tx;
318
+					$line->localtax2_tx		   = $objp->localtax2_tx;
319
+					$line->localtax1_type	   = $objp->localtax1_type;
320
+					$line->localtax2_type	   = $objp->localtax2_type;
321
+					$line->subprice            = $objp->subprice;
322
+					$line->pu_ht	           = $objp->subprice;
323
+					$line->remise_percent      = $objp->remise_percent;
324
+
325
+					$line->vat_src_code        = $objp->vat_src_code;
326
+					$line->total_ht            = $objp->total_ht;
327
+					$line->total_tva           = $objp->total_tva;
328
+					$line->total_localtax1	   = $objp->total_localtax1;
329
+					$line->total_localtax2	   = $objp->total_localtax2;
330
+					$line->total_ttc           = $objp->total_ttc;
331
+					$line->product_type        = $objp->product_type;
332
+
333
+					$line->fk_product          = $objp->fk_product;
334
+
335
+					$line->libelle             = $objp->product_label;
336
+					$line->product_label       = $objp->product_label;
337
+					$line->product_desc        = $objp->product_desc;
338
+
339
+					$line->ref                 = $objp->product_ref;    // Ref of product
340
+					$line->product_ref         = $objp->product_ref;    // Ref of product
341
+					$line->ref_fourn           = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
342
+					$line->ref_supplier        = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
343
+
344
+					$line->date_start          = $this->db->jdate($objp->date_start);
345
+					$line->date_end            = $this->db->jdate($objp->date_end);
346
+					$line->fk_unit             = $objp->fk_unit;
347 347
 
348 348
 					// Multicurrency
349 349
 					$line->fk_multicurrency 		= $objp->fk_multicurrency;
@@ -353,924 +353,924 @@  discard block
 block discarded – undo
353 353
 					$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
354 354
 					$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
355 355
 
356
-	                $line->special_code        = $objp->special_code;
357
-	                $line->fk_parent_line      = $objp->fk_parent_line;
358
-
359
-                    $line->rang                = $objp->rang;
360
-
361
-                    $this->lines[$i]      = $line;
362
-
363
-                    $i++;
364
-                }
365
-                $this->db->free($result);
366
-
367
-                return 1;
368
-            }
369
-            else
370
-            {
371
-                $this->error=$this->db->error()." sql=".$sql;
372
-                return -1;
373
-            }
374
-        }
375
-        else
376
-        {
377
-            $this->error=$this->db->error()." sql=".$sql;
378
-            return -1;
379
-        }
380
-    }
381
-
382
-    /**
383
-     *	Validate an order
384
-     *
385
-     *	@param	User	$user			Validator User
386
-     *	@param	int		$idwarehouse	Id of warehouse to use for stock decrease
387
-     *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
388
-     *	@return	int						<0 if KO, >0 if OK
389
-     */
390
-    public function valid($user,$idwarehouse=0,$notrigger=0)
391
-    {
392
-        global $langs,$conf;
393
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
394
-
395
-        $error=0;
396
-
397
-        dol_syslog(get_class($this)."::valid");
398
-        $result = 0;
399
-        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
400
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
401
-        {
402
-            $this->db->begin();
403
-
404
-            // Definition of supplier order numbering model name
405
-            $soc = new Societe($this->db);
406
-            $soc->fetch($this->fourn_id);
407
-
408
-            // Check if object has a temporary ref
409
-            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
410
-            {
411
-                $num = $this->getNextNumRef($soc);
412
-            }
413
-            else
414
-			{
415
-                $num = $this->ref;
416
-            }
417
-            $this->newref = $num;
418
-
419
-            $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
420
-            $sql.= " SET ref='".$this->db->escape($num)."',";
421
-            $sql.= " fk_statut = 1,";
422
-            $sql.= " date_valid='".$this->db->idate(dol_now())."',";
423
-            $sql.= " fk_user_valid = ".$user->id;
424
-            $sql.= " WHERE rowid = ".$this->id;
425
-            $sql.= " AND fk_statut = 0";
426
-
427
-            $resql=$this->db->query($sql);
428
-            if (! $resql)
429
-            {
430
-                dol_print_error($this->db);
431
-                $error++;
432
-            }
433
-
434
-            if (! $error && ! $notrigger)
435
-            {
356
+					$line->special_code        = $objp->special_code;
357
+					$line->fk_parent_line      = $objp->fk_parent_line;
358
+
359
+					$line->rang                = $objp->rang;
360
+
361
+					$this->lines[$i]      = $line;
362
+
363
+					$i++;
364
+				}
365
+				$this->db->free($result);
366
+
367
+				return 1;
368
+			}
369
+			else
370
+			{
371
+				$this->error=$this->db->error()." sql=".$sql;
372
+				return -1;
373
+			}
374
+		}
375
+		else
376
+		{
377
+			$this->error=$this->db->error()." sql=".$sql;
378
+			return -1;
379
+		}
380
+	}
381
+
382
+	/**
383
+	 *	Validate an order
384
+	 *
385
+	 *	@param	User	$user			Validator User
386
+	 *	@param	int		$idwarehouse	Id of warehouse to use for stock decrease
387
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
388
+	 *	@return	int						<0 if KO, >0 if OK
389
+	 */
390
+	public function valid($user,$idwarehouse=0,$notrigger=0)
391
+	{
392
+		global $langs,$conf;
393
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
394
+
395
+		$error=0;
396
+
397
+		dol_syslog(get_class($this)."::valid");
398
+		$result = 0;
399
+		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
400
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
401
+		{
402
+			$this->db->begin();
403
+
404
+			// Definition of supplier order numbering model name
405
+			$soc = new Societe($this->db);
406
+			$soc->fetch($this->fourn_id);
407
+
408
+			// Check if object has a temporary ref
409
+			if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
410
+			{
411
+				$num = $this->getNextNumRef($soc);
412
+			}
413
+			else
414
+			{
415
+				$num = $this->ref;
416
+			}
417
+			$this->newref = $num;
418
+
419
+			$sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
420
+			$sql.= " SET ref='".$this->db->escape($num)."',";
421
+			$sql.= " fk_statut = 1,";
422
+			$sql.= " date_valid='".$this->db->idate(dol_now())."',";
423
+			$sql.= " fk_user_valid = ".$user->id;
424
+			$sql.= " WHERE rowid = ".$this->id;
425
+			$sql.= " AND fk_statut = 0";
426
+
427
+			$resql=$this->db->query($sql);
428
+			if (! $resql)
429
+			{
430
+				dol_print_error($this->db);
431
+				$error++;
432
+			}
433
+
434
+			if (! $error && ! $notrigger)
435
+			{
436 436
 				// Call trigger
437 437
 				$result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE',$user);
438 438
 				if ($result < 0) $error++;
439 439
 				// End call triggers
440
-            }
441
-
442
-            if (! $error)
443
-            {
444
-	            $this->oldref = $this->ref;
445
-
446
-                // Rename directory if dir was a temporary ref
447
-                if (preg_match('/^[\(]?PROV/i', $this->ref))
448
-                {
449
-                    // We rename directory ($this->ref = ancienne ref, $num = nouvelle ref)
450
-                    // in order not to lose the attached files
451
-                    $oldref = dol_sanitizeFileName($this->ref);
452
-                    $newref = dol_sanitizeFileName($num);
453
-                    $dirsource = $conf->fournisseur->dir_output.'/commande/'.$oldref;
454
-                    $dirdest = $conf->fournisseur->dir_output.'/commande/'.$newref;
455
-                    if (file_exists($dirsource))
456
-                    {
457
-                        dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
458
-
459
-                        if (@rename($dirsource, $dirdest))
460
-                        {
461
-                            dol_syslog("Rename ok");
462
-                            // Rename docs starting with $oldref with $newref
463
-	                        $listoffiles=dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
464
-	                        foreach($listoffiles as $fileentry)
465
-	                        {
466
-	                        	$dirsource=$fileentry['name'];
467
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
468
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
469
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
470
-	                        	@rename($dirsource, $dirdest);
471
-	                        }
472
-                        }
473
-                    }
474
-                }
475
-            }
476
-
477
-            if (! $error)
478
-            {
479
-                $result = 1;
480
-                $this->statut = 1;
481
-                $this->ref = $num;
482
-            }
483
-
484
-            if (! $error)
485
-            {
486
-                $this->db->commit();
487
-                return 1;
488
-            }
489
-            else
490
-            {
491
-                $this->db->rollback();
492
-                return -1;
493
-            }
494
-        }
495
-        else
496
-        {
497
-            $this->error='NotAuthorized';
498
-            dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
499
-            return -1;
500
-        }
501
-    }
502
-
503
-    /**
504
-     *  Return label of the status of object
505
-     *
440
+			}
441
+
442
+			if (! $error)
443
+			{
444
+				$this->oldref = $this->ref;
445
+
446
+				// Rename directory if dir was a temporary ref
447
+				if (preg_match('/^[\(]?PROV/i', $this->ref))
448
+				{
449
+					// We rename directory ($this->ref = ancienne ref, $num = nouvelle ref)
450
+					// in order not to lose the attached files
451
+					$oldref = dol_sanitizeFileName($this->ref);
452
+					$newref = dol_sanitizeFileName($num);
453
+					$dirsource = $conf->fournisseur->dir_output.'/commande/'.$oldref;
454
+					$dirdest = $conf->fournisseur->dir_output.'/commande/'.$newref;
455
+					if (file_exists($dirsource))
456
+					{
457
+						dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
458
+
459
+						if (@rename($dirsource, $dirdest))
460
+						{
461
+							dol_syslog("Rename ok");
462
+							// Rename docs starting with $oldref with $newref
463
+							$listoffiles=dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
464
+							foreach($listoffiles as $fileentry)
465
+							{
466
+								$dirsource=$fileentry['name'];
467
+								$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
468
+								$dirsource=$fileentry['path'].'/'.$dirsource;
469
+								$dirdest=$fileentry['path'].'/'.$dirdest;
470
+								@rename($dirsource, $dirdest);
471
+							}
472
+						}
473
+					}
474
+				}
475
+			}
476
+
477
+			if (! $error)
478
+			{
479
+				$result = 1;
480
+				$this->statut = 1;
481
+				$this->ref = $num;
482
+			}
483
+
484
+			if (! $error)
485
+			{
486
+				$this->db->commit();
487
+				return 1;
488
+			}
489
+			else
490
+			{
491
+				$this->db->rollback();
492
+				return -1;
493
+			}
494
+		}
495
+		else
496
+		{
497
+			$this->error='NotAuthorized';
498
+			dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
499
+			return -1;
500
+		}
501
+	}
502
+
503
+	/**
504
+	 *  Return label of the status of object
505
+	 *
506 506
 	 *  @param      int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto
507
-     *  @return 	string        			Label
508
-     */
509
-    public function getLibStatut($mode=0)
510
-    {
511
-        return $this->LibStatut($this->statut,$mode,$this->billed);
512
-    }
513
-
514
-    /**
515
-     *  Return label of a status
516
-     *
517
-     * 	@param  int		$statut		Id statut
518
-     *  @param  int		$mode       0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
519
-     *  @param  int     $billed     1=Billed
520
-     *  @return string				Label of status
521
-     */
522
-    function LibStatut($statut,$mode=0,$billed=0)
523
-    {
524
-        global $langs;
525
-        $langs->load('orders');
526
-
527
-        $billedtext='';
507
+	 *  @return 	string        			Label
508
+	 */
509
+	public function getLibStatut($mode=0)
510
+	{
511
+		return $this->LibStatut($this->statut,$mode,$this->billed);
512
+	}
513
+
514
+	/**
515
+	 *  Return label of a status
516
+	 *
517
+	 * 	@param  int		$statut		Id statut
518
+	 *  @param  int		$mode       0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
519
+	 *  @param  int     $billed     1=Billed
520
+	 *  @return string				Label of status
521
+	 */
522
+	function LibStatut($statut,$mode=0,$billed=0)
523
+	{
524
+		global $langs;
525
+		$langs->load('orders');
526
+
527
+		$billedtext='';
528 528
 		//if ($statut==5 && $this->billed == 1) $statut = 8;
529
-        if ($billed == 1) $billedtext=$langs->trans("Billed");
530
-
531
-        // List of language codes for status
532
-        $statutshort[0] = 'StatusOrderDraftShort';
533
-        $statutshort[1] = 'StatusOrderValidatedShort';
534
-        $statutshort[2] = 'StatusOrderApprovedShort';
535
-        $statutshort[3] = 'StatusOrderOnProcessShort';
536
-        $statutshort[4] = 'StatusOrderReceivedPartiallyShort';
537
-        $statutshort[5] = 'StatusOrderReceivedAllShort';
538
-        $statutshort[6] = 'StatusOrderCanceledShort';
539
-        $statutshort[7] = 'StatusOrderCanceledShort';
540
-        //$statutshort[8] = 'StatusOrderBilledShort';
541
-        $statutshort[9] = 'StatusOrderRefusedShort';
542
-
543
-        if ($mode == 0)
544
-        {
545
-            return $langs->trans($this->statuts[$statut]);
546
-        }
547
-        if ($mode == 1)
548
-        {
549
-            return $langs->trans($statutshort[$statut]);
550
-        }
551
-        if ($mode == 2)
552
-        {
553
-            return $langs->trans($this->statuts[$statut]);
554
-        }
555
-        if ($mode == 3)
556
-        {
557
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
558
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1');
559
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
560
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
561
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
562
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
563
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
529
+		if ($billed == 1) $billedtext=$langs->trans("Billed");
530
+
531
+		// List of language codes for status
532
+		$statutshort[0] = 'StatusOrderDraftShort';
533
+		$statutshort[1] = 'StatusOrderValidatedShort';
534
+		$statutshort[2] = 'StatusOrderApprovedShort';
535
+		$statutshort[3] = 'StatusOrderOnProcessShort';
536
+		$statutshort[4] = 'StatusOrderReceivedPartiallyShort';
537
+		$statutshort[5] = 'StatusOrderReceivedAllShort';
538
+		$statutshort[6] = 'StatusOrderCanceledShort';
539
+		$statutshort[7] = 'StatusOrderCanceledShort';
540
+		//$statutshort[8] = 'StatusOrderBilledShort';
541
+		$statutshort[9] = 'StatusOrderRefusedShort';
542
+
543
+		if ($mode == 0)
544
+		{
545
+			return $langs->trans($this->statuts[$statut]);
546
+		}
547
+		if ($mode == 1)
548
+		{
549
+			return $langs->trans($statutshort[$statut]);
550
+		}
551
+		if ($mode == 2)
552
+		{
553
+			return $langs->trans($this->statuts[$statut]);
554
+		}
555
+		if ($mode == 3)
556
+		{
557
+			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
558
+			if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1');
559
+			if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
560
+			if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
561
+			if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
562
+			if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
563
+			if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
564 564
 			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
565
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
566
-        }
567
-        if ($mode == 4)
568
-        {
569
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
570
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
571
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
572
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
573
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
574
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
575
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
565
+			if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
566
+		}
567
+		if ($mode == 4)
568
+		{
569
+			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
570
+			if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
571
+			if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
572
+			if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
573
+			if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
574
+			if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
575
+			if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
576 576
 			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
577
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
578
-        }
579
-        if ($mode == 5)
580
-        {
581
-            if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
582
-            if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
583
-            if ($statut==2) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
584
-            if ($statut==3) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
585
-            if ($statut==4) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
586
-            if ($statut==5) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
587
-            if ($statut==6 || $statut==7) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
588
-            if ($statut==8) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
589
-            if ($statut==9) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
590
-        }
591
-    }
592
-
593
-
594
-    /**
595
-     *	Return clicable name (with picto eventually)
596
-     *
597
-     *	@param		int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
598
-     *	@param		string	$option						On what the link points
599
-     *  @param	    int   	$notooltip					1=Disable tooltip
600
-     *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
601
-     *	@return		string								Chain with URL
602
-     */
603
-    public function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
604
-    {
605
-        global $langs, $conf;
606
-
607
-        $result='';
608
-        $label = '<u>' . $langs->trans("ShowOrder") . '</u>';
609
-        if (! empty($this->ref))
610
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
611
-        if (! empty($this->ref_supplier))
612
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
613
-        if (! empty($this->total_ht))
614
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
615
-        if (! empty($this->total_tva))
616
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
617
-        if (! empty($this->total_ttc))
618
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
619
-
620
-        $picto='order';
621
-        $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
622
-
623
-        if ($option !== 'nolink')
624
-        {
625
-        	// Add param to save lastsearch_values or not
626
-        	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
627
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
628
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
629
-        }
630
-
631
-        $linkclose='';
632
-        if (empty($notooltip))
633
-        {
634
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
635
-            {
636
-                $label=$langs->trans("ShowOrder");
637
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
638
-            }
639
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
640
-            $linkclose.=' class="classfortooltip"';
641
-        }
642
-
643
-        $linkstart = '<a href="'.$url.'"';
644
-        $linkstart.=$linkclose.'>';
645
-        $linkend='</a>';
646
-
647
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
648
-        if ($withpicto && $withpicto != 2) $result.=' ';
649
-        $result.=$linkstart.$this->ref.$linkend;
650
-        return $result;
651
-    }
652
-
653
-
654
-    /**
655
-     *  Returns the following order reference not used depending on the numbering model activated
656
-     *                  defined within COMMANDE_SUPPLIER_ADDON_NUMBER
657
-     *
658
-     *  @param	    Company		$soc  		company object
659
-     *  @return     string                  free reference for the invoice
660
-     */
661
-    public function getNextNumRef($soc)
662
-    {
663
-        global $db, $langs, $conf;
664
-        $langs->load("orders");
665
-
666
-        if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
667
-        {
668
-            $mybool = false;
669
-
670
-            $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
671
-            $classname=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
672
-
673
-            // Include file with class
674
-            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
675
-
676
-            foreach ($dirmodels as $reldir) {
677
-
678
-                $dir = dol_buildpath($reldir."core/modules/supplier_order/");
679
-
680
-                // Load file with numbering class (if found)
681
-                $mybool|=@include_once $dir.$file;
682
-            }
683
-
684
-            if (! $mybool)
685
-            {
686
-                dol_print_error('',"Failed to include file ".$file);
687
-                return '';
688
-            }
689
-
690
-            $obj = new $classname();
691
-            $numref = $obj->getNextValue($soc,$this);
692
-
693
-            if ( $numref != "")
694
-            {
695
-                return $numref;
696
-            }
697
-            else
698
-			{
699
-                $this->error = $obj->error;
700
-                return -1;
701
-            }
702
-        }
703
-        else
704
-		{
705
-            $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
706
-            return -2;
707
-        }
708
-    }
577
+			if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
578
+		}
579
+		if ($mode == 5)
580
+		{
581
+			if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
582
+			if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
583
+			if ($statut==2) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
584
+			if ($statut==3) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
585
+			if ($statut==4) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
586
+			if ($statut==5) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
587
+			if ($statut==6 || $statut==7) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
588
+			if ($statut==8) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
589
+			if ($statut==9) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
590
+		}
591
+	}
592
+
593
+
594
+	/**
595
+	 *	Return clicable name (with picto eventually)
596
+	 *
597
+	 *	@param		int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
598
+	 *	@param		string	$option						On what the link points
599
+	 *  @param	    int   	$notooltip					1=Disable tooltip
600
+	 *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
601
+	 *	@return		string								Chain with URL
602
+	 */
603
+	public function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
604
+	{
605
+		global $langs, $conf;
606
+
607
+		$result='';
608
+		$label = '<u>' . $langs->trans("ShowOrder") . '</u>';
609
+		if (! empty($this->ref))
610
+			$label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
611
+		if (! empty($this->ref_supplier))
612
+			$label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
613
+		if (! empty($this->total_ht))
614
+			$label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
615
+		if (! empty($this->total_tva))
616
+			$label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
617
+		if (! empty($this->total_ttc))
618
+			$label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
619
+
620
+		$picto='order';
621
+		$url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
622
+
623
+		if ($option !== 'nolink')
624
+		{
625
+			// Add param to save lastsearch_values or not
626
+			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
627
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
628
+			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
629
+		}
630
+
631
+		$linkclose='';
632
+		if (empty($notooltip))
633
+		{
634
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
635
+			{
636
+				$label=$langs->trans("ShowOrder");
637
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
638
+			}
639
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
640
+			$linkclose.=' class="classfortooltip"';
641
+		}
642
+
643
+		$linkstart = '<a href="'.$url.'"';
644
+		$linkstart.=$linkclose.'>';
645
+		$linkend='</a>';
646
+
647
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
648
+		if ($withpicto && $withpicto != 2) $result.=' ';
649
+		$result.=$linkstart.$this->ref.$linkend;
650
+		return $result;
651
+	}
652
+
653
+
654
+	/**
655
+	 *  Returns the following order reference not used depending on the numbering model activated
656
+	 *                  defined within COMMANDE_SUPPLIER_ADDON_NUMBER
657
+	 *
658
+	 *  @param	    Company		$soc  		company object
659
+	 *  @return     string                  free reference for the invoice
660
+	 */
661
+	public function getNextNumRef($soc)
662
+	{
663
+		global $db, $langs, $conf;
664
+		$langs->load("orders");
665
+
666
+		if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
667
+		{
668
+			$mybool = false;
669
+
670
+			$file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
671
+			$classname=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
672
+
673
+			// Include file with class
674
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
675
+
676
+			foreach ($dirmodels as $reldir) {
677
+
678
+				$dir = dol_buildpath($reldir."core/modules/supplier_order/");
679
+
680
+				// Load file with numbering class (if found)
681
+				$mybool|=@include_once $dir.$file;
682
+			}
683
+
684
+			if (! $mybool)
685
+			{
686
+				dol_print_error('',"Failed to include file ".$file);
687
+				return '';
688
+			}
689
+
690
+			$obj = new $classname();
691
+			$numref = $obj->getNextValue($soc,$this);
692
+
693
+			if ( $numref != "")
694
+			{
695
+				return $numref;
696
+			}
697
+			else
698
+			{
699
+				$this->error = $obj->error;
700
+				return -1;
701
+			}
702
+		}
703
+		else
704
+		{
705
+			$this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
706
+			return -2;
707
+		}
708
+	}
709 709
 	/**
710
-     *	Class invoiced the supplier order
711
-     *
712
-     *  @param      User        $user       Object user making the change
713
-     *	@return     int     	            <0 if KO, >0 if KO
714
-     */
715
-    public function classifyBilled(User $user)
716
-    {
717
-        $error=0;
718
-        $this->db->begin();
719
-
720
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
721
-        $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0 ';
722
-        if ($this->db->query($sql))
723
-        {
724
-        	if (! $error)
725
-        	{
726
-        	    // Call trigger
727
-        	    $result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED',$user);
728
-        	    if ($result < 0) $error++;
729
-        	    // End call triggers
730
-        	}
731
-
732
-        	if (! $error)
733
-        	{
734
-        	    $this->billed=1;
735
-
736
-        	    $this->db->commit();
737
-        	    return 1;
738
-        	}
739
-        	else
740
-        	{
741
-        	    $this->db->rollback();
742
-                return -1;
743
-        	}
744
-        }
745
-        else
746
-        {
747
-        	dol_print_error($this->db);
748
-
749
-        	$this->db->rollback();
710
+	 *	Class invoiced the supplier order
711
+	 *
712
+	 *  @param      User        $user       Object user making the change
713
+	 *	@return     int     	            <0 if KO, >0 if KO
714
+	 */
715
+	public function classifyBilled(User $user)
716
+	{
717
+		$error=0;
718
+		$this->db->begin();
719
+
720
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
721
+		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0 ';
722
+		if ($this->db->query($sql))
723
+		{
724
+			if (! $error)
725
+			{
726
+				// Call trigger
727
+				$result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED',$user);
728
+				if ($result < 0) $error++;
729
+				// End call triggers
730
+			}
731
+
732
+			if (! $error)
733
+			{
734
+				$this->billed=1;
735
+
736
+				$this->db->commit();
737
+				return 1;
738
+			}
739
+			else
740
+			{
741
+				$this->db->rollback();
742
+				return -1;
743
+			}
744
+		}
745
+		else
746
+		{
747
+			dol_print_error($this->db);
748
+
749
+			$this->db->rollback();
750 750
 			return -1;
751
-        }
752
-    }
753
-
754
-    /**
755
-     * 	Approve a supplier order
756
-     *
757
-     *	@param	User	$user			Object user
758
-     *	@param	int		$idwarehouse	Id of warhouse for stock change
759
-     *  @param	int		$secondlevel	0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
760
-     *	@return	int						<0 if KO, >0 if OK
761
-     */
762
-    public function approve($user, $idwarehouse=0, $secondlevel=0)
763
-    {
764
-        global $langs,$conf;
751
+		}
752
+	}
753
+
754
+	/**
755
+	 * 	Approve a supplier order
756
+	 *
757
+	 *	@param	User	$user			Object user
758
+	 *	@param	int		$idwarehouse	Id of warhouse for stock change
759
+	 *  @param	int		$secondlevel	0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
760
+	 *	@return	int						<0 if KO, >0 if OK
761
+	 */
762
+	public function approve($user, $idwarehouse=0, $secondlevel=0)
763
+	{
764
+		global $langs,$conf;
765 765
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
766 766
 
767
-        $error=0;
767
+		$error=0;
768 768
 
769
-        dol_syslog(get_class($this)."::approve");
769
+		dol_syslog(get_class($this)."::approve");
770 770
 
771
-        if ($user->rights->fournisseur->commande->approuver)
772
-        {
773
-        	$now = dol_now();
771
+		if ($user->rights->fournisseur->commande->approuver)
772
+		{
773
+			$now = dol_now();
774 774
 
775
-            $this->db->begin();
775
+			$this->db->begin();
776 776
 
777 777
 			// Definition of order numbering model name
778
-            $soc = new Societe($this->db);
779
-            $soc->fetch($this->fourn_id);
778
+			$soc = new Societe($this->db);
779
+			$soc->fetch($this->fourn_id);
780 780
 
781
-            // Check if object has a temporary ref
782
-            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
783
-            {
784
-                $num = $this->getNextNumRef($soc);
785
-            }
786
-            else
781
+			// Check if object has a temporary ref
782
+			if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
783
+			{
784
+				$num = $this->getNextNumRef($soc);
785
+			}
786
+			else
787 787
 			{
788
-                $num = $this->ref;
789
-            }
790
-            $this->newref = $num;
788
+				$num = $this->ref;
789
+			}
790
+			$this->newref = $num;
791 791
 
792
-            // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
792
+			// Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
793 793
 			$movetoapprovestatus=true;
794 794
 			$comment='';
795 795
 
796
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
796
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
797 797
 			$sql.= " SET ref='".$this->db->escape($num)."',";
798 798
 			if (empty($secondlevel))	// standard or first level approval
799 799
 			{
800
-	            $sql.= " date_approve='".$this->db->idate($now)."',";
801
-    	        $sql.= " fk_user_approve = ".$user->id;
802
-    	        if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
803
-    	        {
804
-    	        	if (empty($this->user_approve_id2))
805
-    	        	{
806
-    	        	    $movetoapprovestatus=false;		// second level approval not done
807
-    	        	    $comment=' (first level)';
808
-    	        	}
809
-    	        }
800
+				$sql.= " date_approve='".$this->db->idate($now)."',";
801
+				$sql.= " fk_user_approve = ".$user->id;
802
+				if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
803
+				{
804
+					if (empty($this->user_approve_id2))
805
+					{
806
+						$movetoapprovestatus=false;		// second level approval not done
807
+						$comment=' (first level)';
808
+					}
809
+				}
810 810
 			}
811 811
 			else	// request a second level approval
812 812
 			{
813
-            	$sql.= " date_approve2='".$this->db->idate($now)."',";
814
-            	$sql.= " fk_user_approve2 = ".$user->id;
815
-    	        if (empty($this->user_approve_id)) $movetoapprovestatus=false;		// first level approval not done
816
-    	        $comment=' (second level)';
813
+				$sql.= " date_approve2='".$this->db->idate($now)."',";
814
+				$sql.= " fk_user_approve2 = ".$user->id;
815
+				if (empty($this->user_approve_id)) $movetoapprovestatus=false;		// first level approval not done
816
+				$comment=' (second level)';
817 817
 			}
818 818
 			// If double approval is required and first approval, we keep status to 1 = validated
819 819
 			if ($movetoapprovestatus) $sql.= ", fk_statut = 2";
820 820
 			else $sql.= ", fk_statut = 1";
821
-            $sql.= " WHERE rowid = ".$this->id;
822
-            $sql.= " AND fk_statut = 1";
821
+			$sql.= " WHERE rowid = ".$this->id;
822
+			$sql.= " AND fk_statut = 1";
823 823
 
824
-            if ($this->db->query($sql))
825
-            {
826
-            	if (! empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
827
-	            {
824
+			if ($this->db->query($sql))
825
+			{
826
+				if (! empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
827
+				{
828 828
 					$result=$this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
829 829
 					if ($result < 0 && $result != -2)	// -2 means already exists
830 830
 					{
831 831
 						$error++;
832 832
 					}
833
-	            }
834
-
835
-                // If stock is incremented on validate order, we must increment it
836
-                if (! $error && $movetoapprovestatus && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
837
-                {
838
-                    require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
839
-                    $langs->load("agenda");
840
-
841
-                    $cpt=count($this->lines);
842
-                    for ($i = 0; $i < $cpt; $i++)
843
-                    {
844
-                        // Product with reference
845
-                        if ($this->lines[$i]->fk_product > 0)
846
-                        {
847
-                            $this->line = $this->lines[$i];
848
-                            $mouvP = new MouvementStock($this->db);
849
-                            $mouvP->origin = &$this;
850
-                            // We decrement stock of product (and sub-products)
851
-	                        $up_ht_disc=$this->lines[$i]->subprice;
852
-    	                    if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
853
-                            $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr",$this->ref));
854
-                            if ($result < 0) { $error++; }
855
-                            unset($this->line);
856
-                        }
857
-                    }
858
-                }
859
-
860
-                if (! $error)
861
-                {
833
+				}
834
+
835
+				// If stock is incremented on validate order, we must increment it
836
+				if (! $error && $movetoapprovestatus && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
837
+				{
838
+					require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
839
+					$langs->load("agenda");
840
+
841
+					$cpt=count($this->lines);
842
+					for ($i = 0; $i < $cpt; $i++)
843
+					{
844
+						// Product with reference
845
+						if ($this->lines[$i]->fk_product > 0)
846
+						{
847
+							$this->line = $this->lines[$i];
848
+							$mouvP = new MouvementStock($this->db);
849
+							$mouvP->origin = &$this;
850
+							// We decrement stock of product (and sub-products)
851
+							$up_ht_disc=$this->lines[$i]->subprice;
852
+							if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
853
+							$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr",$this->ref));
854
+							if ($result < 0) { $error++; }
855
+							unset($this->line);
856
+						}
857
+					}
858
+				}
859
+
860
+				if (! $error)
861
+				{
862 862
 					// Call trigger
863 863
 					$result=$this->call_trigger('ORDER_SUPPLIER_APPROVE',$user);
864 864
 					if ($result < 0) $error++;
865 865
 					// End call triggers
866
-                }
866
+				}
867 867
 
868
-                if (! $error)
869
-                {
870
-                	$this->ref = $this->newref;
868
+				if (! $error)
869
+				{
870
+					$this->ref = $this->newref;
871 871
 
872
-                	if ($movetoapprovestatus) $this->statut = 2;
872
+					if ($movetoapprovestatus) $this->statut = 2;
873 873
 					else $this->statut = 1;
874
-           			if (empty($secondlevel))	// standard or first level approval
874
+		   			if (empty($secondlevel))	// standard or first level approval
875 875
 					{
876
-			            $this->date_approve = $now;
877
-		    	        $this->user_approve_id = $user->id;
876
+						$this->date_approve = $now;
877
+						$this->user_approve_id = $user->id;
878 878
 					}
879 879
 					else	// request a second level approval
880 880
 					{
881
-			            $this->date_approve2 = $now;
882
-		    	        $this->user_approve_id2 = $user->id;
881
+						$this->date_approve2 = $now;
882
+						$this->user_approve_id2 = $user->id;
883 883
 					}
884 884
 
885
-                    $this->db->commit();
886
-                    return 1;
887
-                }
888
-                else
889
-                {
890
-                    $this->db->rollback();
891
-                    return -1;
892
-                }
893
-            }
894
-            else
895
-            {
896
-                $this->db->rollback();
897
-                $this->error=$this->db->lasterror();
898
-                return -1;
899
-            }
900
-        }
901
-        else
902
-        {
903
-            dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
904
-        }
905
-        return -1;
906
-    }
907
-
908
-    /**
909
-     * 	Refuse an order
910
-     *
911
-     * 	@param		User	$user		User making action
912
-     *	@return		int					0 if Ok, <0 if Ko
913
-     */
914
-    public function refuse($user)
915
-    {
916
-        global $conf, $langs;
885
+					$this->db->commit();
886
+					return 1;
887
+				}
888
+				else
889
+				{
890
+					$this->db->rollback();
891
+					return -1;
892
+				}
893
+			}
894
+			else
895
+			{
896
+				$this->db->rollback();
897
+				$this->error=$this->db->lasterror();
898
+				return -1;
899
+			}
900
+		}
901
+		else
902
+		{
903
+			dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
904
+		}
905
+		return -1;
906
+	}
907
+
908
+	/**
909
+	 * 	Refuse an order
910
+	 *
911
+	 * 	@param		User	$user		User making action
912
+	 *	@return		int					0 if Ok, <0 if Ko
913
+	 */
914
+	public function refuse($user)
915
+	{
916
+		global $conf, $langs;
917 917
 
918 918
 		$error=0;
919 919
 
920
-        dol_syslog(get_class($this)."::refuse");
921
-        $result = 0;
922
-        if ($user->rights->fournisseur->commande->approuver)
923
-        {
924
-            $this->db->begin();
920
+		dol_syslog(get_class($this)."::refuse");
921
+		$result = 0;
922
+		if ($user->rights->fournisseur->commande->approuver)
923
+		{
924
+			$this->db->begin();
925 925
 
926
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 9";
927
-            $sql .= " WHERE rowid = ".$this->id;
926
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 9";
927
+			$sql .= " WHERE rowid = ".$this->id;
928 928
 
929
-            if ($this->db->query($sql))
930
-            {
931
-                $result = 0;
929
+			if ($this->db->query($sql))
930
+			{
931
+				$result = 0;
932 932
 
933
-                if ($error == 0)
934
-                {
933
+				if ($error == 0)
934
+				{
935 935
 					// Call trigger
936 936
 					$result=$this->call_trigger('ORDER_SUPPLIER_REFUSE',$user);
937 937
 					if ($result < 0)
938
-                    {
939
-                        $error++;
940
-                        $this->db->rollback();
941
-                    }
942
-                    else
943
-                    	$this->db->commit();
938
+					{
939
+						$error++;
940
+						$this->db->rollback();
941
+					}
942
+					else
943
+						$this->db->commit();
944 944
 					// End call triggers
945
-                }
946
-            }
947
-            else
948
-            {
949
-                $this->db->rollback();
950
-                $this->error=$this->db->lasterror();
951
-                dol_syslog(get_class($this)."::refuse Error -1");
952
-                $result = -1;
953
-            }
954
-        }
955
-        else
956
-        {
957
-            dol_syslog(get_class($this)."::refuse Not Authorized");
958
-        }
959
-        return $result ;
960
-    }
961
-
962
-    /**
963
-     * 	Cancel an approved order.
964
-     *	The cancellation is done after approval
965
-     *
966
-     * 	@param	User	$user			User making action
967
-     *	@param	int		$idwarehouse	Id warehouse to use for stock change (not used for supplier orders).
968
-     * 	@return	int						>0 if Ok, <0 if Ko
969
-     */
970
-    function Cancel($user, $idwarehouse=-1)
971
-    {
972
-        global $langs,$conf;
945
+				}
946
+			}
947
+			else
948
+			{
949
+				$this->db->rollback();
950
+				$this->error=$this->db->lasterror();
951
+				dol_syslog(get_class($this)."::refuse Error -1");
952
+				$result = -1;
953
+			}
954
+		}
955
+		else
956
+		{
957
+			dol_syslog(get_class($this)."::refuse Not Authorized");
958
+		}
959
+		return $result ;
960
+	}
961
+
962
+	/**
963
+	 * 	Cancel an approved order.
964
+	 *	The cancellation is done after approval
965
+	 *
966
+	 * 	@param	User	$user			User making action
967
+	 *	@param	int		$idwarehouse	Id warehouse to use for stock change (not used for supplier orders).
968
+	 * 	@return	int						>0 if Ok, <0 if Ko
969
+	 */
970
+	function Cancel($user, $idwarehouse=-1)
971
+	{
972
+		global $langs,$conf;
973 973
 
974 974
 		$error=0;
975 975
 
976
-        //dol_syslog("CommandeFournisseur::Cancel");
977
-        $result = 0;
978
-        if ($user->rights->fournisseur->commande->commander)
979
-        {
980
-            $statut = 6;
976
+		//dol_syslog("CommandeFournisseur::Cancel");
977
+		$result = 0;
978
+		if ($user->rights->fournisseur->commande->commander)
979
+		{
980
+			$statut = 6;
981 981
 
982
-            $this->db->begin();
982
+			$this->db->begin();
983 983
 
984
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut;
985
-            $sql .= " WHERE rowid = ".$this->id;
986
-            dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
987
-            if ($this->db->query($sql))
988
-            {
989
-                $result = 0;
984
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut;
985
+			$sql .= " WHERE rowid = ".$this->id;
986
+			dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
987
+			if ($this->db->query($sql))
988
+			{
989
+				$result = 0;
990 990
 
991 991
 				// Call trigger
992 992
 				$result=$this->call_trigger('ORDER_SUPPLIER_CANCEL',$user);
993 993
 				if ($result < 0) $error++;
994 994
 				// End call triggers
995 995
 
996
-                if ($error == 0)
997
-                {
998
-                    $this->db->commit();
999
-                    return 1;
1000
-                }
1001
-                else
1002
-                {
1003
-                    $this->db->rollback();
1004
-                    return -1;
1005
-                }
1006
-            }
1007
-            else
1008
-            {
1009
-                $this->db->rollback();
1010
-                $this->error=$this->db->lasterror();
1011
-                dol_syslog(get_class($this)."::cancel ".$this->error);
1012
-                return -1;
1013
-            }
1014
-        }
1015
-        else
1016
-        {
1017
-            dol_syslog(get_class($this)."::cancel Not Authorized");
1018
-            return -1;
1019
-        }
1020
-    }
1021
-
1022
-
1023
-    /**
1024
-     * 	Submit a supplier order to supplier
1025
-     *
1026
-     * 	@param		User	$user		User making change
1027
-     * 	@param		date	$date		Date
1028
-     * 	@param		int		$methode	Method
1029
-     * 	@param		string	$comment	Comment
1030
-     * 	@return		int			        <0 if KO, >0 if OK
1031
-     */
1032
-    public function commande($user, $date, $methode, $comment='')
1033
-    {
1034
-        global $langs;
1035
-        dol_syslog(get_class($this)."::commande");
1036
-        $error = 0;
1037
-        if ($user->rights->fournisseur->commande->commander)
1038
-        {
1039
-            $this->db->begin();
1040
-
1041
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 3, fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."'";
1042
-            $sql .= " WHERE rowid = ".$this->id;
1043
-
1044
-            dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1045
-            if ($this->db->query($sql))
1046
-            {
1047
-                $this->statut = 3;
1048
-                $this->methode_commande_id = $methode;
1049
-                $this->date_commande = $date;
1050
-
1051
-                // Call trigger
1052
-                $result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT',$user);
1053
-                if ($result < 0) $error++;
1054
-                // End call triggers
1055
-            }
1056
-            else
1057
-            {
1058
-                $error++;
1059
-                $this->error = $this->db->lasterror();
1060
-                $this->errors[] = $this->db->lasterror();
1061
-            }
1062
-
1063
-            if (! $error)
1064
-            {
1065
-                $this->db->commit();
1066
-            }
1067
-            else
1068
-            {
1069
-                $this->db->rollback();
1070
-            }
1071
-        }
1072
-        else
1073
-        {
1074
-            $error++;
1075
-            $this->error = $langs->trans('NotAuthorized');
1076
-            $this->errors[] = $langs->trans('NotAuthorized');
1077
-            dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1078
-        }
1079
-
1080
-        return ($error ? -1 : 1);
1081
-    }
1082
-
1083
-    /**
1084
-     *  Create order with draft status
1085
-     *
1086
-     *  @param      User	$user       User making creation
1087
-     *	@param		int		$notrigger	Disable all triggers
1088
-     *  @return     int         		<0 if KO, Id of supplier order if OK
1089
-     */
1090
-    public function create($user, $notrigger=0)
1091
-    {
1092
-        global $langs,$conf,$hookmanager;
1093
-
1094
-        $this->db->begin();
1095
-
1096
-		$error=0;
1097
-        $now=dol_now();
1098
-
1099
-        // Clean parameters
1100
-        if (empty($this->source)) $this->source = 0;
1101
-
1102
-		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
1103
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1104
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1105
-		if (empty($this->fk_multicurrency))
996
+				if ($error == 0)
997
+				{
998
+					$this->db->commit();
999
+					return 1;
1000
+				}
1001
+				else
1002
+				{
1003
+					$this->db->rollback();
1004
+					return -1;
1005
+				}
1006
+			}
1007
+			else
1008
+			{
1009
+				$this->db->rollback();
1010
+				$this->error=$this->db->lasterror();
1011
+				dol_syslog(get_class($this)."::cancel ".$this->error);
1012
+				return -1;
1013
+			}
1014
+		}
1015
+		else
1016
+		{
1017
+			dol_syslog(get_class($this)."::cancel Not Authorized");
1018
+			return -1;
1019
+		}
1020
+	}
1021
+
1022
+
1023
+	/**
1024
+	 * 	Submit a supplier order to supplier
1025
+	 *
1026
+	 * 	@param		User	$user		User making change
1027
+	 * 	@param		date	$date		Date
1028
+	 * 	@param		int		$methode	Method
1029
+	 * 	@param		string	$comment	Comment
1030
+	 * 	@return		int			        <0 if KO, >0 if OK
1031
+	 */
1032
+	public function commande($user, $date, $methode, $comment='')
1033
+	{
1034
+		global $langs;
1035
+		dol_syslog(get_class($this)."::commande");
1036
+		$error = 0;
1037
+		if ($user->rights->fournisseur->commande->commander)
1038
+		{
1039
+			$this->db->begin();
1040
+
1041
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 3, fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."'";
1042
+			$sql .= " WHERE rowid = ".$this->id;
1043
+
1044
+			dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1045
+			if ($this->db->query($sql))
1046
+			{
1047
+				$this->statut = 3;
1048
+				$this->methode_commande_id = $methode;
1049
+				$this->date_commande = $date;
1050
+
1051
+				// Call trigger
1052
+				$result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT',$user);
1053
+				if ($result < 0) $error++;
1054
+				// End call triggers
1055
+			}
1056
+			else
1057
+			{
1058
+				$error++;
1059
+				$this->error = $this->db->lasterror();
1060
+				$this->errors[] = $this->db->lasterror();
1061
+			}
1062
+
1063
+			if (! $error)
1064
+			{
1065
+				$this->db->commit();
1066
+			}
1067
+			else
1068
+			{
1069
+				$this->db->rollback();
1070
+			}
1071
+		}
1072
+		else
1073
+		{
1074
+			$error++;
1075
+			$this->error = $langs->trans('NotAuthorized');
1076
+			$this->errors[] = $langs->trans('NotAuthorized');
1077
+			dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1078
+		}
1079
+
1080
+		return ($error ? -1 : 1);
1081
+	}
1082
+
1083
+	/**
1084
+	 *  Create order with draft status
1085
+	 *
1086
+	 *  @param      User	$user       User making creation
1087
+	 *	@param		int		$notrigger	Disable all triggers
1088
+	 *  @return     int         		<0 if KO, Id of supplier order if OK
1089
+	 */
1090
+	public function create($user, $notrigger=0)
1091
+	{
1092
+		global $langs,$conf,$hookmanager;
1093
+
1094
+		$this->db->begin();
1095
+
1096
+		$error=0;
1097
+		$now=dol_now();
1098
+
1099
+		// Clean parameters
1100
+		if (empty($this->source)) $this->source = 0;
1101
+
1102
+		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
1103
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1104
+		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1105
+		if (empty($this->fk_multicurrency))
1106 1106
 		{
1107 1107
 			$this->multicurrency_code = $conf->currency;
1108 1108
 			$this->fk_multicurrency = 0;
1109 1109
 			$this->multicurrency_tx = 1;
1110 1110
 		}
1111 1111
 
1112
-        // We set order into draft status
1113
-        $this->brouillon = 1;
1114
-
1115
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
1116
-        $sql.= "ref";
1117
-        $sql.= ", ref_supplier";
1118
-        $sql.= ", note_private";
1119
-        $sql.= ", note_public";
1120
-        $sql.= ", entity";
1121
-        $sql.= ", fk_soc";
1122
-        $sql.= ", fk_projet";
1123
-        $sql.= ", date_creation";
1112
+		// We set order into draft status
1113
+		$this->brouillon = 1;
1114
+
1115
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
1116
+		$sql.= "ref";
1117
+		$sql.= ", ref_supplier";
1118
+		$sql.= ", note_private";
1119
+		$sql.= ", note_public";
1120
+		$sql.= ", entity";
1121
+		$sql.= ", fk_soc";
1122
+		$sql.= ", fk_projet";
1123
+		$sql.= ", date_creation";
1124 1124
 		$sql.= ", date_livraison";
1125
-        $sql.= ", fk_user_author";
1126
-        $sql.= ", fk_statut";
1127
-        $sql.= ", source";
1128
-        $sql.= ", model_pdf";
1129
-        $sql.= ", fk_mode_reglement";
1125
+		$sql.= ", fk_user_author";
1126
+		$sql.= ", fk_statut";
1127
+		$sql.= ", source";
1128
+		$sql.= ", model_pdf";
1129
+		$sql.= ", fk_mode_reglement";
1130 1130
 		$sql.= ", fk_cond_reglement";
1131
-        $sql.= ", fk_account";
1131
+		$sql.= ", fk_account";
1132 1132
 		$sql.= ", fk_incoterms, location_incoterms";
1133
-        $sql.= ", fk_multicurrency";
1134
-        $sql.= ", multicurrency_code";
1135
-        $sql.= ", multicurrency_tx";
1136
-        $sql.= ") ";
1137
-        $sql.= " VALUES (";
1138
-        $sql.= "''";
1139
-        $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
1140
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
1141
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
1142
-        $sql.= ", ".$conf->entity;
1143
-        $sql.= ", ".$this->socid;
1144
-        $sql.= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
1145
-        $sql.= ", '".$this->db->idate($now)."'";
1133
+		$sql.= ", fk_multicurrency";
1134
+		$sql.= ", multicurrency_code";
1135
+		$sql.= ", multicurrency_tx";
1136
+		$sql.= ") ";
1137
+		$sql.= " VALUES (";
1138
+		$sql.= "''";
1139
+		$sql.= ", '".$this->db->escape($this->ref_supplier)."'";
1140
+		$sql.= ", '".$this->db->escape($this->note_private)."'";
1141
+		$sql.= ", '".$this->db->escape($this->note_public)."'";
1142
+		$sql.= ", ".$conf->entity;
1143
+		$sql.= ", ".$this->socid;
1144
+		$sql.= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
1145
+		$sql.= ", '".$this->db->idate($now)."'";
1146 1146
 		$sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
1147
-        $sql.= ", ".$user->id;
1148
-        $sql.= ", 0";
1149
-        $sql.= ", ".$this->db->escape($this->source);
1150
-        $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
1151
-        $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1152
-        $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1153
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
1154
-        $sql.= ", ".(int) $this->fk_incoterms;
1155
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
1147
+		$sql.= ", ".$user->id;
1148
+		$sql.= ", 0";
1149
+		$sql.= ", ".$this->db->escape($this->source);
1150
+		$sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
1151
+		$sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1152
+		$sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1153
+		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
1154
+		$sql.= ", ".(int) $this->fk_incoterms;
1155
+		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
1156 1156
 		$sql.= ", ".(int) $this->fk_multicurrency;
1157 1157
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
1158 1158
 		$sql.= ", ".(double) $this->multicurrency_tx;
1159
-        $sql.= ")";
1159
+		$sql.= ")";
1160 1160
 
1161
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
1162
-        if ($this->db->query($sql))
1163
-        {
1164
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
1161
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
1162
+		if ($this->db->query($sql))
1163
+		{
1164
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
1165 1165
 
1166 1166
 			if ($this->id) {
1167 1167
 				$num=count($this->lines);
1168 1168
 
1169
-	            // insert products details into database
1170
-	            for ($i=0;$i<$num;$i++)
1171
-	            {
1172
-	                $result = $this->addline(              // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1173
-	                    $this->lines[$i]->desc,
1174
-	                    $this->lines[$i]->subprice,
1175
-	                    $this->lines[$i]->qty,
1176
-	                    $this->lines[$i]->tva_tx,
1177
-	                    $this->lines[$i]->localtax1_tx,
1178
-	                    $this->lines[$i]->localtax2_tx,
1179
-	                    $this->lines[$i]->fk_product,
1180
-	                    0,
1181
-	                    $this->lines[$i]->ref_fourn,   // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1182
-	                    $this->lines[$i]->remise_percent,
1183
-	                    'HT',
1184
-	                    0,
1185
-	                    $this->lines[$i]->product_type,
1186
-	                    $this->lines[$i]->info_bits,
1187
-                        false,
1188
-	                    $this->lines[$i]->date_start,
1189
-                        $this->lines[$i]->date_end,
1190
-                        0,
1191
-                        $this->lines[$i]->fk_unit
1192
-	                );
1193
-	                if ($result < 0)
1194
-	                {
1195
-	                    dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);	// do not use dol_print_error here as it may be a functionnal error
1196
-	                    $this->db->rollback();
1197
-	                    return -1;
1198
-	                }
1199
-	            }
1200
-
1201
-	            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1202
-	            $sql.= " SET ref='(PROV".$this->id.")'";
1203
-	            $sql.= " WHERE rowid=".$this->id;
1204
-	            dol_syslog(get_class($this)."::create", LOG_DEBUG);
1205
-	            if ($this->db->query($sql))
1206
-	            {
1169
+				// insert products details into database
1170
+				for ($i=0;$i<$num;$i++)
1171
+				{
1172
+					$result = $this->addline(              // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1173
+						$this->lines[$i]->desc,
1174
+						$this->lines[$i]->subprice,
1175
+						$this->lines[$i]->qty,
1176
+						$this->lines[$i]->tva_tx,
1177
+						$this->lines[$i]->localtax1_tx,
1178
+						$this->lines[$i]->localtax2_tx,
1179
+						$this->lines[$i]->fk_product,
1180
+						0,
1181
+						$this->lines[$i]->ref_fourn,   // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1182
+						$this->lines[$i]->remise_percent,
1183
+						'HT',
1184
+						0,
1185
+						$this->lines[$i]->product_type,
1186
+						$this->lines[$i]->info_bits,
1187
+						false,
1188
+						$this->lines[$i]->date_start,
1189
+						$this->lines[$i]->date_end,
1190
+						0,
1191
+						$this->lines[$i]->fk_unit
1192
+					);
1193
+					if ($result < 0)
1194
+					{
1195
+						dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);	// do not use dol_print_error here as it may be a functionnal error
1196
+						$this->db->rollback();
1197
+						return -1;
1198
+					}
1199
+				}
1200
+
1201
+				$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1202
+				$sql.= " SET ref='(PROV".$this->id.")'";
1203
+				$sql.= " WHERE rowid=".$this->id;
1204
+				dol_syslog(get_class($this)."::create", LOG_DEBUG);
1205
+				if ($this->db->query($sql))
1206
+				{
1207 1207
 					// Add link with price request and supplier order
1208 1208
 					if ($this->id)
1209
-                    {
1210
-                        $this->ref="(PROV".$this->id.")";
1211
-
1212
-                        // Add object linked
1213
-                        if (is_array($this->linked_objects) && ! empty($this->linked_objects))
1214
-                        {
1215
-                        	foreach($this->linked_objects as $origin => $origin_id)
1216
-                        	{
1217
-                        		$ret = $this->add_object_linked($origin, $origin_id);
1218
-                        		if (! $ret)
1219
-                        		{
1220
-                        			dol_print_error($this->db);
1221
-                        			$error++;
1222
-                        		}
1223
-                        	}
1224
-                        }
1225
-                    }
1226
-
1227
-	                if (! $error)
1228
-                    {
1229
-                    	$result=$this->insertExtraFields();
1230
-	                    if ($result < 0) $error++;
1231
-                    }
1209
+					{
1210
+						$this->ref="(PROV".$this->id.")";
1211
+
1212
+						// Add object linked
1213
+						if (is_array($this->linked_objects) && ! empty($this->linked_objects))
1214
+						{
1215
+							foreach($this->linked_objects as $origin => $origin_id)
1216
+							{
1217
+								$ret = $this->add_object_linked($origin, $origin_id);
1218
+								if (! $ret)
1219
+								{
1220
+									dol_print_error($this->db);
1221
+									$error++;
1222
+								}
1223
+							}
1224
+						}
1225
+					}
1226
+
1227
+					if (! $error)
1228
+					{
1229
+						$result=$this->insertExtraFields();
1230
+						if ($result < 0) $error++;
1231
+					}
1232 1232
 
1233 1233
 					if (! $error && ! $notrigger)
1234
-	                {
1234
+					{
1235 1235
 						// Call trigger
1236 1236
 						$result=$this->call_trigger('ORDER_SUPPLIER_CREATE',$user);
1237 1237
 						if ($result < 0)
1238
-	                    {
1239
-	                        $this->db->rollback();
1240
-	                        return -1;
1241
-	                    }
1238
+						{
1239
+							$this->db->rollback();
1240
+							return -1;
1241
+						}
1242 1242
 						// End call triggers
1243
-	                }
1244
-
1245
-	                $this->db->commit();
1246
-	                return $this->id;
1247
-	            }
1248
-	            else
1249
-	            {
1250
-	                $this->error=$this->db->lasterror();
1251
-	                $this->db->rollback();
1252
-	                return -2;
1253
-	            }
1254
-            }
1255
-        }
1256
-        else
1257
-        {
1258
-            $this->error=$this->db->lasterror();
1259
-            $this->db->rollback();
1260
-            return -1;
1261
-        }
1262
-    }
1263
-
1264
-    /**
1265
-     *	Load an object from its id and create a new one in database
1266
-     *
1267
-     *	@return		int							New id of clone
1268
-     */
1269
-    public function createFromClone()
1270
-    {
1271
-        global $conf,$user,$langs,$hookmanager;
1272
-
1273
-        $error=0;
1243
+					}
1244
+
1245
+					$this->db->commit();
1246
+					return $this->id;
1247
+				}
1248
+				else
1249
+				{
1250
+					$this->error=$this->db->lasterror();
1251
+					$this->db->rollback();
1252
+					return -2;
1253
+				}
1254
+			}
1255
+		}
1256
+		else
1257
+		{
1258
+			$this->error=$this->db->lasterror();
1259
+			$this->db->rollback();
1260
+			return -1;
1261
+		}
1262
+	}
1263
+
1264
+	/**
1265
+	 *	Load an object from its id and create a new one in database
1266
+	 *
1267
+	 *	@return		int							New id of clone
1268
+	 */
1269
+	public function createFromClone()
1270
+	{
1271
+		global $conf,$user,$langs,$hookmanager;
1272
+
1273
+		$error=0;
1274 1274
 
1275 1275
 		$this->context['createfromclone'] = 'createfromclone';
1276 1276
 
@@ -1279,1431 +1279,1431 @@  discard block
 block discarded – undo
1279 1279
 		// Load source object
1280 1280
 		$objFrom = clone $this;
1281 1281
 
1282
-        $this->id=0;
1283
-        $this->statut=0;
1284
-
1285
-        // Clear fields
1286
-        $this->user_author_id     = $user->id;
1287
-        $this->user_valid         = '';
1288
-        $this->date_creation      = '';
1289
-        $this->date_validation    = '';
1290
-        $this->ref_supplier       = '';
1291
-        $this->user_approve_id    = '';
1292
-        $this->user_approve_id2   = '';
1293
-        $this->date_approve       = '';
1294
-        $this->date_approve2      = '';
1295
-
1296
-        // Create clone
1297
-        $result=$this->create($user);
1298
-        if ($result < 0) $error++;
1299
-
1300
-        if (! $error)
1301
-        {
1302
-            // Hook of thirdparty module
1303
-            if (is_object($hookmanager))
1304
-            {
1305
-                $parameters=array('objFrom'=>$objFrom);
1306
-                $action='';
1307
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1308
-                if ($reshook < 0) $error++;
1309
-            }
1282
+		$this->id=0;
1283
+		$this->statut=0;
1284
+
1285
+		// Clear fields
1286
+		$this->user_author_id     = $user->id;
1287
+		$this->user_valid         = '';
1288
+		$this->date_creation      = '';
1289
+		$this->date_validation    = '';
1290
+		$this->ref_supplier       = '';
1291
+		$this->user_approve_id    = '';
1292
+		$this->user_approve_id2   = '';
1293
+		$this->date_approve       = '';
1294
+		$this->date_approve2      = '';
1295
+
1296
+		// Create clone
1297
+		$result=$this->create($user);
1298
+		if ($result < 0) $error++;
1299
+
1300
+		if (! $error)
1301
+		{
1302
+			// Hook of thirdparty module
1303
+			if (is_object($hookmanager))
1304
+			{
1305
+				$parameters=array('objFrom'=>$objFrom);
1306
+				$action='';
1307
+				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1308
+				if ($reshook < 0) $error++;
1309
+			}
1310 1310
 
1311 1311
 			// Call trigger
1312 1312
 			$result=$this->call_trigger('ORDER_SUPPLIER_CLONE',$user);
1313 1313
 			if ($result < 0) $error++;
1314 1314
 			// End call triggers
1315
-        }
1315
+		}
1316 1316
 
1317 1317
 		unset($this->context['createfromclone']);
1318 1318
 
1319 1319
 		// End
1320
-        if (! $error)
1321
-        {
1322
-            $this->db->commit();
1323
-            return $this->id;
1324
-        }
1325
-        else
1326
-        {
1327
-            $this->db->rollback();
1328
-            return -1;
1329
-        }
1330
-    }
1331
-
1332
-    /**
1333
-     *	Add order line
1334
-     *
1335
-     *	@param      string	$desc            		Description
1336
-     *	@param      float	$pu_ht              	Unit price
1337
-     *	@param      float	$qty             		Quantity
1338
-     *	@param      float	$txtva           		Taux tva
1339
-     *	@param      float	$txlocaltax1        	Localtax1 tax
1340
-     *  @param      float	$txlocaltax2        	Localtax2 tax
1341
-     *	@param      int		$fk_product      		Id product
1342
-     *  @param      int		$fk_prod_fourn_price	Id supplier price
1343
-     *  @param      string	$fourn_ref				Supplier reference price
1344
-     *	@param      float	$remise_percent  		Remise
1345
-     *	@param      string	$price_base_type		HT or TTC
1346
-     *	@param		float	$pu_ttc					Unit price TTC
1347
-     *	@param		int		$type					Type of line (0=product, 1=service)
1348
-     *	@param		int		$info_bits				More information
1349
-     *  @param		bool	$notrigger				Disable triggers
1350
-     *  @param		int		$date_start				Date start of service
1351
-     *  @param		int		$date_end				Date end of service
1320
+		if (! $error)
1321
+		{
1322
+			$this->db->commit();
1323
+			return $this->id;
1324
+		}
1325
+		else
1326
+		{
1327
+			$this->db->rollback();
1328
+			return -1;
1329
+		}
1330
+	}
1331
+
1332
+	/**
1333
+	 *	Add order line
1334
+	 *
1335
+	 *	@param      string	$desc            		Description
1336
+	 *	@param      float	$pu_ht              	Unit price
1337
+	 *	@param      float	$qty             		Quantity
1338
+	 *	@param      float	$txtva           		Taux tva
1339
+	 *	@param      float	$txlocaltax1        	Localtax1 tax
1340
+	 *  @param      float	$txlocaltax2        	Localtax2 tax
1341
+	 *	@param      int		$fk_product      		Id product
1342
+	 *  @param      int		$fk_prod_fourn_price	Id supplier price
1343
+	 *  @param      string	$fourn_ref				Supplier reference price
1344
+	 *	@param      float	$remise_percent  		Remise
1345
+	 *	@param      string	$price_base_type		HT or TTC
1346
+	 *	@param		float	$pu_ttc					Unit price TTC
1347
+	 *	@param		int		$type					Type of line (0=product, 1=service)
1348
+	 *	@param		int		$info_bits				More information
1349
+	 *  @param		bool	$notrigger				Disable triggers
1350
+	 *  @param		int		$date_start				Date start of service
1351
+	 *  @param		int		$date_end				Date end of service
1352 1352
 	 *  @param		array	$array_options			extrafields array
1353
-     *  @param 		string	$fk_unit 				Code of the unit to use. Null to use the default one
1353
+	 *  @param 		string	$fk_unit 				Code of the unit to use. Null to use the default one
1354 1354
 	 *  @param 		string	$pu_ht_devise			Amount in currency
1355 1355
 	 *  @param		string	$origin					'order', ...
1356 1356
 	 *  @param		int		$origin_id				Id of origin object
1357
-     *	@return     int             				<=0 if KO, >0 if OK
1358
-     */
1357
+	 *	@return     int             				<=0 if KO, >0 if OK
1358
+	 */
1359 1359
 	public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $fourn_ref='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null, $array_options=0, $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0)
1360
-    {
1361
-        global $langs,$mysoc,$conf;
1360
+	{
1361
+		global $langs,$mysoc,$conf;
1362 1362
 
1363
-        $error = 0;
1363
+		$error = 0;
1364 1364
 
1365
-        dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $fourn_ref, $remise_percent, $price_base_type, $pu_ttc, $type, $fk_unit");
1366
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1365
+		dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $fourn_ref, $remise_percent, $price_base_type, $pu_ttc, $type, $fk_unit");
1366
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1367 1367
 
1368
-        // Clean parameters
1369
-        if (! $qty) $qty=1;
1370
-        if (! $info_bits) $info_bits=0;
1371
-        if (empty($txtva)) $txtva=0;
1372
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1373
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1368
+		// Clean parameters
1369
+		if (! $qty) $qty=1;
1370
+		if (! $info_bits) $info_bits=0;
1371
+		if (empty($txtva)) $txtva=0;
1372
+		if (empty($txlocaltax1)) $txlocaltax1=0;
1373
+		if (empty($txlocaltax2)) $txlocaltax2=0;
1374 1374
 		if (empty($remise_percent)) $remise_percent=0;
1375 1375
 
1376
-        $remise_percent=price2num($remise_percent);
1377
-        $qty=price2num($qty);
1378
-        $pu_ht=price2num($pu_ht);
1379
-        $pu_ttc=price2num($pu_ttc);
1380
-        $txtva = price2num($txtva);
1381
-        $txlocaltax1 = price2num($txlocaltax1);
1382
-        $txlocaltax2 = price2num($txlocaltax2);
1383
-        if ($price_base_type=='HT')
1384
-        {
1385
-            $pu=$pu_ht;
1386
-        }
1387
-        else
1388
-        {
1389
-            $pu=$pu_ttc;
1390
-        }
1391
-        $desc=trim($desc);
1392
-        $ref_supplier=''; // Ref of supplier price when we add line
1393
-
1394
-        // Check parameters
1395
-        if ($qty < 1 && ! $fk_product)
1396
-        {
1397
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Product"));
1398
-            return -1;
1399
-        }
1400
-        if ($type < 0) return -1;
1401
-
1402
-        if ($this->statut == 0)
1403
-        {
1404
-            $this->db->begin();
1405
-
1406
-            if ($fk_product > 0)
1407
-            {
1408
-                if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
1409
-                {
1410
-                    // Check quantity is enough
1411
-                    dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." fourn_ref=".$fourn_ref);
1412
-                    $prod = new Product($this->db, $fk_product);
1413
-                    if ($prod->fetch($fk_product) > 0)
1414
-                    {
1415
-                        $product_type = $prod->type;
1416
-                        $label = $prod->label;
1417
-
1418
-                        // We use 'none' instead of $fourn_ref, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
1419
-                        // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
1420
-                        $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc);   // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc
1421
-                        if ($result > 0)
1422
-                        {
1423
-                            $pu           = $prod->fourn_pu;       // Unit price supplier price set by get_buyprice
1424
-                            $ref_supplier = $prod->ref_supplier;   // Ref supplier price set by get_buyprice
1425
-			    // is remise percent not keyed but present for the product we add it
1426
-                            if ($remise_percent == 0 && $prod->remise_percent !=0)
1427
-                            	$remise_percent =$prod->remise_percent;
1428
-
1429
-
1430
-                        }
1431
-                        if ($result == 0)                   // If result == 0, we failed to found the supplier reference price
1432
-                        {
1433
-                            $langs->load("errors");
1434
-                            $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1435
-                            $this->db->rollback();
1436
-                            dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
1437
-                            //$pu    = $prod->fourn_pu;     // We do not overwrite unit price
1438
-                            //$ref   = $prod->ref_fourn;    // We do not overwrite ref supplier price
1439
-                            return -1;
1440
-                        }
1441
-                        if ($result == -1)
1442
-                        {
1443
-                            $langs->load("errors");
1444
-                            $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1445
-                            $this->db->rollback();
1446
-                            dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
1447
-                            return -1;
1448
-                        }
1449
-                        if ($result < -1)
1450
-                        {
1451
-                            $this->error=$prod->error;
1452
-                            $this->db->rollback();
1453
-                            dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1454
-                            return -1;
1455
-                        }
1456
-                    }
1457
-                    else
1458
-    				{
1459
-                        $this->error=$prod->error;
1460
-                        return -1;
1461
-                    }
1462
-                }
1463
-            }
1464
-            else
1465
-            {
1466
-                $product_type = $type;
1467
-            }
1468
-
1469
-            // Calcul du total TTC et de la TVA pour la ligne a partir de
1470
-            // qty, pu, remise_percent et txtva
1471
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1472
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1473
-
1474
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc,$this->thirdparty);
1475
-
1476
-            // Clean vat code
1477
-            $vat_src_code='';
1478
-            if (preg_match('/\((.*)\)/', $txtva, $reg))
1479
-            {
1480
-                $vat_src_code = $reg[1];
1481
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1482
-            }
1483
-
1484
-            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx,$pu_ht_devise);
1485
-            $total_ht  = $tabprice[0];
1486
-            $total_tva = $tabprice[1];
1487
-            $total_ttc = $tabprice[2];
1488
-            $total_localtax1 = $tabprice[9];
1489
-            $total_localtax2 = $tabprice[10];
1376
+		$remise_percent=price2num($remise_percent);
1377
+		$qty=price2num($qty);
1378
+		$pu_ht=price2num($pu_ht);
1379
+		$pu_ttc=price2num($pu_ttc);
1380
+		$txtva = price2num($txtva);
1381
+		$txlocaltax1 = price2num($txlocaltax1);
1382
+		$txlocaltax2 = price2num($txlocaltax2);
1383
+		if ($price_base_type=='HT')
1384
+		{
1385
+			$pu=$pu_ht;
1386
+		}
1387
+		else
1388
+		{
1389
+			$pu=$pu_ttc;
1390
+		}
1391
+		$desc=trim($desc);
1392
+		$ref_supplier=''; // Ref of supplier price when we add line
1393
+
1394
+		// Check parameters
1395
+		if ($qty < 1 && ! $fk_product)
1396
+		{
1397
+			$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Product"));
1398
+			return -1;
1399
+		}
1400
+		if ($type < 0) return -1;
1401
+
1402
+		if ($this->statut == 0)
1403
+		{
1404
+			$this->db->begin();
1405
+
1406
+			if ($fk_product > 0)
1407
+			{
1408
+				if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
1409
+				{
1410
+					// Check quantity is enough
1411
+					dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." fourn_ref=".$fourn_ref);
1412
+					$prod = new Product($this->db, $fk_product);
1413
+					if ($prod->fetch($fk_product) > 0)
1414
+					{
1415
+						$product_type = $prod->type;
1416
+						$label = $prod->label;
1417
+
1418
+						// We use 'none' instead of $fourn_ref, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
1419
+						// If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
1420
+						$result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc);   // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc
1421
+						if ($result > 0)
1422
+						{
1423
+							$pu           = $prod->fourn_pu;       // Unit price supplier price set by get_buyprice
1424
+							$ref_supplier = $prod->ref_supplier;   // Ref supplier price set by get_buyprice
1425
+				// is remise percent not keyed but present for the product we add it
1426
+							if ($remise_percent == 0 && $prod->remise_percent !=0)
1427
+								$remise_percent =$prod->remise_percent;
1428
+
1429
+
1430
+						}
1431
+						if ($result == 0)                   // If result == 0, we failed to found the supplier reference price
1432
+						{
1433
+							$langs->load("errors");
1434
+							$this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1435
+							$this->db->rollback();
1436
+							dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
1437
+							//$pu    = $prod->fourn_pu;     // We do not overwrite unit price
1438
+							//$ref   = $prod->ref_fourn;    // We do not overwrite ref supplier price
1439
+							return -1;
1440
+						}
1441
+						if ($result == -1)
1442
+						{
1443
+							$langs->load("errors");
1444
+							$this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1445
+							$this->db->rollback();
1446
+							dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
1447
+							return -1;
1448
+						}
1449
+						if ($result < -1)
1450
+						{
1451
+							$this->error=$prod->error;
1452
+							$this->db->rollback();
1453
+							dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1454
+							return -1;
1455
+						}
1456
+					}
1457
+					else
1458
+					{
1459
+						$this->error=$prod->error;
1460
+						return -1;
1461
+					}
1462
+				}
1463
+			}
1464
+			else
1465
+			{
1466
+				$product_type = $type;
1467
+			}
1468
+
1469
+			// Calcul du total TTC et de la TVA pour la ligne a partir de
1470
+			// qty, pu, remise_percent et txtva
1471
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1472
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1473
+
1474
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc,$this->thirdparty);
1475
+
1476
+			// Clean vat code
1477
+			$vat_src_code='';
1478
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
1479
+			{
1480
+				$vat_src_code = $reg[1];
1481
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1482
+			}
1483
+
1484
+			$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx,$pu_ht_devise);
1485
+			$total_ht  = $tabprice[0];
1486
+			$total_tva = $tabprice[1];
1487
+			$total_ttc = $tabprice[2];
1488
+			$total_localtax1 = $tabprice[9];
1489
+			$total_localtax2 = $tabprice[10];
1490 1490
 			$pu_ht = $tabprice[3];
1491 1491
 
1492 1492
 			// MultiCurrency
1493 1493
 			$multicurrency_total_ht  = $tabprice[16];
1494
-            $multicurrency_total_tva = $tabprice[17];
1495
-            $multicurrency_total_ttc = $tabprice[18];
1494
+			$multicurrency_total_tva = $tabprice[17];
1495
+			$multicurrency_total_ttc = $tabprice[18];
1496 1496
 			$pu_ht_devise = $tabprice[19];
1497 1497
 
1498
-            $localtax1_type=$localtaxes_type[0];
1498
+			$localtax1_type=$localtaxes_type[0];
1499 1499
 			$localtax2_type=$localtaxes_type[2];
1500 1500
 
1501
-            $subprice = price2num($pu,'MU');
1502
-
1503
-            $rangmax = $this->line_max();
1504
-            $rang = $rangmax + 1;
1505
-
1506
-            // Insert line
1507
-            $this->line=new CommandeFournisseurLigne($this->db);
1508
-
1509
-            $this->line->context = $this->context;
1510
-
1511
-            $this->line->fk_commande=$this->id;
1512
-            $this->line->label=$label;
1513
-            $this->line->ref_fourn = $ref_supplier;
1514
-            $this->line->ref_supplier = $ref_supplier;
1515
-            $this->line->desc=$desc;
1516
-            $this->line->qty=$qty;
1517
-            $this->line->tva_tx=$txtva;
1518
-            $this->line->localtax1_tx=$txlocaltax1;
1519
-            $this->line->localtax2_tx=$txlocaltax2;
1520
-            $this->line->localtax1_type = $localtaxes_type[0];
1521
-            $this->line->localtax2_type = $localtaxes_type[2];
1522
-            $this->line->fk_product=$fk_product;
1523
-            $this->line->product_type=$product_type;
1524
-            $this->line->remise_percent=$remise_percent;
1525
-            $this->line->subprice=$pu_ht;
1526
-            $this->line->rang=$this->rang;
1527
-            $this->line->info_bits=$info_bits;
1528
-
1529
-            $this->line->vat_src_code=$vat_src_code;
1530
-            $this->line->total_ht=$total_ht;
1531
-            $this->line->total_tva=$total_tva;
1532
-            $this->line->total_localtax1=$total_localtax1;
1533
-            $this->line->total_localtax2=$total_localtax2;
1534
-            $this->line->total_ttc=$total_ttc;
1535
-            $this->line->product_type=$type;
1536
-            $this->line->special_code=$this->special_code;
1537
-            $this->line->origin=$origin;
1538
-            $this->line->origin_id=$origin_id;
1539
-            $this->line->fk_unit=$fk_unit;
1540
-
1541
-            $this->line->date_start=$date_start;
1542
-            $this->line->date_end=$date_end;
1543
-
1544
-            // Multicurrency
1545
-            $this->line->fk_multicurrency			= $this->fk_multicurrency;
1546
-            $this->line->multicurrency_code			= $this->multicurrency_code;
1547
-            $this->line->multicurrency_subprice		= $pu_ht_devise;
1548
-            $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1549
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1550
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1551
-
1552
-            $this->line->subprice=$pu_ht;
1553
-            $this->line->price=$this->line->subprice;
1554
-
1555
-            $this->line->remise_percent=$remise_percent;
1556
-
1557
-            if (is_array($array_options) && count($array_options)>0) {
1558
-                $this->line->array_options=$array_options;
1559
-            }
1560
-
1561
-            $result=$this->line->insert($notrigger);
1562
-            if ($result > 0)
1563
-            {
1564
-                // Reorder if child line
1565
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1566
-
1567
-                // Mise a jour informations denormalisees au niveau de la commande meme
1568
-                $result=$this->update_price(1,'auto',0,$this->thirdparty);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1569
-                if ($result > 0)
1570
-                {
1571
-                    $this->db->commit();
1572
-                    return $this->line->id;
1573
-                }
1574
-                else
1575
-                {
1576
-                    $this->db->rollback();
1577
-                    return -1;
1578
-                }
1579
-            }
1580
-            else
1581
-            {
1582
-                $this->error=$this->line->error;
1583
-                $this->errors=$this->line->errors;
1584
-                dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1585
-                $this->db->rollback();
1586
-                return -1;
1587
-            }
1588
-        }
1589
-    }
1590
-
1591
-
1592
-    /**
1593
-     * Save a receiving into the tracking table of receiving (commande_fournisseur_dispatch) and add product into stock warehouse.
1594
-     *
1595
-     * @param 	User		$user					User object making change
1596
-     * @param 	int			$product				Id of product to dispatch
1597
-     * @param 	double		$qty					Qty to dispatch
1598
-     * @param 	int			$entrepot				Id of warehouse to add product
1599
-     * @param 	double		$price					Unit Price for PMP value calculation (Unit price without Tax and taking into account discount)
1600
-     * @param	string		$comment				Comment for stock movement
1501
+			$subprice = price2num($pu,'MU');
1502
+
1503
+			$rangmax = $this->line_max();
1504
+			$rang = $rangmax + 1;
1505
+
1506
+			// Insert line
1507
+			$this->line=new CommandeFournisseurLigne($this->db);
1508
+
1509
+			$this->line->context = $this->context;
1510
+
1511
+			$this->line->fk_commande=$this->id;
1512
+			$this->line->label=$label;
1513
+			$this->line->ref_fourn = $ref_supplier;
1514
+			$this->line->ref_supplier = $ref_supplier;
1515
+			$this->line->desc=$desc;
1516
+			$this->line->qty=$qty;
1517
+			$this->line->tva_tx=$txtva;
1518
+			$this->line->localtax1_tx=$txlocaltax1;
1519
+			$this->line->localtax2_tx=$txlocaltax2;
1520
+			$this->line->localtax1_type = $localtaxes_type[0];
1521
+			$this->line->localtax2_type = $localtaxes_type[2];
1522
+			$this->line->fk_product=$fk_product;
1523
+			$this->line->product_type=$product_type;
1524
+			$this->line->remise_percent=$remise_percent;
1525
+			$this->line->subprice=$pu_ht;
1526
+			$this->line->rang=$this->rang;
1527
+			$this->line->info_bits=$info_bits;
1528
+
1529
+			$this->line->vat_src_code=$vat_src_code;
1530
+			$this->line->total_ht=$total_ht;
1531
+			$this->line->total_tva=$total_tva;
1532
+			$this->line->total_localtax1=$total_localtax1;
1533
+			$this->line->total_localtax2=$total_localtax2;
1534
+			$this->line->total_ttc=$total_ttc;
1535
+			$this->line->product_type=$type;
1536
+			$this->line->special_code=$this->special_code;
1537
+			$this->line->origin=$origin;
1538
+			$this->line->origin_id=$origin_id;
1539
+			$this->line->fk_unit=$fk_unit;
1540
+
1541
+			$this->line->date_start=$date_start;
1542
+			$this->line->date_end=$date_end;
1543
+
1544
+			// Multicurrency
1545
+			$this->line->fk_multicurrency			= $this->fk_multicurrency;
1546
+			$this->line->multicurrency_code			= $this->multicurrency_code;
1547
+			$this->line->multicurrency_subprice		= $pu_ht_devise;
1548
+			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1549
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1550
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1551
+
1552
+			$this->line->subprice=$pu_ht;
1553
+			$this->line->price=$this->line->subprice;
1554
+
1555
+			$this->line->remise_percent=$remise_percent;
1556
+
1557
+			if (is_array($array_options) && count($array_options)>0) {
1558
+				$this->line->array_options=$array_options;
1559
+			}
1560
+
1561
+			$result=$this->line->insert($notrigger);
1562
+			if ($result > 0)
1563
+			{
1564
+				// Reorder if child line
1565
+				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1566
+
1567
+				// Mise a jour informations denormalisees au niveau de la commande meme
1568
+				$result=$this->update_price(1,'auto',0,$this->thirdparty);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1569
+				if ($result > 0)
1570
+				{
1571
+					$this->db->commit();
1572
+					return $this->line->id;
1573
+				}
1574
+				else
1575
+				{
1576
+					$this->db->rollback();
1577
+					return -1;
1578
+				}
1579
+			}
1580
+			else
1581
+			{
1582
+				$this->error=$this->line->error;
1583
+				$this->errors=$this->line->errors;
1584
+				dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1585
+				$this->db->rollback();
1586
+				return -1;
1587
+			}
1588
+		}
1589
+	}
1590
+
1591
+
1592
+	/**
1593
+	 * Save a receiving into the tracking table of receiving (commande_fournisseur_dispatch) and add product into stock warehouse.
1594
+	 *
1595
+	 * @param 	User		$user					User object making change
1596
+	 * @param 	int			$product				Id of product to dispatch
1597
+	 * @param 	double		$qty					Qty to dispatch
1598
+	 * @param 	int			$entrepot				Id of warehouse to add product
1599
+	 * @param 	double		$price					Unit Price for PMP value calculation (Unit price without Tax and taking into account discount)
1600
+	 * @param	string		$comment				Comment for stock movement
1601 1601
 	 * @param	date		$eatby					eat-by date
1602 1602
 	 * @param	date		$sellby					sell-by date
1603 1603
 	 * @param	string		$batch					Lot number
1604 1604
 	 * @param	int			$fk_commandefourndet	Id of supplier order line
1605
-     * @param	int			$notrigger          	1 = notrigger
1606
-     * @return 	int						<0 if KO, >0 if OK
1607
-     */
1608
-    public function dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0)
1609
-    {
1610
-        global $conf, $langs;
1611
-
1612
-        $error = 0;
1613
-        require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
1614
-
1615
-        // Check parameters (if test are wrong here, there is bug into caller)
1616
-        if ($entrepot <= 0)
1617
-        {
1618
-            $this->error='ErrorBadValueForParameterWarehouse';
1619
-            return -1;
1620
-        }
1621
-        if ($qty <= 0)
1622
-        {
1623
-            $this->error='ErrorBadValueForParameterQty';
1624
-            return -1;
1625
-        }
1626
-
1627
-        $dispatchstatus = 1;
1628
-        if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0;	// Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1629
-
1630
-        $now=dol_now();
1631
-
1632
-        if (($this->statut == 3 || $this->statut == 4 || $this->statut == 5))
1633
-        {
1634
-            $this->db->begin();
1635
-
1636
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
1637
-            $sql.= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
1638
-            $sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
1639
-            $sql.= ($eatby?"'".$this->db->idate($eatby)."'":"null").", ".($sellby?"'".$this->db->idate($sellby)."'":"null").", ".($batch?"'".$batch."'":"null");
1640
-            $sql.= ")";
1641
-
1642
-            dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
1643
-            $resql = $this->db->query($sql);
1644
-            if ($resql)
1645
-            {
1646
-                if (! $notrigger)
1647
-                {
1648
-                    global $conf, $langs, $user;
1605
+	 * @param	int			$notrigger          	1 = notrigger
1606
+	 * @return 	int						<0 if KO, >0 if OK
1607
+	 */
1608
+	public function dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0)
1609
+	{
1610
+		global $conf, $langs;
1611
+
1612
+		$error = 0;
1613
+		require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
1614
+
1615
+		// Check parameters (if test are wrong here, there is bug into caller)
1616
+		if ($entrepot <= 0)
1617
+		{
1618
+			$this->error='ErrorBadValueForParameterWarehouse';
1619
+			return -1;
1620
+		}
1621
+		if ($qty <= 0)
1622
+		{
1623
+			$this->error='ErrorBadValueForParameterQty';
1624
+			return -1;
1625
+		}
1626
+
1627
+		$dispatchstatus = 1;
1628
+		if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0;	// Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1629
+
1630
+		$now=dol_now();
1631
+
1632
+		if (($this->statut == 3 || $this->statut == 4 || $this->statut == 5))
1633
+		{
1634
+			$this->db->begin();
1635
+
1636
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
1637
+			$sql.= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
1638
+			$sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
1639
+			$sql.= ($eatby?"'".$this->db->idate($eatby)."'":"null").", ".($sellby?"'".$this->db->idate($sellby)."'":"null").", ".($batch?"'".$batch."'":"null");
1640
+			$sql.= ")";
1641
+
1642
+			dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
1643
+			$resql = $this->db->query($sql);
1644
+			if ($resql)
1645
+			{
1646
+				if (! $notrigger)
1647
+				{
1648
+					global $conf, $langs, $user;
1649 1649
 					// Call trigger
1650 1650
 					$result=$this->call_trigger('LINEORDER_SUPPLIER_DISPATCH',$user);
1651 1651
 					if ($result < 0)
1652
-                    {
1653
-                        $error++;
1654
-                        return -1;
1655
-                    }
1652
+					{
1653
+						$error++;
1654
+						return -1;
1655
+					}
1656 1656
 					// End call triggers
1657
-                }
1658
-            }
1659
-            else
1660
-			{
1661
-                $this->error=$this->db->lasterror();
1662
-                $error++;
1663
-            }
1664
-
1665
-            // Si module stock gere et que incrementation faite depuis un dispatching en stock
1666
-            if (! $error && $entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
1667
-            {
1668
-
1669
-                $mouv = new MouvementStock($this->db);
1670
-                if ($product > 0)
1671
-                {
1672
-                	// $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
1673
-                	$mouv->origin = &$this;
1657
+				}
1658
+			}
1659
+			else
1660
+			{
1661
+				$this->error=$this->db->lasterror();
1662
+				$error++;
1663
+			}
1664
+
1665
+			// Si module stock gere et que incrementation faite depuis un dispatching en stock
1666
+			if (! $error && $entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
1667
+			{
1668
+
1669
+				$mouv = new MouvementStock($this->db);
1670
+				if ($product > 0)
1671
+				{
1672
+					// $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
1673
+					$mouv->origin = &$this;
1674 1674
 					$result=$mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch);
1675
-                    if ($result < 0)
1676
-                    {
1677
-                        $this->error=$mouv->error;
1678
-                        $this->errors=$mouv->errors;
1679
-                        dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',',$this->errors), LOG_ERR);
1680
-                        $error++;
1681
-                    }
1682
-                }
1683
-            }
1684
-
1685
-            if ($error == 0)
1686
-            {
1687
-                $this->db->commit();
1688
-                return 1;
1689
-            }
1690
-            else
1691
-            {
1692
-                $this->db->rollback();
1693
-                return -1;
1694
-            }
1695
-        }
1696
-        else
1697
-		{
1698
-            $this->error='BadStatusForObject';
1699
-            return -2;
1700
-        }
1701
-    }
1702
-
1703
-    /**
1704
-     * 	Delete line
1705
-     *
1706
-     *	@param	int		$idline		Id of line to delete
1707
-     *	@param	int		$notrigger	1=Disable call to triggers
1708
-     *	@return	int					<0 if KO, >0 if OK
1709
-     */
1710
-    public function deleteline($idline, $notrigger=0)
1711
-    {
1712
-        if ($this->statut == 0)
1713
-        {
1714
-            $line = new CommandeFournisseurLigne($this->db);
1715
-
1716
-            if ($line->fetch($idline) <= 0)
1717
-            {
1718
-                return 0;
1719
-            }
1720
-
1721
-            if ($line->delete($notrigger) > 0)
1722
-            {
1723
-                $this->update_price();
1724
-                return 1;
1725
-            }
1726
-            else
1727
-            {
1728
-                $this->error = $line->error;
1729
-                $this->errors = $line->errors;
1730
-                return -1;
1731
-            }
1732
-        }
1733
-        else
1734
-        {
1735
-            return -2;
1736
-        }
1737
-    }
1738
-
1739
-    /**
1740
-     *  Delete an order
1741
-     *
1742
-     *	@param	User	$user		Object user
1743
-     *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1744
-     *	@return	int					<0 if KO, >0 if OK
1745
-     */
1746
-    public function delete(User $user, $notrigger=0)
1747
-    {
1748
-        global $langs,$conf;
1749
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1750
-
1751
-        $error = 0;
1752
-
1753
-        $this->db->begin();
1754
-
1755
-        if (empty($notrigger))
1756
-        {
1757
-            // Call trigger
1758
-            $result=$this->call_trigger('ORDER_SUPPLIER_DELETE',$user);
1759
-            if ($result < 0)
1760
-            {
1761
-            	$this->errors[]='ErrorWhenRunningTrigger';
1762
-            	dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1763
-            	return -1;
1764
-            }
1765
-            // End call triggers
1766
-        }
1767
-
1768
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ;
1769
-        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1770
-        if (! $this->db->query($sql) )
1771
-        {
1772
-            $this->error=$this->db->lasterror();
1773
-            $this->errors[]=$this->db->lasterror();
1774
-            $error++;
1775
-        }
1776
-
1777
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id;
1778
-        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1779
-        if ($resql = $this->db->query($sql) )
1780
-        {
1781
-            if ($this->db->affected_rows($resql) < 1)
1782
-            {
1783
-                $this->error=$this->db->lasterror();
1784
-                $this->errors[]=$this->db->lasterror();
1785
-                $error++;
1786
-            }
1787
-        }
1788
-        else
1789
-        {
1790
-            $this->error=$this->db->lasterror();
1791
-            $this->errors[]=$this->db->lasterror();
1792
-            $error++;
1793
-        }
1794
-
1795
-        // Remove extrafields
1796
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1797
-        {
1798
-        	$result=$this->deleteExtraFields();
1799
-        	if ($result < 0)
1800
-        	{
1801
-        		$this->error='FailToDeleteExtraFields';
1802
-        		$this->errors[]='FailToDeleteExtraFields';
1803
-        		$error++;
1804
-        		dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1805
-        	}
1806
-        }
1675
+					if ($result < 0)
1676
+					{
1677
+						$this->error=$mouv->error;
1678
+						$this->errors=$mouv->errors;
1679
+						dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',',$this->errors), LOG_ERR);
1680
+						$error++;
1681
+					}
1682
+				}
1683
+			}
1807 1684
 
1808
-		// Delete linked object
1809
-    	$res = $this->deleteObjectLinked();
1810
-    	if ($res < 0) {
1811
-    		$this->error='FailToDeleteObjectLinked';
1812
-    		$this->errors[]='FailToDeleteObjectLinked';
1813
-    		$error++;
1814
-    	}
1815
-
1816
-        if (! $error)
1817
-        {
1818
-        	// We remove directory
1819
-        	$ref = dol_sanitizeFileName($this->ref);
1820
-        	if ($conf->fournisseur->commande->dir_output)
1821
-        	{
1822
-        		$dir = $conf->fournisseur->commande->dir_output . "/" . $ref ;
1823
-        		$file = $dir . "/" . $ref . ".pdf";
1824
-        		if (file_exists($file))
1825
-        		{
1826
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1827
-        			{
1828
-        				$this->error='ErrorFailToDeleteFile';
1829
-        				$this->errors[]='ErrorFailToDeleteFile';
1830
-        				$error++;
1831
-        			}
1832
-        		}
1833
-        		if (file_exists($dir))
1834
-        		{
1835
-        			$res=@dol_delete_dir_recursive($dir);
1836
-        			if (! $res)
1837
-        			{
1838
-        				$this->error='ErrorFailToDeleteDir';
1839
-        				$this->errors[]='ErrorFailToDeleteDir';
1840
-        				$error++;
1841
-        			}
1842
-        		}
1843
-        	}
1844
-        }
1685
+			if ($error == 0)
1686
+			{
1687
+				$this->db->commit();
1688
+				return 1;
1689
+			}
1690
+			else
1691
+			{
1692
+				$this->db->rollback();
1693
+				return -1;
1694
+			}
1695
+		}
1696
+		else
1697
+		{
1698
+			$this->error='BadStatusForObject';
1699
+			return -2;
1700
+		}
1701
+	}
1845 1702
 
1846
-		if (! $error)
1703
+	/**
1704
+	 * 	Delete line
1705
+	 *
1706
+	 *	@param	int		$idline		Id of line to delete
1707
+	 *	@param	int		$notrigger	1=Disable call to triggers
1708
+	 *	@return	int					<0 if KO, >0 if OK
1709
+	 */
1710
+	public function deleteline($idline, $notrigger=0)
1711
+	{
1712
+		if ($this->statut == 0)
1847 1713
 		{
1848
-			dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1849
-			$this->db->commit();
1850
-			return 1;
1714
+			$line = new CommandeFournisseurLigne($this->db);
1715
+
1716
+			if ($line->fetch($idline) <= 0)
1717
+			{
1718
+				return 0;
1719
+			}
1720
+
1721
+			if ($line->delete($notrigger) > 0)
1722
+			{
1723
+				$this->update_price();
1724
+				return 1;
1725
+			}
1726
+			else
1727
+			{
1728
+				$this->error = $line->error;
1729
+				$this->errors = $line->errors;
1730
+				return -1;
1731
+			}
1851 1732
 		}
1852 1733
 		else
1853 1734
 		{
1854
-			dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1855
-			$this->db->rollback();
1856
-			return -$error;
1735
+			return -2;
1857 1736
 		}
1858
-    }
1859
-
1860
-    /**
1861
-     *	Get list of order methods
1862
-     *
1863
-     *	@return 0 if Ok, <0 if Ko
1864
-     */
1865
-    function get_methodes_commande()
1866
-    {
1867
-        $sql = "SELECT rowid, libelle";
1868
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
1869
-        $sql.= " WHERE active = 1";
1870
-
1871
-        $resql=$this->db->query($sql);
1872
-        if ($resql)
1873
-        {
1874
-            $i = 0;
1875
-            $num = $this->db->num_rows($resql);
1876
-            $this->methodes_commande = array();
1877
-            while ($i < $num)
1878
-            {
1879
-                $row = $this->db->fetch_row($resql);
1880
-
1881
-                $this->methodes_commande[$row[0]] = $row[1];
1882
-
1883
-                $i++;
1884
-            }
1885
-            return 0;
1886
-        }
1887
-        else
1888
-        {
1889
-            return -1;
1890
-        }
1891
-    }
1892
-
1893
-    /**
1894
-	 * Return array of dispathed lines waiting to be approved for this order
1737
+	}
1738
+
1739
+	/**
1740
+	 *  Delete an order
1895 1741
 	 *
1896
-	 * @param	int		$status		Filter on stats (-1 = no filter, 0 = lines draft to be approved, 1 = approved lines)
1897
-	 * @return	array				Array of lines
1898
-     */
1899
-    public function getDispachedLines($status=-1)
1900
-    {
1901
-    	$ret = array();
1742
+	 *	@param	User	$user		Object user
1743
+	 *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1744
+	 *	@return	int					<0 if KO, >0 if OK
1745
+	 */
1746
+	public function delete(User $user, $notrigger=0)
1747
+	{
1748
+		global $langs,$conf;
1749
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1902 1750
 
1903
-    	// List of already dispatched lines
1904
-		$sql = "SELECT p.ref, p.label,";
1905
-		$sql.= " e.rowid as warehouse_id, e.label as entrepot,";
1906
-		$sql.= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
1907
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p,";
1908
-		$sql.= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
1909
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
1910
-		$sql.= " WHERE cfd.fk_commande = ".$this->id;
1911
-		$sql.= " AND cfd.fk_product = p.rowid";
1912
-		if ($status >= 0) $sql.=" AND cfd.status = ".$status;
1913
-		$sql.= " ORDER BY cfd.rowid ASC";
1751
+		$error = 0;
1914 1752
 
1915
-		$resql = $this->db->query($sql);
1916
-		if ($resql)
1753
+		$this->db->begin();
1754
+
1755
+		if (empty($notrigger))
1756
+		{
1757
+			// Call trigger
1758
+			$result=$this->call_trigger('ORDER_SUPPLIER_DELETE',$user);
1759
+			if ($result < 0)
1760
+			{
1761
+				$this->errors[]='ErrorWhenRunningTrigger';
1762
+				dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1763
+				return -1;
1764
+			}
1765
+			// End call triggers
1766
+		}
1767
+
1768
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ;
1769
+		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1770
+		if (! $this->db->query($sql) )
1771
+		{
1772
+			$this->error=$this->db->lasterror();
1773
+			$this->errors[]=$this->db->lasterror();
1774
+			$error++;
1775
+		}
1776
+
1777
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id;
1778
+		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1779
+		if ($resql = $this->db->query($sql) )
1780
+		{
1781
+			if ($this->db->affected_rows($resql) < 1)
1782
+			{
1783
+				$this->error=$this->db->lasterror();
1784
+				$this->errors[]=$this->db->lasterror();
1785
+				$error++;
1786
+			}
1787
+		}
1788
+		else
1789
+		{
1790
+			$this->error=$this->db->lasterror();
1791
+			$this->errors[]=$this->db->lasterror();
1792
+			$error++;
1793
+		}
1794
+
1795
+		// Remove extrafields
1796
+		if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1797
+		{
1798
+			$result=$this->deleteExtraFields();
1799
+			if ($result < 0)
1800
+			{
1801
+				$this->error='FailToDeleteExtraFields';
1802
+				$this->errors[]='FailToDeleteExtraFields';
1803
+				$error++;
1804
+				dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1805
+			}
1806
+		}
1807
+
1808
+		// Delete linked object
1809
+		$res = $this->deleteObjectLinked();
1810
+		if ($res < 0) {
1811
+			$this->error='FailToDeleteObjectLinked';
1812
+			$this->errors[]='FailToDeleteObjectLinked';
1813
+			$error++;
1814
+		}
1815
+
1816
+		if (! $error)
1817
+		{
1818
+			// We remove directory
1819
+			$ref = dol_sanitizeFileName($this->ref);
1820
+			if ($conf->fournisseur->commande->dir_output)
1821
+			{
1822
+				$dir = $conf->fournisseur->commande->dir_output . "/" . $ref ;
1823
+				$file = $dir . "/" . $ref . ".pdf";
1824
+				if (file_exists($file))
1825
+				{
1826
+					if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1827
+					{
1828
+						$this->error='ErrorFailToDeleteFile';
1829
+						$this->errors[]='ErrorFailToDeleteFile';
1830
+						$error++;
1831
+					}
1832
+				}
1833
+				if (file_exists($dir))
1834
+				{
1835
+					$res=@dol_delete_dir_recursive($dir);
1836
+					if (! $res)
1837
+					{
1838
+						$this->error='ErrorFailToDeleteDir';
1839
+						$this->errors[]='ErrorFailToDeleteDir';
1840
+						$error++;
1841
+					}
1842
+				}
1843
+			}
1844
+		}
1845
+
1846
+		if (! $error)
1847
+		{
1848
+			dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1849
+			$this->db->commit();
1850
+			return 1;
1851
+		}
1852
+		else
1853
+		{
1854
+			dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1855
+			$this->db->rollback();
1856
+			return -$error;
1857
+		}
1858
+	}
1859
+
1860
+	/**
1861
+	 *	Get list of order methods
1862
+	 *
1863
+	 *	@return 0 if Ok, <0 if Ko
1864
+	 */
1865
+	function get_methodes_commande()
1866
+	{
1867
+		$sql = "SELECT rowid, libelle";
1868
+		$sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
1869
+		$sql.= " WHERE active = 1";
1870
+
1871
+		$resql=$this->db->query($sql);
1872
+		if ($resql)
1873
+		{
1874
+			$i = 0;
1875
+			$num = $this->db->num_rows($resql);
1876
+			$this->methodes_commande = array();
1877
+			while ($i < $num)
1878
+			{
1879
+				$row = $this->db->fetch_row($resql);
1880
+
1881
+				$this->methodes_commande[$row[0]] = $row[1];
1882
+
1883
+				$i++;
1884
+			}
1885
+			return 0;
1886
+		}
1887
+		else
1888
+		{
1889
+			return -1;
1890
+		}
1891
+	}
1892
+
1893
+	/**
1894
+	 * Return array of dispathed lines waiting to be approved for this order
1895
+	 *
1896
+	 * @param	int		$status		Filter on stats (-1 = no filter, 0 = lines draft to be approved, 1 = approved lines)
1897
+	 * @return	array				Array of lines
1898
+	 */
1899
+	public function getDispachedLines($status=-1)
1900
+	{
1901
+		$ret = array();
1902
+
1903
+		// List of already dispatched lines
1904
+		$sql = "SELECT p.ref, p.label,";
1905
+		$sql.= " e.rowid as warehouse_id, e.label as entrepot,";
1906
+		$sql.= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
1907
+		$sql.= " FROM ".MAIN_DB_PREFIX."product as p,";
1908
+		$sql.= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
1909
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
1910
+		$sql.= " WHERE cfd.fk_commande = ".$this->id;
1911
+		$sql.= " AND cfd.fk_product = p.rowid";
1912
+		if ($status >= 0) $sql.=" AND cfd.status = ".$status;
1913
+		$sql.= " ORDER BY cfd.rowid ASC";
1914
+
1915
+		$resql = $this->db->query($sql);
1916
+		if ($resql)
1917 1917
 		{
1918 1918
 			$num = $this->db->num_rows($resql);
1919 1919
 			$i = 0;
1920 1920
 
1921
-			while ($i < $num)
1922
-			{
1923
-				$objp = $this->db->fetch_object($resql);
1924
-				if ($objp) $ret[]=array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
1921
+			while ($i < $num)
1922
+			{
1923
+				$objp = $this->db->fetch_object($resql);
1924
+				if ($objp) $ret[]=array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
1925
+
1926
+				$i++;
1927
+			}
1928
+		}
1929
+		else dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
1930
+
1931
+		return $ret;
1932
+	}
1933
+
1934
+
1935
+	/**
1936
+	 * 	Set a delivery in database for this supplier order
1937
+	 *
1938
+	 *	@param	User	$user		User that input data
1939
+	 *	@param	date	$date		Date of reception
1940
+	 *	@param	string	$type		Type of receipt ('tot' = total/done, 'par' = partial, 'nev' = never, 'can' = cancel)
1941
+	 *	@param	string	$comment	Comment
1942
+	 *	@return	int					<0 if KO, >0 if OK
1943
+	 */
1944
+	function Livraison($user, $date, $type, $comment)
1945
+	{
1946
+		global $conf, $langs;
1947
+
1948
+		$result = 0;
1949
+		$error = 0;
1950
+
1951
+		dol_syslog(get_class($this)."::Livraison");
1952
+
1953
+		if ($user->rights->fournisseur->commande->receptionner)
1954
+		{
1955
+			if ($type == 'par') $statut = 4;
1956
+			if ($type == 'tot')	$statut = 5;
1957
+			if ($type == 'nev') $statut = 7;
1958
+			if ($type == 'can') $statut = 7;
1959
+
1960
+			// Some checks to accept the record
1961
+			if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
1962
+			{
1963
+				// If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
1964
+				if (! $error && ($type == 'tot'))
1965
+				{
1966
+					$dispatchedlinearray=$this->getDispachedLines(0);
1967
+					if (count($dispatchedlinearray) > 0)
1968
+					{
1969
+						$result=-1;
1970
+						$error++;
1971
+						$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
1972
+						dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
1973
+					}
1974
+
1975
+				}
1976
+				if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot'))	// Accept to move to reception done, only if status of all line are ok (refuse denied)
1977
+				{
1978
+					$dispatcheddenied=$this->getDispachedLines(2);
1979
+					if (count($dispatchedlinearray) > 0)
1980
+					{
1981
+						$result=-1;
1982
+						$error++;
1983
+						$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
1984
+						dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
1985
+					}
1986
+				}
1987
+			}
1988
+
1989
+			// TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
1990
+
1991
+
1992
+			if (! $error && ! ($statut == 4 or $statut == 5 or $statut == 7))
1993
+			{
1994
+				$error++;
1995
+				dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
1996
+				$result = -2;
1997
+			}
1998
+
1999
+			if (! $error)
2000
+			{
2001
+				$this->db->begin();
2002
+
2003
+				$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2004
+				$sql.= " SET fk_statut = ".$statut;
2005
+				$sql.= " WHERE rowid = ".$this->id;
2006
+				$sql.= " AND fk_statut IN (3,4)";	// Process running or Partially received
2007
+
2008
+				dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2009
+				$resql=$this->db->query($sql);
2010
+				if ($resql)
2011
+				{
2012
+					$result = 0;
2013
+					$old_statut = $this->statut;
2014
+					$this->statut = $statut;
2015
+					$this->actionmsg2 = $comment;
2016
+
2017
+					// Call trigger
2018
+					$result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE',$user);
2019
+					if ($result < 0) $error++;
2020
+					// End call triggers
2021
+
2022
+					if (! $error)
2023
+					{
2024
+						$this->db->commit();
2025
+					}
2026
+					else
2027
+					{
2028
+						$this->statut = $old_statut;
2029
+						$this->db->rollback();
2030
+						$this->error=$this->db->lasterror();
2031
+						$result = -1;
2032
+					}
2033
+				}
2034
+				else
2035
+				{
2036
+					$this->db->rollback();
2037
+					$this->error=$this->db->lasterror();
2038
+					$result = -1;
2039
+				}
2040
+			}
2041
+		}
2042
+		else
2043
+		{
2044
+			$this->error = $langs->trans('NotAuthorized');
2045
+			$this->errors[] = $langs->trans('NotAuthorized');
2046
+			dol_syslog(get_class($this)."::Livraison Not Authorized");
2047
+			$result = -3;
2048
+		}
2049
+		return $result ;
2050
+	}
2051
+
2052
+	/**
2053
+	 *	Set the planned delivery date
2054
+	 *
2055
+	 *	@param      User			$user        		Objet user making change
2056
+	 *	@param      timestamp		$date_livraison     Planned delivery date
2057
+	 *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2058
+	 *	@return     int         						<0 if KO, >0 if OK
2059
+	 */
2060
+	function set_date_livraison($user, $date_livraison, $notrigger=0)
2061
+	{
2062
+		if ($user->rights->fournisseur->commande->creer)
2063
+		{
2064
+			$error=0;
2065
+
2066
+			$this->db->begin();
2067
+
2068
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2069
+			$sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2070
+			$sql.= " WHERE rowid = ".$this->id;
2071
+
2072
+			dol_syslog(__METHOD__, LOG_DEBUG);
2073
+			$resql=$this->db->query($sql);
2074
+			if (!$resql)
2075
+			{
2076
+				$this->errors[]=$this->db->error();
2077
+				$error++;
2078
+			}
2079
+
2080
+			if (! $error)
2081
+			{
2082
+				$this->oldcopy= clone $this;
2083
+				$this->date_livraison = $date_livraison;
2084
+			}
2085
+
2086
+			if (! $notrigger && empty($error))
2087
+			{
2088
+				// Call trigger
2089
+				$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2090
+				if ($result < 0) $error++;
2091
+				// End call triggers
2092
+			}
2093
+
2094
+			if (! $error)
2095
+			{
2096
+				$this->db->commit();
2097
+				return 1;
2098
+			}
2099
+			else
2100
+			{
2101
+				foreach($this->errors as $errmsg)
2102
+				{
2103
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2104
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2105
+				}
2106
+				$this->db->rollback();
2107
+				return -1*$error;
2108
+			}
2109
+		}
2110
+		else
2111
+		{
2112
+			return -2;
2113
+		}
2114
+	}
2115
+
2116
+	/**
2117
+	 *	Set the id projet
2118
+	 *
2119
+	 *	@param      User			$user        		Objet utilisateur qui modifie
2120
+	 *	@param      int				$id_projet    	 	Date de livraison
2121
+	 *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2122
+	 *	@return     int         						<0 si ko, >0 si ok
2123
+	 */
2124
+	function set_id_projet($user, $id_projet, $notrigger=0)
2125
+	{
2126
+		if ($user->rights->fournisseur->commande->creer)
2127
+		{
2128
+			$error=0;
2129
+
2130
+			$this->db->begin();
2131
+
2132
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2133
+			$sql.= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2134
+			$sql.= " WHERE rowid = ".$this->id;
2135
+
2136
+			dol_syslog(__METHOD__, LOG_DEBUG);
2137
+			$resql=$this->db->query($sql);
2138
+			if (!$resql)
2139
+			{
2140
+				$this->errors[]=$this->db->error();
2141
+				$error++;
2142
+			}
2143
+
2144
+			if (! $error)
2145
+			{
2146
+				$this->oldcopy= clone $this;
2147
+				$this->fk_projet = $id_projet;
2148
+			}
2149
+
2150
+			if (! $notrigger && empty($error))
2151
+			{
2152
+				// Call trigger
2153
+				$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2154
+				if ($result < 0) $error++;
2155
+				// End call triggers
2156
+			}
2157
+
2158
+			if (! $error)
2159
+			{
2160
+				$this->db->commit();
2161
+				return 1;
2162
+			}
2163
+			else
2164
+			{
2165
+				foreach($this->errors as $errmsg)
2166
+				{
2167
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2168
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2169
+				}
2170
+				$this->db->rollback();
2171
+				return -1*$error;
2172
+			}
2173
+		}
2174
+		else
2175
+		{
2176
+			return -2;
2177
+		}
2178
+	}
2179
+
2180
+	/**
2181
+	 *  Update a supplier order from a customer order
2182
+	 *
2183
+	 *  @param  User	$user           User that create
2184
+	 *  @param  int		$idc			Id of supplier order to update
2185
+	 *  @param	int		$comclientid	Id of customer order to use as template
2186
+	 *	@return	int						<0 if KO, >0 if OK
2187
+	 */
2188
+	public function updateFromCommandeClient($user, $idc, $comclientid)
2189
+	{
2190
+		$comclient = new Commande($this->db);
2191
+		$comclient->fetch($comclientid);
2192
+
2193
+		$this->id = $idc;
2194
+
2195
+		$this->lines = array();
2196
+
2197
+		$num=count($comclient->lines);
2198
+		for ($i = 0; $i < $num; $i++)
2199
+		{
2200
+			$prod = new Product($this->db);
2201
+			if ($prod->fetch($comclient->lines[$i]->fk_product) > 0)
2202
+			{
2203
+				$libelle  = $prod->libelle;
2204
+				$ref      = $prod->ref;
2205
+			}
2206
+
2207
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
2208
+			$sql .= " (fk_commande,label,description,fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2209
+			$sql .= " VALUES (".$idc.", '" . $this->db->escape($libelle) . "','" . $this->db->escape($comclient->lines[$i]->desc) . "'";
2210
+			$sql .= ",".$comclient->lines[$i]->fk_product.",'".price2num($comclient->lines[$i]->price)."'";
2211
+			$sql .= ", '".$comclient->lines[$i]->qty."', ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent;
2212
+			$sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0','".$ref."');";
2213
+			if ($this->db->query($sql))
2214
+			{
2215
+				$this->update_price();
2216
+			}
2217
+		}
2218
+
2219
+		return 1;
2220
+	}
2221
+
2222
+	/**
2223
+	 *  Tag order with a particular status
2224
+	 *
2225
+	 *  @param      User	$user       Object user that change status
2226
+	 *  @param      int		$status		New status
2227
+	 *  @return     int         		<0 if KO, >0 if OK
2228
+	 */
2229
+	public function setStatus($user,$status)
2230
+	{
2231
+		global $conf,$langs;
2232
+		$error=0;
2233
+
2234
+		$this->db->begin();
2235
+
2236
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
2237
+		$sql.= ' SET fk_statut='.$status;
2238
+		$sql.= ' WHERE rowid = '.$this->id;
2239
+
2240
+		dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2241
+		$resql = $this->db->query($sql);
2242
+		if ($resql)
2243
+		{
2244
+			// Trigger names for each status
2245
+			$trigger_name[0] = 'DRAFT';
2246
+			$trigger_name[1] = 'VALIDATED';
2247
+			$trigger_name[2] = 'APPROVED';
2248
+			$trigger_name[3] = 'ONPROCESS';
2249
+			$trigger_name[4] = 'RECEIVED_PARTIALLY';
2250
+			$trigger_name[5] = 'RECEIVED_ALL';
2251
+			$trigger_name[6] = 'CANCELED';
2252
+			$trigger_name[7] = 'CANCELED';
2253
+			$trigger_name[8] = 'BILLED';
2254
+			$trigger_name[9] = 'REFUSED';
2255
+
2256
+			// Call trigger
2257
+			$result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status],$user);
2258
+			if ($result < 0) { $error++; }
2259
+			// End call triggers
2260
+		}
2261
+		else
2262
+		{
2263
+			$error++;
2264
+			$this->error=$this->db->lasterror();
2265
+			dol_syslog(get_class($this)."::setStatus ".$this->error);
2266
+		}
2267
+
2268
+		if (! $error)
2269
+		{
2270
+			$this->statut = $status;
2271
+			$this->db->commit();
2272
+			return 1;
2273
+		}
2274
+		else
2275
+		{
2276
+			$this->db->rollback();
2277
+			return -1;
2278
+		}
2279
+	}
2280
+
2281
+	/**
2282
+	 *	Update line
2283
+	 *
2284
+	 *	@param     	int			$rowid           	Id de la ligne de facture
2285
+	 *	@param     	string		$desc            	Description de la ligne
2286
+	 *	@param     	double		$pu              	Prix unitaire
2287
+	 *	@param     	double		$qty             	Quantity
2288
+	 *	@param     	double		$remise_percent  	Pourcentage de remise de la ligne
2289
+	 *	@param     	double		$txtva          	Taux TVA
2290
+	 *  @param     	double		$txlocaltax1	    Localtax1 tax
2291
+	 *  @param     	double		$txlocaltax2   		Localtax2 tax
2292
+	 *  @param     	double		$price_base_type 	Type of price base
2293
+	 *	@param		int			$info_bits			Miscellaneous informations
2294
+	 *	@param		int			$type				Type of line (0=product, 1=service)
2295
+	 *  @param		int			$notrigger			Disable triggers
2296
+	 *  @param      timestamp   $date_start     	Date start of service
2297
+	 *  @param      timestamp   $date_end       	Date end of service
2298
+	 *  @param		array		$array_options		Extrafields array
2299
+	 * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2300
+	 * 	@param		double		$pu_ht_devise		Unit price in currency
2301
+	 *	@return    	int         	    			< 0 if error, > 0 if ok
2302
+	 */
2303
+	public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0)
2304
+	{
2305
+		global $mysoc, $conf;
2306
+		dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
2307
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2308
+
2309
+		$error = 0;
2310
+
2311
+		if ($this->brouillon)
2312
+		{
2313
+			$this->db->begin();
2314
+
2315
+			// Clean parameters
2316
+			if (empty($qty)) $qty=0;
2317
+			if (empty($info_bits)) $info_bits=0;
2318
+			if (empty($txtva)) $txtva=0;
2319
+			if (empty($txlocaltax1)) $txlocaltax1=0;
2320
+			if (empty($txlocaltax2)) $txlocaltax2=0;
2321
+			if (empty($remise)) $remise=0;
2322
+			if (empty($remise_percent)) $remise_percent=0;
2323
+
2324
+			$remise_percent=price2num($remise_percent);
2325
+			$qty=price2num($qty);
2326
+			if (! $qty) $qty=1;
2327
+			$pu = price2num($pu);
2328
+			$txtva=price2num($txtva);
2329
+			$txlocaltax1=price2num($txlocaltax1);
2330
+			$txlocaltax2=price2num($txlocaltax2);
2331
+
2332
+			// Check parameters
2333
+			if ($type < 0) return -1;
2334
+
2335
+			// Calcul du total TTC et de la TVA pour la ligne a partir de
2336
+			// qty, pu, remise_percent et txtva
2337
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2338
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2339
+
2340
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc, $this->thirdparty);
2341
+
2342
+			// Clean vat code
2343
+			$vat_src_code='';
2344
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
2345
+			{
2346
+				$vat_src_code = $reg[1];
2347
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2348
+			}
2349
+
2350
+			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2351
+			$total_ht  = $tabprice[0];
2352
+			$total_tva = $tabprice[1];
2353
+			$total_ttc = $tabprice[2];
2354
+			$total_localtax1 = $tabprice[9];
2355
+			$total_localtax2 = $tabprice[10];
2356
+			$pu_ht  = $tabprice[3];
2357
+			$pu_tva = $tabprice[4];
2358
+			$pu_ttc = $tabprice[5];
2359
+
2360
+			// MultiCurrency
2361
+			$multicurrency_total_ht  = $tabprice[16];
2362
+			$multicurrency_total_tva = $tabprice[17];
2363
+			$multicurrency_total_ttc = $tabprice[18];
2364
+			$pu_ht_devise = $tabprice[19];
2365
+
2366
+			$localtax1_type=$localtaxes_type[0];
2367
+			$localtax2_type=$localtaxes_type[2];
2368
+
2369
+			$subprice = price2num($pu_ht,'MU');
2370
+
2371
+			//Fetch current line from the database and then clone the object and set it in $oldline property
2372
+			$this->line=new CommandeFournisseurLigne($this->db);
2373
+			$this->line->fetch($rowid);
2374
+			$oldline = clone $this->line;
2375
+			$this->line->oldline = $oldline;
2376
+
2377
+			$this->line->context = $this->context;
2378
+
2379
+			$this->line->fk_commande=$this->id;
2380
+			//$this->line->label=$label;
2381
+			$this->line->desc=$desc;
2382
+			$this->line->qty=$qty;
2383
+
2384
+			$this->line->vat_src_code   = $vat_src_code;
2385
+			$this->line->tva_tx         = $txtva;
2386
+			$this->line->localtax1_tx   = $txlocaltax1;
2387
+			$this->line->localtax2_tx   = $txlocaltax2;
2388
+			$this->line->localtax1_type = $localtaxes_type[0];
2389
+			$this->line->localtax2_type = $localtaxes_type[2];
2390
+			$this->line->remise_percent = $remise_percent;
2391
+			$this->line->subprice       = $pu_ht;
2392
+			$this->line->rang           = $this->rang;
2393
+			$this->line->info_bits      = $info_bits;
2394
+			$this->line->total_ht       = $total_ht;
2395
+			$this->line->total_tva      = $total_tva;
2396
+			$this->line->total_localtax1= $total_localtax1;
2397
+			$this->line->total_localtax2= $total_localtax2;
2398
+			$this->line->total_ttc      = $total_ttc;
2399
+			$this->line->product_type   = $type;
2400
+			$this->line->special_code   = $this->special_code;
2401
+			$this->line->origin         = $this->origin;
2402
+			$this->line->fk_unit        = $fk_unit;
2403
+
2404
+			$this->line->date_start     = $date_start;
2405
+			$this->line->date_end       = $date_end;
2406
+
2407
+			// Multicurrency
2408
+			$this->line->fk_multicurrency			= $this->fk_multicurrency;
2409
+			$this->line->multicurrency_code			= $this->multicurrency_code;
2410
+			$this->line->multicurrency_subprice		= $pu_ht_devise;
2411
+			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2412
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2413
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2414
+
2415
+			$this->line->subprice=$pu_ht;
2416
+			$this->line->price=$this->line->subprice;
2417
+
2418
+			$this->line->remise_percent=$remise_percent;
2419
+
2420
+			if (is_array($array_options) && count($array_options)>0) {
2421
+				$this->line->array_options=$array_options;
2422
+			}
2423
+
2424
+			$result=$this->line->update($notrigger);
2425
+
2426
+
2427
+			// Mise a jour info denormalisees au niveau facture
2428
+			if ($result >= 0)
2429
+			{
2430
+				$this->update_price('','auto');
2431
+				$this->db->commit();
2432
+				return $result;
2433
+			}
2434
+			else
2435
+			{
2436
+				$this->error=$this->db->lasterror();
2437
+				$this->db->rollback();
2438
+				return -1;
2439
+			}
2440
+		}
2441
+		else
2442
+		{
2443
+			$this->error="Order status makes operation forbidden";
2444
+			dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
2445
+			return -2;
2446
+		}
2447
+	}
2448
+
2449
+
2450
+	/**
2451
+	 *  Initialise an instance with random values.
2452
+	 *  Used to build previews or test instances.
2453
+	 *	id must be 0 if object instance is a specimen.
2454
+	 *
2455
+	 *  @return	void
2456
+	 */
2457
+	public function initAsSpecimen()
2458
+	{
2459
+		global $user,$langs,$conf;
2460
+
2461
+		dol_syslog(get_class($this)."::initAsSpecimen");
2462
+
2463
+		$now=dol_now();
2464
+
2465
+		// Find first product
2466
+		$prodid=0;
2467
+		$product=new ProductFournisseur($this->db);
2468
+		$sql = "SELECT rowid";
2469
+		$sql.= " FROM ".MAIN_DB_PREFIX."product";
2470
+		$sql.= " WHERE entity IN (".getEntity('product').")";
2471
+		$sql.=$this->db->order("rowid","ASC");
2472
+		$sql.=$this->db->plimit(1);
2473
+		$resql = $this->db->query($sql);
2474
+		if ($resql)
2475
+		{
2476
+			$obj = $this->db->fetch_object($resql);
2477
+			$prodid = $obj->rowid;
2478
+		}
2479
+
2480
+		// Initialise parametres
2481
+		$this->id=0;
2482
+		$this->ref = 'SPECIMEN';
2483
+		$this->specimen=1;
2484
+		$this->socid = 1;
2485
+		$this->date = $now;
2486
+		$this->date_commande = $now;
2487
+		$this->date_lim_reglement=$this->date+3600*24*30;
2488
+		$this->cond_reglement_code = 'RECEP';
2489
+		$this->mode_reglement_code = 'CHQ';
2490
+		$this->note_public='This is a comment (public)';
2491
+		$this->note_private='This is a comment (private)';
2492
+		$this->statut=0;
2493
+
2494
+		// Lines
2495
+		$nbp = 5;
2496
+		$xnbp = 0;
2497
+		while ($xnbp < $nbp)
2498
+		{
2499
+			$line=new CommandeFournisseurLigne($this->db);
2500
+			$line->desc=$langs->trans("Description")." ".$xnbp;
2501
+			$line->qty=1;
2502
+			$line->subprice=100;
2503
+			$line->price=100;
2504
+			$line->tva_tx=19.6;
2505
+			$line->localtax1_tx=0;
2506
+			$line->localtax2_tx=0;
2507
+			if ($xnbp == 2)
2508
+			{
2509
+				$line->total_ht=50;
2510
+				$line->total_ttc=59.8;
2511
+				$line->total_tva=9.8;
2512
+				$line->remise_percent=50;
2513
+			}
2514
+			else
2515
+			{
2516
+				$line->total_ht=100;
2517
+				$line->total_ttc=119.6;
2518
+				$line->total_tva=19.6;
2519
+				$line->remise_percent=00;
2520
+			}
2521
+			$line->fk_product=$prodid;
2522
+
2523
+			$this->lines[$xnbp]=$line;
2524
+
2525
+			$this->total_ht       += $line->total_ht;
2526
+			$this->total_tva      += $line->total_tva;
2527
+			$this->total_ttc      += $line->total_ttc;
2528
+
2529
+			$xnbp++;
2530
+		}
2531
+	}
2532
+
2533
+	/**
2534
+	 *	Charge les informations d'ordre info dans l'objet facture
2535
+	 *
2536
+	 *	@param  int		$id       	Id de la facture a charger
2537
+	 *	@return	void
2538
+	 */
2539
+	public function info($id)
2540
+	{
2541
+		$sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
2542
+		$sql.= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
2543
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
2544
+		$sql.= ' WHERE c.rowid = '.$id;
2545
+
2546
+		$result=$this->db->query($sql);
2547
+		if ($result)
2548
+		{
2549
+			if ($this->db->num_rows($result))
2550
+			{
2551
+				$obj = $this->db->fetch_object($result);
2552
+				$this->id = $obj->rowid;
2553
+				if ($obj->fk_user_author)   $this->user_creation_id = $obj->fk_user_author;
2554
+				if ($obj->fk_user_valid)    $this->user_validation_id = $obj->fk_user_valid;
2555
+				if ($obj->fk_user_modif)    $this->user_modification_id =$obj->fk_user_modif;
2556
+				if ($obj->fk_user_approve)  $this->user_approve_id = $obj->fk_user_approve;
2557
+				if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2;
2558
+
2559
+				$this->date_creation     = $this->db->idate($obj->datec);
2560
+				$this->date_modification = $this->db->idate($obj->datem);
2561
+				$this->date_approve      = $this->db->idate($obj->datea);
2562
+				$this->date_approve2     = $this->db->idate($obj->datea2);
2563
+				$this->date_validation   = $this->db->idate($obj->date_validation);
2564
+			}
2565
+			$this->db->free($result);
2566
+		}
2567
+		else
2568
+		{
2569
+			dol_print_error($this->db);
2570
+		}
2571
+	}
2572
+
2573
+	/**
2574
+	 *	Charge indicateurs this->nb de tableau de bord
2575
+	 *
2576
+	 *	@return     int         <0 si ko, >0 si ok
2577
+	 */
2578
+	function load_state_board()
2579
+	{
2580
+		global $conf, $user;
2581
+
2582
+		$this->nb=array();
2583
+		$clause = "WHERE";
2584
+
2585
+		$sql = "SELECT count(co.rowid) as nb";
2586
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
2587
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
2588
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
2589
+		{
2590
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2591
+			$sql.= " WHERE sc.fk_user = " .$user->id;
2592
+			$clause = "AND";
2593
+		}
2594
+		$sql.= " ".$clause." co.entity = ".$conf->entity;
2595
+
2596
+		$resql=$this->db->query($sql);
2597
+		if ($resql)
2598
+		{
2599
+			while ($obj=$this->db->fetch_object($resql))
2600
+			{
2601
+				$this->nb["supplier_orders"]=$obj->nb;
2602
+			}
2603
+			$this->db->free($resql);
2604
+			return 1;
2605
+		}
2606
+		else
2607
+		{
2608
+			dol_print_error($this->db);
2609
+			$this->error=$this->db->error();
2610
+			return -1;
2611
+		}
2612
+	}
2613
+
2614
+	/**
2615
+	 *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2616
+	 *
2617
+	 *	@param          User	$user   Objet user
2618
+	 *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
2619
+	 */
2620
+	function load_board($user)
2621
+	{
2622
+		global $conf, $langs;
2623
+
2624
+		$clause = " WHERE";
1925 2625
 
1926
-				$i++;
1927
-			}
2626
+		$sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date";
2627
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
2628
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
2629
+		{
2630
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
2631
+			$sql.= " WHERE sc.fk_user = " .$user->id;
2632
+			$clause = " AND";
1928 2633
 		}
1929
-		else dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2634
+		$sql.= $clause." c.entity = ".$conf->entity;
2635
+		$sql.= " AND (c.fk_statut BETWEEN 1 AND 2)";
2636
+		if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
1930 2637
 
1931
-		return $ret;
1932
-    }
1933
-
1934
-
1935
-    /**
1936
-     * 	Set a delivery in database for this supplier order
1937
-     *
1938
-     *	@param	User	$user		User that input data
1939
-     *	@param	date	$date		Date of reception
1940
-     *	@param	string	$type		Type of receipt ('tot' = total/done, 'par' = partial, 'nev' = never, 'can' = cancel)
1941
-     *	@param	string	$comment	Comment
1942
-     *	@return	int					<0 if KO, >0 if OK
1943
-     */
1944
-    function Livraison($user, $date, $type, $comment)
1945
-    {
1946
-    	global $conf, $langs;
1947
-
1948
-        $result = 0;
1949
-		$error = 0;
2638
+		$resql=$this->db->query($sql);
2639
+		if ($resql)
2640
+		{
2641
+			$commandestatic = new CommandeFournisseur($this->db);
1950 2642
 
1951
-        dol_syslog(get_class($this)."::Livraison");
2643
+			$response = new WorkboardResponse();
2644
+			$response->warning_delay=$conf->commande->fournisseur->warning_delay/60/60/24;
2645
+			$response->label=$langs->trans("SuppliersOrdersToProcess");
2646
+			$response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2,3&mainmenu=commercial&leftmenu=orders_suppliers';
2647
+			$response->img=img_object('',"order");
1952 2648
 
1953
-        if ($user->rights->fournisseur->commande->receptionner)
1954
-        {
1955
-            if ($type == 'par') $statut = 4;
1956
-            if ($type == 'tot')	$statut = 5;
1957
-            if ($type == 'nev') $statut = 7;
1958
-            if ($type == 'can') $statut = 7;
2649
+			while ($obj=$this->db->fetch_object($resql))
2650
+			{
2651
+				$response->nbtodo++;
1959 2652
 
1960
-            // Some checks to accept the record
1961
-            if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
1962
-            {
1963
-				// If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
1964
-	        	if (! $error && ($type == 'tot'))
1965
-		    	{
1966
-		    		$dispatchedlinearray=$this->getDispachedLines(0);
1967
-		    		if (count($dispatchedlinearray) > 0)
1968
-		    		{
1969
-		    			$result=-1;
1970
-		    			$error++;
1971
-		    			$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
1972
-		    			dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
1973
-		    		}
1974
-
1975
-		    	}
1976
-	    		if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot'))	// Accept to move to reception done, only if status of all line are ok (refuse denied)
1977
-	    		{
1978
-	    			$dispatcheddenied=$this->getDispachedLines(2);
1979
-	    			if (count($dispatchedlinearray) > 0)
1980
-	    			{
1981
-		    			$result=-1;
1982
-		    			$error++;
1983
-		    			$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
1984
-		    			dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
1985
-	    			}
1986
-	    		}
1987
-            }
1988
-
1989
-            // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
1990
-
1991
-
1992
-            if (! $error && ! ($statut == 4 or $statut == 5 or $statut == 7))
1993
-            {
1994
-            	$error++;
1995
-                dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
1996
-                $result = -2;
1997
-            }
1998
-
1999
-            if (! $error)
2000
-            {
2001
-                $this->db->begin();
2002
-
2003
-                $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2004
-                $sql.= " SET fk_statut = ".$statut;
2005
-                $sql.= " WHERE rowid = ".$this->id;
2006
-                $sql.= " AND fk_statut IN (3,4)";	// Process running or Partially received
2007
-
2008
-                dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2009
-                $resql=$this->db->query($sql);
2010
-                if ($resql)
2011
-                {
2012
-                    $result = 0;
2013
-                    $old_statut = $this->statut;
2014
-                    $this->statut = $statut;
2015
-					$this->actionmsg2 = $comment;
2653
+				$commandestatic->date_livraison = $this->db->jdate($obj->delivery_date);
2654
+				$commandestatic->date_commande = $this->db->jdate($obj->date_commande);
2655
+				$commandestatic->statut = $obj->fk_statut;
2016 2656
 
2017
-                    // Call trigger
2018
-                    $result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE',$user);
2019
-                    if ($result < 0) $error++;
2020
-                    // End call triggers
2021
-
2022
-                    if (! $error)
2023
-                    {
2024
-                        $this->db->commit();
2025
-                    }
2026
-                    else
2027
-                    {
2028
-                        $this->statut = $old_statut;
2029
-                        $this->db->rollback();
2030
-                        $this->error=$this->db->lasterror();
2031
-                        $result = -1;
2032
-                    }
2033
-                }
2034
-                else
2035
-                {
2036
-                    $this->db->rollback();
2037
-                    $this->error=$this->db->lasterror();
2038
-                    $result = -1;
2039
-                }
2040
-            }
2041
-        }
2042
-        else
2043
-        {
2044
-            $this->error = $langs->trans('NotAuthorized');
2045
-            $this->errors[] = $langs->trans('NotAuthorized');
2046
-            dol_syslog(get_class($this)."::Livraison Not Authorized");
2047
-            $result = -3;
2048
-        }
2049
-        return $result ;
2050
-    }
2657
+				if ($commandestatic->hasDelay()) {
2658
+					$response->nbtodolate++;
2659
+				}
2660
+			}
2051 2661
 
2052
-	/**
2053
-     *	Set the planned delivery date
2054
-     *
2055
-     *	@param      User			$user        		Objet user making change
2056
-     *	@param      timestamp		$date_livraison     Planned delivery date
2057
-     *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2058
-     *	@return     int         						<0 if KO, >0 if OK
2059
-     */
2060
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
2061
-    {
2062
-        if ($user->rights->fournisseur->commande->creer)
2063
-        {
2064
-        	$error=0;
2065
-
2066
-        	$this->db->begin();
2067
-
2068
-        	$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2069
-            $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2070
-            $sql.= " WHERE rowid = ".$this->id;
2071
-
2072
-        	dol_syslog(__METHOD__, LOG_DEBUG);
2073
-        	$resql=$this->db->query($sql);
2074
-        	if (!$resql)
2075
-        	{
2076
-        		$this->errors[]=$this->db->error();
2077
-        		$error++;
2078
-        	}
2079
-
2080
-        	if (! $error)
2081
-        	{
2082
-        		$this->oldcopy= clone $this;
2083
-        		$this->date_livraison = $date_livraison;
2084
-        	}
2085
-
2086
-        	if (! $notrigger && empty($error))
2087
-        	{
2088
-        		// Call trigger
2089
-        		$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2090
-        		if ($result < 0) $error++;
2091
-        		// End call triggers
2092
-        	}
2093
-
2094
-        	if (! $error)
2095
-        	{
2096
-        		$this->db->commit();
2097
-        		return 1;
2098
-        	}
2099
-        	else
2100
-        	{
2101
-        		foreach($this->errors as $errmsg)
2102
-        		{
2103
-        			dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2104
-        			$this->error.=($this->error?', '.$errmsg:$errmsg);
2105
-        		}
2106
-        		$this->db->rollback();
2107
-        		return -1*$error;
2108
-        	}
2109
-        }
2110
-        else
2111
-        {
2112
-            return -2;
2113
-        }
2114
-    }
2662
+			return $response;
2663
+		}
2664
+		else
2665
+		{
2666
+			$this->error=$this->db->error();
2667
+			return -1;
2668
+		}
2669
+	}
2115 2670
 
2116 2671
 	/**
2117
-     *	Set the id projet
2118
-     *
2119
-     *	@param      User			$user        		Objet utilisateur qui modifie
2120
-     *	@param      int				$id_projet    	 	Date de livraison
2121
-     *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2122
-     *	@return     int         						<0 si ko, >0 si ok
2123
-     */
2124
-    function set_id_projet($user, $id_projet, $notrigger=0)
2125
-    {
2126
-        if ($user->rights->fournisseur->commande->creer)
2127
-        {
2128
-        	$error=0;
2129
-
2130
-        	$this->db->begin();
2131
-
2132
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2133
-            $sql.= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2134
-            $sql.= " WHERE rowid = ".$this->id;
2135
-
2136
-            dol_syslog(__METHOD__, LOG_DEBUG);
2137
-            $resql=$this->db->query($sql);
2138
-            if (!$resql)
2139
-            {
2140
-            	$this->errors[]=$this->db->error();
2141
-            	$error++;
2142
-            }
2143
-
2144
-            if (! $error)
2145
-            {
2146
-            	$this->oldcopy= clone $this;
2147
-            	$this->fk_projet = $id_projet;
2148
-            }
2149
-
2150
-            if (! $notrigger && empty($error))
2151
-            {
2152
-            	// Call trigger
2153
-            	$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2154
-            	if ($result < 0) $error++;
2155
-            	// End call triggers
2156
-            }
2157
-
2158
-            if (! $error)
2159
-            {
2160
-            	$this->db->commit();
2161
-            	return 1;
2162
-            }
2163
-            else
2164
-            {
2165
-            	foreach($this->errors as $errmsg)
2166
-            	{
2167
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2168
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2169
-            	}
2170
-            	$this->db->rollback();
2171
-            	return -1*$error;
2172
-            }
2173
-        }
2174
-        else
2175
-        {
2176
-            return -2;
2177
-        }
2178
-    }
2179
-
2180
-    /**
2181
-     *  Update a supplier order from a customer order
2182
-     *
2183
-     *  @param  User	$user           User that create
2184
-     *  @param  int		$idc			Id of supplier order to update
2185
-     *  @param	int		$comclientid	Id of customer order to use as template
2186
-     *	@return	int						<0 if KO, >0 if OK
2187
-     */
2188
-    public function updateFromCommandeClient($user, $idc, $comclientid)
2189
-    {
2190
-        $comclient = new Commande($this->db);
2191
-        $comclient->fetch($comclientid);
2192
-
2193
-        $this->id = $idc;
2194
-
2195
-        $this->lines = array();
2196
-
2197
-        $num=count($comclient->lines);
2198
-        for ($i = 0; $i < $num; $i++)
2199
-        {
2200
-            $prod = new Product($this->db);
2201
-            if ($prod->fetch($comclient->lines[$i]->fk_product) > 0)
2202
-            {
2203
-                $libelle  = $prod->libelle;
2204
-                $ref      = $prod->ref;
2205
-            }
2206
-
2207
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
2208
-            $sql .= " (fk_commande,label,description,fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2209
-            $sql .= " VALUES (".$idc.", '" . $this->db->escape($libelle) . "','" . $this->db->escape($comclient->lines[$i]->desc) . "'";
2210
-            $sql .= ",".$comclient->lines[$i]->fk_product.",'".price2num($comclient->lines[$i]->price)."'";
2211
-            $sql .= ", '".$comclient->lines[$i]->qty."', ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent;
2212
-            $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0','".$ref."');";
2213
-            if ($this->db->query($sql))
2214
-            {
2215
-                $this->update_price();
2216
-            }
2217
-        }
2218
-
2219
-        return 1;
2220
-    }
2221
-
2222
-    /**
2223
-     *  Tag order with a particular status
2224
-     *
2225
-     *  @param      User	$user       Object user that change status
2226
-     *  @param      int		$status		New status
2227
-     *  @return     int         		<0 if KO, >0 if OK
2228
-     */
2229
-    public function setStatus($user,$status)
2230
-    {
2231
-        global $conf,$langs;
2232
-        $error=0;
2233
-
2234
-        $this->db->begin();
2235
-
2236
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
2237
-        $sql.= ' SET fk_statut='.$status;
2238
-        $sql.= ' WHERE rowid = '.$this->id;
2239
-
2240
-        dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2241
-        $resql = $this->db->query($sql);
2242
-        if ($resql)
2243
-        {
2244
-            // Trigger names for each status
2245
-            $trigger_name[0] = 'DRAFT';
2246
-            $trigger_name[1] = 'VALIDATED';
2247
-            $trigger_name[2] = 'APPROVED';
2248
-            $trigger_name[3] = 'ONPROCESS';
2249
-            $trigger_name[4] = 'RECEIVED_PARTIALLY';
2250
-            $trigger_name[5] = 'RECEIVED_ALL';
2251
-            $trigger_name[6] = 'CANCELED';
2252
-            $trigger_name[7] = 'CANCELED';
2253
-            $trigger_name[8] = 'BILLED';
2254
-            $trigger_name[9] = 'REFUSED';
2255
-
2256
-            // Call trigger
2257
-            $result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status],$user);
2258
-            if ($result < 0) { $error++; }
2259
-            // End call triggers
2260
-        }
2261
-        else
2262
-        {
2263
-            $error++;
2264
-            $this->error=$this->db->lasterror();
2265
-            dol_syslog(get_class($this)."::setStatus ".$this->error);
2266
-        }
2267
-
2268
-        if (! $error)
2269
-        {
2270
-            $this->statut = $status;
2271
-            $this->db->commit();
2272
-            return 1;
2273
-        }
2274
-        else
2275
-        {
2276
-            $this->db->rollback();
2277
-            return -1;
2278
-        }
2279
-    }
2280
-
2281
-    /**
2282
-     *	Update line
2283
-     *
2284
-     *	@param     	int			$rowid           	Id de la ligne de facture
2285
-     *	@param     	string		$desc            	Description de la ligne
2286
-     *	@param     	double		$pu              	Prix unitaire
2287
-     *	@param     	double		$qty             	Quantity
2288
-     *	@param     	double		$remise_percent  	Pourcentage de remise de la ligne
2289
-     *	@param     	double		$txtva          	Taux TVA
2290
-     *  @param     	double		$txlocaltax1	    Localtax1 tax
2291
-     *  @param     	double		$txlocaltax2   		Localtax2 tax
2292
-     *  @param     	double		$price_base_type 	Type of price base
2293
-     *	@param		int			$info_bits			Miscellaneous informations
2294
-     *	@param		int			$type				Type of line (0=product, 1=service)
2295
-     *  @param		int			$notrigger			Disable triggers
2296
-     *  @param      timestamp   $date_start     	Date start of service
2297
-     *  @param      timestamp   $date_end       	Date end of service
2298
-	 *  @param		array		$array_options		Extrafields array
2299
-     * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2300
-	 * 	@param		double		$pu_ht_devise		Unit price in currency
2301
-     *	@return    	int         	    			< 0 if error, > 0 if ok
2302
-     */
2303
-    public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0)
2304
-    {
2305
-    	global $mysoc, $conf;
2306
-        dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
2307
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2308
-
2309
-        $error = 0;
2310
-
2311
-        if ($this->brouillon)
2312
-        {
2313
-            $this->db->begin();
2314
-
2315
-            // Clean parameters
2316
-            if (empty($qty)) $qty=0;
2317
-            if (empty($info_bits)) $info_bits=0;
2318
-            if (empty($txtva)) $txtva=0;
2319
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2320
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2321
-            if (empty($remise)) $remise=0;
2322
-            if (empty($remise_percent)) $remise_percent=0;
2323
-
2324
-            $remise_percent=price2num($remise_percent);
2325
-            $qty=price2num($qty);
2326
-            if (! $qty) $qty=1;
2327
-            $pu = price2num($pu);
2328
-            $txtva=price2num($txtva);
2329
-            $txlocaltax1=price2num($txlocaltax1);
2330
-            $txlocaltax2=price2num($txlocaltax2);
2331
-
2332
-            // Check parameters
2333
-            if ($type < 0) return -1;
2334
-
2335
-            // Calcul du total TTC et de la TVA pour la ligne a partir de
2336
-            // qty, pu, remise_percent et txtva
2337
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2338
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2339
-
2340
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc, $this->thirdparty);
2341
-
2342
-            // Clean vat code
2343
-            $vat_src_code='';
2344
-            if (preg_match('/\((.*)\)/', $txtva, $reg))
2345
-            {
2346
-                $vat_src_code = $reg[1];
2347
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2348
-            }
2349
-
2350
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2351
-            $total_ht  = $tabprice[0];
2352
-            $total_tva = $tabprice[1];
2353
-            $total_ttc = $tabprice[2];
2354
-            $total_localtax1 = $tabprice[9];
2355
-            $total_localtax2 = $tabprice[10];
2356
-			$pu_ht  = $tabprice[3];
2357
-			$pu_tva = $tabprice[4];
2358
-			$pu_ttc = $tabprice[5];
2672
+	 * Returns the translated input method of object (defined if $this->methode_commande_id > 0).
2673
+	 * This function make a sql request to get translation. No cache yet, try to not use it inside a loop.
2674
+	 *
2675
+	 * @return string
2676
+	 */
2677
+	public function getInputMethod()
2678
+	{
2679
+		global $db, $langs;
2359 2680
 
2360
-			// MultiCurrency
2361
-			$multicurrency_total_ht  = $tabprice[16];
2362
-            $multicurrency_total_tva = $tabprice[17];
2363
-            $multicurrency_total_ttc = $tabprice[18];
2364
-			$pu_ht_devise = $tabprice[19];
2681
+		if ($this->methode_commande_id > 0)
2682
+		{
2683
+			$sql = "SELECT rowid, code, libelle as label";
2684
+			$sql.= " FROM ".MAIN_DB_PREFIX.'c_input_method';
2685
+			$sql.= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
2365 2686
 
2366
-            $localtax1_type=$localtaxes_type[0];
2367
-			$localtax2_type=$localtaxes_type[2];
2687
+			$resql = $db->query($sql);
2688
+			if ($resql)
2689
+			{
2690
+				if ($db->num_rows($query))
2691
+				{
2692
+					$obj = $db->fetch_object($query);
2368 2693
 
2369
-            $subprice = price2num($pu_ht,'MU');
2370
-
2371
-            //Fetch current line from the database and then clone the object and set it in $oldline property
2372
-            $this->line=new CommandeFournisseurLigne($this->db);
2373
-            $this->line->fetch($rowid);
2374
-            $oldline = clone $this->line;
2375
-            $this->line->oldline = $oldline;
2376
-
2377
-            $this->line->context = $this->context;
2378
-
2379
-            $this->line->fk_commande=$this->id;
2380
-            //$this->line->label=$label;
2381
-            $this->line->desc=$desc;
2382
-            $this->line->qty=$qty;
2383
-
2384
-	        $this->line->vat_src_code   = $vat_src_code;
2385
-            $this->line->tva_tx         = $txtva;
2386
-            $this->line->localtax1_tx   = $txlocaltax1;
2387
-            $this->line->localtax2_tx   = $txlocaltax2;
2388
-            $this->line->localtax1_type = $localtaxes_type[0];
2389
-            $this->line->localtax2_type = $localtaxes_type[2];
2390
-            $this->line->remise_percent = $remise_percent;
2391
-            $this->line->subprice       = $pu_ht;
2392
-            $this->line->rang           = $this->rang;
2393
-            $this->line->info_bits      = $info_bits;
2394
-            $this->line->total_ht       = $total_ht;
2395
-            $this->line->total_tva      = $total_tva;
2396
-            $this->line->total_localtax1= $total_localtax1;
2397
-            $this->line->total_localtax2= $total_localtax2;
2398
-            $this->line->total_ttc      = $total_ttc;
2399
-            $this->line->product_type   = $type;
2400
-            $this->line->special_code   = $this->special_code;
2401
-            $this->line->origin         = $this->origin;
2402
-            $this->line->fk_unit        = $fk_unit;
2403
-
2404
-            $this->line->date_start     = $date_start;
2405
-            $this->line->date_end       = $date_end;
2406
-
2407
-            // Multicurrency
2408
-            $this->line->fk_multicurrency			= $this->fk_multicurrency;
2409
-            $this->line->multicurrency_code			= $this->multicurrency_code;
2410
-            $this->line->multicurrency_subprice		= $pu_ht_devise;
2411
-            $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2412
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2413
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2414
-
2415
-            $this->line->subprice=$pu_ht;
2416
-            $this->line->price=$this->line->subprice;
2417
-
2418
-            $this->line->remise_percent=$remise_percent;
2419
-
2420
-            if (is_array($array_options) && count($array_options)>0) {
2421
-                $this->line->array_options=$array_options;
2422
-            }
2423
-
2424
-            $result=$this->line->update($notrigger);
2425
-
2426
-
2427
-            // Mise a jour info denormalisees au niveau facture
2428
-            if ($result >= 0)
2429
-            {
2430
-                $this->update_price('','auto');
2431
-				$this->db->commit();
2432
-				return $result;
2433
-            }
2434
-            else
2435
-            {
2436
-                $this->error=$this->db->lasterror();
2437
-                $this->db->rollback();
2438
-                return -1;
2439
-            }
2440
-        }
2441
-        else
2442
-        {
2443
-            $this->error="Order status makes operation forbidden";
2444
-            dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
2445
-            return -2;
2446
-        }
2447
-    }
2448
-
2449
-
2450
-    /**
2451
-     *  Initialise an instance with random values.
2452
-     *  Used to build previews or test instances.
2453
-     *	id must be 0 if object instance is a specimen.
2454
-     *
2455
-     *  @return	void
2456
-     */
2457
-    public function initAsSpecimen()
2458
-    {
2459
-        global $user,$langs,$conf;
2460
-
2461
-        dol_syslog(get_class($this)."::initAsSpecimen");
2462
-
2463
-        $now=dol_now();
2464
-
2465
-        // Find first product
2466
-        $prodid=0;
2467
-        $product=new ProductFournisseur($this->db);
2468
-        $sql = "SELECT rowid";
2469
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
2470
-        $sql.= " WHERE entity IN (".getEntity('product').")";
2471
-        $sql.=$this->db->order("rowid","ASC");
2472
-        $sql.=$this->db->plimit(1);
2473
-        $resql = $this->db->query($sql);
2474
-        if ($resql)
2475
-        {
2476
-            $obj = $this->db->fetch_object($resql);
2477
-            $prodid = $obj->rowid;
2478
-        }
2479
-
2480
-        // Initialise parametres
2481
-        $this->id=0;
2482
-        $this->ref = 'SPECIMEN';
2483
-        $this->specimen=1;
2484
-        $this->socid = 1;
2485
-        $this->date = $now;
2486
-        $this->date_commande = $now;
2487
-        $this->date_lim_reglement=$this->date+3600*24*30;
2488
-        $this->cond_reglement_code = 'RECEP';
2489
-        $this->mode_reglement_code = 'CHQ';
2490
-        $this->note_public='This is a comment (public)';
2491
-        $this->note_private='This is a comment (private)';
2492
-        $this->statut=0;
2493
-
2494
-        // Lines
2495
-        $nbp = 5;
2496
-        $xnbp = 0;
2497
-        while ($xnbp < $nbp)
2498
-        {
2499
-            $line=new CommandeFournisseurLigne($this->db);
2500
-            $line->desc=$langs->trans("Description")." ".$xnbp;
2501
-            $line->qty=1;
2502
-            $line->subprice=100;
2503
-            $line->price=100;
2504
-            $line->tva_tx=19.6;
2505
-            $line->localtax1_tx=0;
2506
-            $line->localtax2_tx=0;
2507
-            if ($xnbp == 2)
2508
-            {
2509
-                $line->total_ht=50;
2510
-                $line->total_ttc=59.8;
2511
-                $line->total_tva=9.8;
2512
-                $line->remise_percent=50;
2513
-            }
2514
-            else
2515
-            {
2516
-                $line->total_ht=100;
2517
-                $line->total_ttc=119.6;
2518
-                $line->total_tva=19.6;
2519
-                $line->remise_percent=00;
2520
-            }
2521
-            $line->fk_product=$prodid;
2522
-
2523
-            $this->lines[$xnbp]=$line;
2524
-
2525
-            $this->total_ht       += $line->total_ht;
2526
-            $this->total_tva      += $line->total_tva;
2527
-            $this->total_ttc      += $line->total_ttc;
2528
-
2529
-            $xnbp++;
2530
-        }
2531
-    }
2532
-
2533
-    /**
2534
-     *	Charge les informations d'ordre info dans l'objet facture
2535
-     *
2536
-     *	@param  int		$id       	Id de la facture a charger
2537
-     *	@return	void
2538
-     */
2539
-    public function info($id)
2540
-    {
2541
-        $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
2542
-        $sql.= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
2543
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
2544
-        $sql.= ' WHERE c.rowid = '.$id;
2545
-
2546
-        $result=$this->db->query($sql);
2547
-        if ($result)
2548
-        {
2549
-            if ($this->db->num_rows($result))
2550
-            {
2551
-                $obj = $this->db->fetch_object($result);
2552
-                $this->id = $obj->rowid;
2553
-                if ($obj->fk_user_author)   $this->user_creation_id = $obj->fk_user_author;
2554
-                if ($obj->fk_user_valid)    $this->user_validation_id = $obj->fk_user_valid;
2555
-                if ($obj->fk_user_modif)    $this->user_modification_id =$obj->fk_user_modif;
2556
-                if ($obj->fk_user_approve)  $this->user_approve_id = $obj->fk_user_approve;
2557
-                if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2;
2558
-
2559
-                $this->date_creation     = $this->db->idate($obj->datec);
2560
-                $this->date_modification = $this->db->idate($obj->datem);
2561
-                $this->date_approve      = $this->db->idate($obj->datea);
2562
-                $this->date_approve2     = $this->db->idate($obj->datea2);
2563
-                $this->date_validation   = $this->db->idate($obj->date_validation);
2564
-            }
2565
-            $this->db->free($result);
2566
-        }
2567
-        else
2568
-        {
2569
-            dol_print_error($this->db);
2570
-        }
2571
-    }
2572
-
2573
-    /**
2574
-     *	Charge indicateurs this->nb de tableau de bord
2575
-     *
2576
-     *	@return     int         <0 si ko, >0 si ok
2577
-     */
2578
-    function load_state_board()
2579
-    {
2580
-        global $conf, $user;
2581
-
2582
-        $this->nb=array();
2583
-        $clause = "WHERE";
2584
-
2585
-        $sql = "SELECT count(co.rowid) as nb";
2586
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
2587
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
2588
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
2589
-        {
2590
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2591
-            $sql.= " WHERE sc.fk_user = " .$user->id;
2592
-            $clause = "AND";
2593
-        }
2594
-        $sql.= " ".$clause." co.entity = ".$conf->entity;
2595
-
2596
-        $resql=$this->db->query($sql);
2597
-        if ($resql)
2598
-        {
2599
-            while ($obj=$this->db->fetch_object($resql))
2600
-            {
2601
-                $this->nb["supplier_orders"]=$obj->nb;
2602
-            }
2603
-            $this->db->free($resql);
2604
-            return 1;
2605
-        }
2606
-        else
2607
-        {
2608
-            dol_print_error($this->db);
2609
-            $this->error=$this->db->error();
2610
-            return -1;
2611
-        }
2612
-    }
2613
-
2614
-    /**
2615
-     *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2616
-     *
2617
-     *	@param          User	$user   Objet user
2618
-     *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
2619
-     */
2620
-    function load_board($user)
2621
-    {
2622
-        global $conf, $langs;
2623
-
2624
-        $clause = " WHERE";
2625
-
2626
-        $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date";
2627
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
2628
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
2629
-        {
2630
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
2631
-            $sql.= " WHERE sc.fk_user = " .$user->id;
2632
-            $clause = " AND";
2633
-        }
2634
-        $sql.= $clause." c.entity = ".$conf->entity;
2635
-        $sql.= " AND (c.fk_statut BETWEEN 1 AND 2)";
2636
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2637
-
2638
-        $resql=$this->db->query($sql);
2639
-        if ($resql)
2640
-        {
2641
-            $commandestatic = new CommandeFournisseur($this->db);
2642
-
2643
-	        $response = new WorkboardResponse();
2644
-	        $response->warning_delay=$conf->commande->fournisseur->warning_delay/60/60/24;
2645
-	        $response->label=$langs->trans("SuppliersOrdersToProcess");
2646
-	        $response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2,3&mainmenu=commercial&leftmenu=orders_suppliers';
2647
-	        $response->img=img_object('',"order");
2648
-
2649
-            while ($obj=$this->db->fetch_object($resql))
2650
-            {
2651
-                $response->nbtodo++;
2652
-
2653
-                $commandestatic->date_livraison = $this->db->jdate($obj->delivery_date);
2654
-                $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
2655
-                $commandestatic->statut = $obj->fk_statut;
2656
-
2657
-                if ($commandestatic->hasDelay()) {
2658
-	                $response->nbtodolate++;
2659
-                }
2660
-            }
2661
-
2662
-            return $response;
2663
-        }
2664
-        else
2665
-        {
2666
-            $this->error=$this->db->error();
2667
-            return -1;
2668
-        }
2669
-    }
2670
-
2671
-    /**
2672
-     * Returns the translated input method of object (defined if $this->methode_commande_id > 0).
2673
-     * This function make a sql request to get translation. No cache yet, try to not use it inside a loop.
2674
-     *
2675
-     * @return string
2676
-     */
2677
-    public function getInputMethod()
2678
-    {
2679
-        global $db, $langs;
2680
-
2681
-        if ($this->methode_commande_id > 0)
2682
-        {
2683
-            $sql = "SELECT rowid, code, libelle as label";
2684
-            $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_method';
2685
-            $sql.= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
2686
-
2687
-            $resql = $db->query($sql);
2688
-            if ($resql)
2689
-            {
2690
-                if ($db->num_rows($query))
2691
-                {
2692
-                    $obj = $db->fetch_object($query);
2693
-
2694
-                    $string = $langs->trans($obj->code);
2695
-                    if ($string == $obj->code)
2696
-                    {
2697
-                        $string = $obj->label != '-' ? $obj->label : '';
2698
-                    }
2699
-                    return $string;
2700
-                }
2701
-            }
2702
-            else dol_print_error($db);
2703
-        }
2704
-
2705
-        return '';
2706
-    }
2694
+					$string = $langs->trans($obj->code);
2695
+					if ($string == $obj->code)
2696
+					{
2697
+						$string = $obj->label != '-' ? $obj->label : '';
2698
+					}
2699
+					return $string;
2700
+				}
2701
+			}
2702
+			else dol_print_error($db);
2703
+		}
2704
+
2705
+		return '';
2706
+	}
2707 2707
 
2708 2708
 	/**
2709 2709
 	 *  Create a document onto disk according to template model.
@@ -2738,12 +2738,12 @@  discard block
 block discarded – undo
2738 2738
 	}
2739 2739
 
2740 2740
 	/**
2741
-     * Return the max number delivery delay in day
2742
-     *
2743
-     * @param	Translate	$langs		Language object
2744
-     * @return 							Translated string
2745
-     */
2746
-    public function getMaxDeliveryTimeDay($langs)
2741
+	 * Return the max number delivery delay in day
2742
+	 *
2743
+	 * @param	Translate	$langs		Language object
2744
+	 * @return 							Translated string
2745
+	 */
2746
+	public function getMaxDeliveryTimeDay($langs)
2747 2747
 	{
2748 2748
 		if (empty($this->lines)) return '';
2749 2749
 
@@ -2796,134 +2796,134 @@  discard block
 block discarded – undo
2796 2796
 		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2797 2797
 	}
2798 2798
 
2799
-    /**
2800
-     * Is the supplier order delayed?
2801
-     *
2802
-     * @return bool
2803
-     */
2804
-    public function hasDelay()
2805
-    {
2806
-        global $conf;
2807
-
2808
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2809
-
2810
-        $now = dol_now();
2811
-        $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery;
2812
-
2813
-        return ($this->statut > 0 && $this->statut < 4) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
2814
-    }
2815
-
2816
-    /**
2817
-     * Show the customer delayed info
2818
-     *
2819
-     * @return string       Show delayed information
2820
-     */
2821
-    public function showDelay()
2822
-    {
2823
-        global $conf, $langs;
2824
-
2825
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2826
-
2827
-        if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2828
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2829
-        $text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
2830
-
2831
-        return $text;
2832
-    }
2833
-
2834
-
2835
-    /**
2836
-     * Calc status regarding to dispatched stock
2837
-     *
2838
-     * @param 		User 	$user                   User action
2839
-     * @param       int     $closeopenorder         Close if received
2840
-     * @param		string	$comment				Comment
2841
-     * @return		int		                        <0 if KO, 0 if not applicable, >0 if OK
2842
-     */
2843
-    public function calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
2844
-    {
2845
-    	global $conf, $langs;
2846
-
2847
-    	if (! empty($conf->fournisseur->enabled))
2848
-    	{
2849
-    		require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
2850
-
2851
-    		$qtydelivered=array();
2852
-    		$qtywished=array();
2853
-
2854
-    		$supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
2855
-    		$filter=array('t.fk_commande'=>$this->id);
2856
-    		if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2857
-    			$filter['t.status']=1;	// Restrict to lines with status validated
2858
-    		}
2859
-
2860
-    		$ret=$supplierorderdispatch->fetchAll('','',0,0,$filter);
2861
-    		if ($ret<0)
2862
-    		{
2863
-    			$this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors;
2864
-    			return $ret;
2865
-    		}
2866
-    		else
2867
-    		{
2868
-    			if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0)
2869
-    			{
2870
-    				$date_liv = dol_now();
2871
-
2872
-    				// Build array with quantity deliverd by product
2873
-    				foreach($supplierorderdispatch->lines as $line) {
2874
-    					$qtydelivered[$line->fk_product]+=$line->qty;
2875
-    				}
2876
-    				foreach($this->lines as $line) {
2877
-    					$qtywished[$line->fk_product]+=$line->qty;
2878
-    				}
2879
-    				//Compare array
2880
-    				$diff_array=array_diff_assoc($qtydelivered,$qtywished);		// Warning: $diff_array is done only on common keys.
2881
-    				$keysinwishednotindelivered=array_diff(array_keys($qtywished),array_keys($qtydelivered));		// To check we also have same number of keys
2882
-    				$keysindeliverednotinwished=array_diff(array_keys($qtydelivered),array_keys($qtywished));		// To check we also have same number of keys
2883
-    				/*var_dump(array_keys($qtydelivered));
2799
+	/**
2800
+	 * Is the supplier order delayed?
2801
+	 *
2802
+	 * @return bool
2803
+	 */
2804
+	public function hasDelay()
2805
+	{
2806
+		global $conf;
2807
+
2808
+		if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2809
+
2810
+		$now = dol_now();
2811
+		$date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery;
2812
+
2813
+		return ($this->statut > 0 && $this->statut < 4) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
2814
+	}
2815
+
2816
+	/**
2817
+	 * Show the customer delayed info
2818
+	 *
2819
+	 * @return string       Show delayed information
2820
+	 */
2821
+	public function showDelay()
2822
+	{
2823
+		global $conf, $langs;
2824
+
2825
+		if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2826
+
2827
+		if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2828
+		else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2829
+		$text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
2830
+
2831
+		return $text;
2832
+	}
2833
+
2834
+
2835
+	/**
2836
+	 * Calc status regarding to dispatched stock
2837
+	 *
2838
+	 * @param 		User 	$user                   User action
2839
+	 * @param       int     $closeopenorder         Close if received
2840
+	 * @param		string	$comment				Comment
2841
+	 * @return		int		                        <0 if KO, 0 if not applicable, >0 if OK
2842
+	 */
2843
+	public function calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
2844
+	{
2845
+		global $conf, $langs;
2846
+
2847
+		if (! empty($conf->fournisseur->enabled))
2848
+		{
2849
+			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
2850
+
2851
+			$qtydelivered=array();
2852
+			$qtywished=array();
2853
+
2854
+			$supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
2855
+			$filter=array('t.fk_commande'=>$this->id);
2856
+			if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2857
+				$filter['t.status']=1;	// Restrict to lines with status validated
2858
+			}
2859
+
2860
+			$ret=$supplierorderdispatch->fetchAll('','',0,0,$filter);
2861
+			if ($ret<0)
2862
+			{
2863
+				$this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors;
2864
+				return $ret;
2865
+			}
2866
+			else
2867
+			{
2868
+				if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0)
2869
+				{
2870
+					$date_liv = dol_now();
2871
+
2872
+					// Build array with quantity deliverd by product
2873
+					foreach($supplierorderdispatch->lines as $line) {
2874
+						$qtydelivered[$line->fk_product]+=$line->qty;
2875
+					}
2876
+					foreach($this->lines as $line) {
2877
+						$qtywished[$line->fk_product]+=$line->qty;
2878
+					}
2879
+					//Compare array
2880
+					$diff_array=array_diff_assoc($qtydelivered,$qtywished);		// Warning: $diff_array is done only on common keys.
2881
+					$keysinwishednotindelivered=array_diff(array_keys($qtywished),array_keys($qtydelivered));		// To check we also have same number of keys
2882
+					$keysindeliverednotinwished=array_diff(array_keys($qtydelivered),array_keys($qtywished));		// To check we also have same number of keys
2883
+					/*var_dump(array_keys($qtydelivered));
2884 2884
     				var_dump(array_keys($qtywished));
2885 2885
     				var_dump($diff_array);
2886 2886
     				var_dump($keysinwishednotindelivered);
2887 2887
     				var_dump($keysindeliverednotinwished);
2888 2888
     				exit;*/
2889 2889
 
2890
-    				if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received
2891
-    				{
2892
-    					if ($closeopenorder)
2893
-    					{
2894
-        					//$ret=$this->setStatus($user,5);
2895
-    						$ret = $this->Livraison($user, $date_liv, 'tot', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2896
-        					if ($ret<0) {
2897
-        						return -1;
2898
-        					}
2899
-    					    return 5;
2900
-    					}
2901
-    					else
2902
-    					{
2903
-    					    //Diff => received partially
2904
-    					    //$ret=$this->setStatus($user,4);
2905
-    						$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2906
-    					    if ($ret<0) {
2907
-    					        return -1;
2908
-    					    }
2909
-    					    return 4;
2910
-    					}
2911
-    				}
2912
-    				else
2913
-    				{
2914
-    					//Diff => received partially
2915
-    					$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2916
-    					if ($ret<0) {
2917
-    						return -1;
2918
-    					}
2919
-    					return 4;
2920
-    				}
2921
-    			}
2922
-    			return 1;
2923
-    		}
2924
-    	}
2925
-    	return 0;
2926
-    }
2890
+					if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received
2891
+					{
2892
+						if ($closeopenorder)
2893
+						{
2894
+							//$ret=$this->setStatus($user,5);
2895
+							$ret = $this->Livraison($user, $date_liv, 'tot', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2896
+							if ($ret<0) {
2897
+								return -1;
2898
+							}
2899
+							return 5;
2900
+						}
2901
+						else
2902
+						{
2903
+							//Diff => received partially
2904
+							//$ret=$this->setStatus($user,4);
2905
+							$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2906
+							if ($ret<0) {
2907
+								return -1;
2908
+							}
2909
+							return 4;
2910
+						}
2911
+					}
2912
+					else
2913
+					{
2914
+						//Diff => received partially
2915
+						$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2916
+						if ($ret<0) {
2917
+							return -1;
2918
+						}
2919
+						return 4;
2920
+					}
2921
+				}
2922
+				return 1;
2923
+			}
2924
+		}
2925
+		return 0;
2926
+	}
2927 2927
 }
2928 2928
 
2929 2929
 
@@ -2933,22 +2933,22 @@  discard block
 block discarded – undo
2933 2933
  */
2934 2934
 class CommandeFournisseurLigne extends CommonOrderLine
2935 2935
 {
2936
-    public $element='commande_fournisseurdet';
2936
+	public $element='commande_fournisseurdet';
2937 2937
 	public $table_element='commande_fournisseurdet';
2938 2938
 
2939
-    public $oldline;
2939
+	public $oldline;
2940 2940
 
2941
-    /**
2942
-     * Id of parent order
2943
-     * @var int
2944
-     */
2945
-    public $fk_commande;
2941
+	/**
2942
+	 * Id of parent order
2943
+	 * @var int
2944
+	 */
2945
+	public $fk_commande;
2946 2946
 
2947
-    // From llx_commande_fournisseurdet
2948
-    public $fk_parent_line;
2949
-    public $fk_facture;
2950
-    public $label;
2951
-    public $rang = 0;
2947
+	// From llx_commande_fournisseurdet
2948
+	public $fk_parent_line;
2949
+	public $fk_facture;
2950
+	public $label;
2951
+	public $rang = 0;
2952 2952
 
2953 2953
 	/**
2954 2954
 	 * Unit price without taxes
@@ -2956,401 +2956,401 @@  discard block
 block discarded – undo
2956 2956
 	 */
2957 2957
 	public $pu_ht;
2958 2958
 
2959
-    public $date_start;
2960
-    public $date_end;
2959
+	public $date_start;
2960
+	public $date_end;
2961 2961
 
2962
-    // From llx_product_fournisseur_price
2962
+	// From llx_product_fournisseur_price
2963 2963
 
2964 2964
 	/**
2965 2965
 	 * Supplier reference of price when we added the line. May have been changed after line was added.
2966 2966
 	 * @var string
2967 2967
 	 */
2968
-    public $ref_supplier;
2969
-    public $remise;
2970
-    public $product_libelle;
2971
-
2972
-
2973
-    /**
2974
-     *	Constructor
2975
-     *
2976
-     *  @param		DoliDB		$db      Database handler
2977
-     */
2978
-    public function __construct($db)
2979
-    {
2980
-        $this->db= $db;
2981
-    }
2982
-
2983
-    /**
2984
-     *  Load line order
2985
-     *
2986
-     *  @param  int		$rowid      Id line order
2987
-     *	@return	int					<0 if KO, >0 if OK
2988
-     */
2989
-    public function fetch($rowid)
2990
-    {
2991
-        $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx,';
2992
-        $sql.= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,';
2993
-        $sql.= ' cd.remise, cd.remise_percent, cd.subprice,';
2994
-        $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
2995
-        $sql.= ' cd.total_localtax1, cd.total_localtax2,';
2996
-        $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,';
2997
-        $sql.= ' cd.date_start, cd.date_end, cd.fk_unit,';
2968
+	public $ref_supplier;
2969
+	public $remise;
2970
+	public $product_libelle;
2971
+
2972
+
2973
+	/**
2974
+	 *	Constructor
2975
+	 *
2976
+	 *  @param		DoliDB		$db      Database handler
2977
+	 */
2978
+	public function __construct($db)
2979
+	{
2980
+		$this->db= $db;
2981
+	}
2982
+
2983
+	/**
2984
+	 *  Load line order
2985
+	 *
2986
+	 *  @param  int		$rowid      Id line order
2987
+	 *	@return	int					<0 if KO, >0 if OK
2988
+	 */
2989
+	public function fetch($rowid)
2990
+	{
2991
+		$sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx,';
2992
+		$sql.= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,';
2993
+		$sql.= ' cd.remise, cd.remise_percent, cd.subprice,';
2994
+		$sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
2995
+		$sql.= ' cd.total_localtax1, cd.total_localtax2,';
2996
+		$sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,';
2997
+		$sql.= ' cd.date_start, cd.date_end, cd.fk_unit,';
2998 2998
 		$sql.= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc';
2999
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3000
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3001
-        $sql.= ' WHERE cd.rowid = '.$rowid;
3002
-        $result = $this->db->query($sql);
3003
-        if ($result)
3004
-        {
3005
-            $objp = $this->db->fetch_object($result);
3006
-
3007
-            $this->rowid            = $objp->rowid;
3008
-            $this->id               = $objp->rowid;
3009
-            $this->fk_commande      = $objp->fk_commande;
3010
-            $this->desc             = $objp->description;
3011
-            $this->qty              = $objp->qty;
3012
-            $this->ref_fourn        = $objp->ref;
3013
-            $this->ref_supplier     = $objp->ref;
3014
-            $this->subprice         = $objp->subprice;
3015
-            $this->tva_tx           = $objp->tva_tx;
3016
-            $this->localtax1_tx		= $objp->localtax1_tx;
3017
-            $this->localtax2_tx		= $objp->localtax2_tx;
3018
-            $this->localtax1_type	= $objp->localtax1_type;
3019
-            $this->localtax2_type	= $objp->localtax2_type;
3020
-            $this->remise           = $objp->remise;
3021
-            $this->remise_percent   = $objp->remise_percent;
3022
-            $this->fk_product       = $objp->fk_product;
3023
-            $this->info_bits        = $objp->info_bits;
3024
-            $this->total_ht         = $objp->total_ht;
3025
-            $this->total_tva        = $objp->total_tva;
3026
-            $this->total_localtax1	= $objp->total_localtax1;
3027
-            $this->total_localtax2	= $objp->total_localtax2;
3028
-            $this->total_ttc        = $objp->total_ttc;
3029
-            $this->product_type     = $objp->product_type;
3030
-
3031
-            $this->ref	            = $objp->product_ref;
3032
-            $this->product_ref      = $objp->product_ref;
3033
-            $this->product_libelle  = $objp->product_libelle;
3034
-            $this->product_desc     = $objp->product_desc;
3035
-
3036
-            $this->date_start       		= $this->db->jdate($objp->date_start);
3037
-            $this->date_end         		= $this->db->jdate($objp->date_end);
3038
-	        $this->fk_unit          		= $objp->fk_unit;
2999
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3000
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3001
+		$sql.= ' WHERE cd.rowid = '.$rowid;
3002
+		$result = $this->db->query($sql);
3003
+		if ($result)
3004
+		{
3005
+			$objp = $this->db->fetch_object($result);
3006
+
3007
+			$this->rowid            = $objp->rowid;
3008
+			$this->id               = $objp->rowid;
3009
+			$this->fk_commande      = $objp->fk_commande;
3010
+			$this->desc             = $objp->description;
3011
+			$this->qty              = $objp->qty;
3012
+			$this->ref_fourn        = $objp->ref;
3013
+			$this->ref_supplier     = $objp->ref;
3014
+			$this->subprice         = $objp->subprice;
3015
+			$this->tva_tx           = $objp->tva_tx;
3016
+			$this->localtax1_tx		= $objp->localtax1_tx;
3017
+			$this->localtax2_tx		= $objp->localtax2_tx;
3018
+			$this->localtax1_type	= $objp->localtax1_type;
3019
+			$this->localtax2_type	= $objp->localtax2_type;
3020
+			$this->remise           = $objp->remise;
3021
+			$this->remise_percent   = $objp->remise_percent;
3022
+			$this->fk_product       = $objp->fk_product;
3023
+			$this->info_bits        = $objp->info_bits;
3024
+			$this->total_ht         = $objp->total_ht;
3025
+			$this->total_tva        = $objp->total_tva;
3026
+			$this->total_localtax1	= $objp->total_localtax1;
3027
+			$this->total_localtax2	= $objp->total_localtax2;
3028
+			$this->total_ttc        = $objp->total_ttc;
3029
+			$this->product_type     = $objp->product_type;
3030
+
3031
+			$this->ref	            = $objp->product_ref;
3032
+			$this->product_ref      = $objp->product_ref;
3033
+			$this->product_libelle  = $objp->product_libelle;
3034
+			$this->product_desc     = $objp->product_desc;
3035
+
3036
+			$this->date_start       		= $this->db->jdate($objp->date_start);
3037
+			$this->date_end         		= $this->db->jdate($objp->date_end);
3038
+			$this->fk_unit          		= $objp->fk_unit;
3039 3039
 
3040 3040
 			$this->multicurrency_subprice	= $objp->multicurrency_subprice;
3041 3041
 			$this->multicurrency_total_ht	= $objp->multicurrency_total_ht;
3042 3042
 			$this->multicurrency_total_tva	= $objp->multicurrency_total_tva;
3043 3043
 			$this->multicurrency_total_ttc	= $objp->multicurrency_total_ttc;
3044 3044
 
3045
-            $this->db->free($result);
3046
-            return 1;
3047
-        }
3048
-        else
3049
-        {
3050
-            dol_print_error($this->db);
3051
-            return -1;
3052
-        }
3053
-    }
3054
-
3055
-    /**
3056
-     *  Mise a jour de l'objet ligne de commande en base
3057
-     *
3058
-     *  @return		int		<0 si ko, >0 si ok
3059
-     */
3060
-    public function updateTotal()
3061
-    {
3062
-        $this->db->begin();
3063
-
3064
-        // Mise a jour ligne en base
3065
-        $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseurdet SET";
3066
-        $sql.= " total_ht='".price2num($this->total_ht)."'";
3067
-        $sql.= ",total_tva='".price2num($this->total_tva)."'";
3068
-        $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
3069
-        $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
3070
-        $sql.= ",total_ttc='".price2num($this->total_ttc)."'";
3071
-        $sql.= " WHERE rowid = ".$this->rowid;
3072
-
3073
-        dol_syslog(get_class($this)."::updateTotal", LOG_DEBUG);
3074
-
3075
-        $resql=$this->db->query($sql);
3076
-        if ($resql)
3077
-        {
3078
-            $this->db->commit();
3079
-            return 1;
3080
-        }
3081
-        else
3082
-        {
3083
-            $this->error=$this->db->error();
3084
-            $this->db->rollback();
3085
-            return -2;
3086
-        }
3087
-    }
3088
-
3089
-    /**
3090
-     *	Insert line into database
3091
-     *
3092
-     *	@param      int		$notrigger		1 = disable triggers
3093
-     *	@return		int						<0 if KO, >0 if OK
3094
-     */
3095
-    public function insert($notrigger=0)
3096
-    {
3097
-        global $conf, $user;
3098
-
3099
-        $error=0;
3100
-
3101
-        dol_syslog(get_class($this)."::insert rang=".$this->rang);
3102
-
3103
-        // Clean parameters
3104
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3105
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3106
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3107
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
3108
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
3109
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3110
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3111
-        if (empty($this->rang)) $this->rang=0;
3112
-        if (empty($this->remise)) $this->remise=0;
3113
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3114
-        if (empty($this->info_bits)) $this->info_bits=0;
3115
-        if (empty($this->special_code)) $this->special_code=0;
3116
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3117
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3118
-
3119
-        // Multicurrency
3120
-        if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3121
-        if (empty($this->fk_multicurrency))
3122
-        {
3123
-            $this->multicurrency_code = $conf->currency;
3124
-            $this->fk_multicurrency = 0;
3125
-            $this->multicurrency_tx = 1;
3126
-        }
3127
-
3128
-        // Check parameters
3129
-        if ($this->product_type < 0) return -1;
3130
-
3131
-        $this->db->begin();
3132
-
3133
-        // Insertion dans base de la ligne
3134
-        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
3135
-        $sql.= " (fk_commande, label, description, date_start, date_end,";
3136
-        $sql.= " fk_product, product_type,";
3137
-        $sql.= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3138
-        $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3139
-        $sql.= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3140
-        $sql.= ")";
3141
-        $sql.= " VALUES (".$this->fk_commande.", '" . $this->db->escape($this->label) . "','" . $this->db->escape($this->desc) . "',";
3142
-        $sql.= " ".($this->date_start?"'".$this->db->idate($this->date_start)."'":"null").",";
3143
-        $sql.= " ".($this->date_end?"'".$this->db->idate($this->date_end)."'":"null").",";
3144
-        if ($this->fk_product) { $sql.= $this->fk_product.","; }
3145
-        else { $sql.= "null,"; }
3146
-        $sql.= "'".$this->db->escape($this->product_type)."',";
3147
-        $sql.= "'".$this->db->escape($this->qty)."', ";
3148
-
3149
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3150
-        $sql.= " ".$this->tva_tx.", ";
3151
-        $sql.= " ".$this->localtax1_tx.",";
3152
-        $sql.= " ".$this->localtax2_tx.",";
3153
-        $sql.= " '".$this->db->escape($this->localtax1_type)."',";
3154
-        $sql.= " '".$this->db->escape($this->localtax2_type)."',";
3155
-        $sql.= " ".$this->remise_percent.", ".price2num($this->subprice,'MU').", '".$this->db->escape($this->ref_supplier)."',";
3156
-        $sql.= " ".price2num($this->total_ht).",";
3157
-        $sql.= " ".price2num($this->total_tva).",";
3158
-        $sql.= " ".price2num($this->total_localtax1).",";
3159
-        $sql.= " ".price2num($this->total_localtax2).",";
3160
-        $sql.= " ".price2num($this->total_ttc).",";
3161
-        $sql.= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'":"null");
3162
-        $sql.= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null");
3163
-        $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3164
-        $sql.= ", ".price2num($this->multicurrency_subprice);
3165
-        $sql.= ", ".price2num($this->multicurrency_total_ht);
3166
-        $sql.= ", ".price2num($this->multicurrency_total_tva);
3167
-        $sql.= ", ".price2num($this->multicurrency_total_ttc);
3168
-        $sql.= ")";
3169
-
3170
-        dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3171
-        $resql=$this->db->query($sql);
3172
-        if ($resql)
3173
-        {
3174
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3175
-            $this->rowid =$this->id;
3176
-
3177
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3178
-            {
3179
-
3180
-                $result=$this->insertExtraFields();
3181
-                if ($result < 0)
3182
-                {
3183
-                    $error++;
3184
-                }
3185
-            }
3186
-
3187
-            if (! $error && ! $notrigger)
3188
-            {
3189
-                // Call trigger
3190
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user);
3191
-                if ($result < 0) $error++;
3192
-                // End call triggers
3193
-            }
3194
-
3195
-            if (!$error) {
3196
-                $this->db->commit();
3197
-                return 1;
3198
-            }
3199
-
3200
-            foreach($this->errors as $errmsg)
3201
-            {
3202
-                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3203
-                $this->errors[]=($this->errors?', '.$errmsg:$errmsg);
3204
-            }
3205
-            $this->db->rollback();
3206
-            return -1*$error;
3207
-        }
3208
-        else
3209
-        {
3210
-            $this->errors[]=$this->db->error();
3211
-            $this->db->rollback();
3212
-            return -2;
3213
-        }
3214
-    }
3215
-    /**
3216
-     *	Update the line object into db
3217
-     *
3218
-     *	@param      int		$notrigger		1 = disable triggers
3219
-     *	@return		int		<0 si ko, >0 si ok
3220
-     */
3221
-    public function update($notrigger=0)
3222
-    {
3223
-        global $conf,$user;
3224
-
3225
-        $error=0;
3226
-
3227
-        // Mise a jour ligne en base
3228
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3229
-        $sql.= "  description='".$this->db->escape($this->desc)."'";
3230
-        $sql.= ", subprice='".price2num($this->subprice)."'";
3231
-        //$sql.= ",remise='".price2num($remise)."'";
3232
-        $sql.= ", remise_percent='".price2num($this->remise_percent)."'";
3045
+			$this->db->free($result);
3046
+			return 1;
3047
+		}
3048
+		else
3049
+		{
3050
+			dol_print_error($this->db);
3051
+			return -1;
3052
+		}
3053
+	}
3054
+
3055
+	/**
3056
+	 *  Mise a jour de l'objet ligne de commande en base
3057
+	 *
3058
+	 *  @return		int		<0 si ko, >0 si ok
3059
+	 */
3060
+	public function updateTotal()
3061
+	{
3062
+		$this->db->begin();
3063
+
3064
+		// Mise a jour ligne en base
3065
+		$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseurdet SET";
3066
+		$sql.= " total_ht='".price2num($this->total_ht)."'";
3067
+		$sql.= ",total_tva='".price2num($this->total_tva)."'";
3068
+		$sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
3069
+		$sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
3070
+		$sql.= ",total_ttc='".price2num($this->total_ttc)."'";
3071
+		$sql.= " WHERE rowid = ".$this->rowid;
3072
+
3073
+		dol_syslog(get_class($this)."::updateTotal", LOG_DEBUG);
3074
+
3075
+		$resql=$this->db->query($sql);
3076
+		if ($resql)
3077
+		{
3078
+			$this->db->commit();
3079
+			return 1;
3080
+		}
3081
+		else
3082
+		{
3083
+			$this->error=$this->db->error();
3084
+			$this->db->rollback();
3085
+			return -2;
3086
+		}
3087
+	}
3088
+
3089
+	/**
3090
+	 *	Insert line into database
3091
+	 *
3092
+	 *	@param      int		$notrigger		1 = disable triggers
3093
+	 *	@return		int						<0 if KO, >0 if OK
3094
+	 */
3095
+	public function insert($notrigger=0)
3096
+	{
3097
+		global $conf, $user;
3098
+
3099
+		$error=0;
3100
+
3101
+		dol_syslog(get_class($this)."::insert rang=".$this->rang);
3102
+
3103
+		// Clean parameters
3104
+		if (empty($this->tva_tx)) $this->tva_tx=0;
3105
+		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3106
+		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3107
+		if (empty($this->localtax1_type)) $this->localtax1_type='0';
3108
+		if (empty($this->localtax2_type)) $this->localtax2_type='0';
3109
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
3110
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
3111
+		if (empty($this->rang)) $this->rang=0;
3112
+		if (empty($this->remise)) $this->remise=0;
3113
+		if (empty($this->remise_percent)) $this->remise_percent=0;
3114
+		if (empty($this->info_bits)) $this->info_bits=0;
3115
+		if (empty($this->special_code)) $this->special_code=0;
3116
+		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3117
+		if (empty($this->pa_ht)) $this->pa_ht=0;
3118
+
3119
+		// Multicurrency
3120
+		if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3121
+		if (empty($this->fk_multicurrency))
3122
+		{
3123
+			$this->multicurrency_code = $conf->currency;
3124
+			$this->fk_multicurrency = 0;
3125
+			$this->multicurrency_tx = 1;
3126
+		}
3127
+
3128
+		// Check parameters
3129
+		if ($this->product_type < 0) return -1;
3130
+
3131
+		$this->db->begin();
3132
+
3133
+		// Insertion dans base de la ligne
3134
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
3135
+		$sql.= " (fk_commande, label, description, date_start, date_end,";
3136
+		$sql.= " fk_product, product_type,";
3137
+		$sql.= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3138
+		$sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3139
+		$sql.= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3140
+		$sql.= ")";
3141
+		$sql.= " VALUES (".$this->fk_commande.", '" . $this->db->escape($this->label) . "','" . $this->db->escape($this->desc) . "',";
3142
+		$sql.= " ".($this->date_start?"'".$this->db->idate($this->date_start)."'":"null").",";
3143
+		$sql.= " ".($this->date_end?"'".$this->db->idate($this->date_end)."'":"null").",";
3144
+		if ($this->fk_product) { $sql.= $this->fk_product.","; }
3145
+		else { $sql.= "null,"; }
3146
+		$sql.= "'".$this->db->escape($this->product_type)."',";
3147
+		$sql.= "'".$this->db->escape($this->qty)."', ";
3148
+
3149
+		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3150
+		$sql.= " ".$this->tva_tx.", ";
3151
+		$sql.= " ".$this->localtax1_tx.",";
3152
+		$sql.= " ".$this->localtax2_tx.",";
3153
+		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
3154
+		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
3155
+		$sql.= " ".$this->remise_percent.", ".price2num($this->subprice,'MU').", '".$this->db->escape($this->ref_supplier)."',";
3156
+		$sql.= " ".price2num($this->total_ht).",";
3157
+		$sql.= " ".price2num($this->total_tva).",";
3158
+		$sql.= " ".price2num($this->total_localtax1).",";
3159
+		$sql.= " ".price2num($this->total_localtax2).",";
3160
+		$sql.= " ".price2num($this->total_ttc).",";
3161
+		$sql.= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'":"null");
3162
+		$sql.= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null");
3163
+		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3164
+		$sql.= ", ".price2num($this->multicurrency_subprice);
3165
+		$sql.= ", ".price2num($this->multicurrency_total_ht);
3166
+		$sql.= ", ".price2num($this->multicurrency_total_tva);
3167
+		$sql.= ", ".price2num($this->multicurrency_total_ttc);
3168
+		$sql.= ")";
3169
+
3170
+		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3171
+		$resql=$this->db->query($sql);
3172
+		if ($resql)
3173
+		{
3174
+			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3175
+			$this->rowid =$this->id;
3176
+
3177
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3178
+			{
3179
+
3180
+				$result=$this->insertExtraFields();
3181
+				if ($result < 0)
3182
+				{
3183
+					$error++;
3184
+				}
3185
+			}
3186
+
3187
+			if (! $error && ! $notrigger)
3188
+			{
3189
+				// Call trigger
3190
+				$result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user);
3191
+				if ($result < 0) $error++;
3192
+				// End call triggers
3193
+			}
3194
+
3195
+			if (!$error) {
3196
+				$this->db->commit();
3197
+				return 1;
3198
+			}
3199
+
3200
+			foreach($this->errors as $errmsg)
3201
+			{
3202
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3203
+				$this->errors[]=($this->errors?', '.$errmsg:$errmsg);
3204
+			}
3205
+			$this->db->rollback();
3206
+			return -1*$error;
3207
+		}
3208
+		else
3209
+		{
3210
+			$this->errors[]=$this->db->error();
3211
+			$this->db->rollback();
3212
+			return -2;
3213
+		}
3214
+	}
3215
+	/**
3216
+	 *	Update the line object into db
3217
+	 *
3218
+	 *	@param      int		$notrigger		1 = disable triggers
3219
+	 *	@return		int		<0 si ko, >0 si ok
3220
+	 */
3221
+	public function update($notrigger=0)
3222
+	{
3223
+		global $conf,$user;
3224
+
3225
+		$error=0;
3226
+
3227
+		// Mise a jour ligne en base
3228
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3229
+		$sql.= "  description='".$this->db->escape($this->desc)."'";
3230
+		$sql.= ", subprice='".price2num($this->subprice)."'";
3231
+		//$sql.= ",remise='".price2num($remise)."'";
3232
+		$sql.= ", remise_percent='".price2num($this->remise_percent)."'";
3233 3233
 
3234 3234
 		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
3235
-        $sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3236
-        $sql.= ", localtax1_tx='".price2num($this->total_localtax1)."'";
3237
-        $sql.= ", localtax2_tx='".price2num($this->total_localtax2)."'";
3238
-        $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3239
-        $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3240
-        $sql.= ", qty='".price2num($this->qty)."'";
3241
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3242
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3243
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3244
-        $sql.= ", total_ht='".price2num($this->total_ht)."'";
3245
-        $sql.= ", total_tva='".price2num($this->total_tva)."'";
3246
-        $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
3247
-        $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
3248
-        $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
3249
-        $sql.= ", product_type=".$this->product_type;
3250
-        $sql.= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'":", fk_unit=null");
3251
-
3252
-        // Multicurrency
3253
-        $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3254
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3255
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3256
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3257
-
3258
-        $sql.= " WHERE rowid = ".$this->id;
3259
-
3260
-        dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
3261
-        $result = $this->db->query($sql);
3262
-        if ($result > 0)
3263
-        {
3264
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3265
-            {
3266
-
3267
-                $result=$this->insertExtraFields();
3268
-                if ($result < 0)
3269
-                {
3270
-                    $error++;
3271
-                }
3272
-            }
3273
-
3274
-            if (! $error && ! $notrigger)
3275
-            {
3276
-                global $user;
3277
-                // Call trigger
3278
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE',$user);
3279
-                if ($result < 0)
3280
-                {
3281
-                    $this->db->rollback();
3282
-                    return -1;
3283
-                }
3284
-                // End call triggers
3285
-            }
3286
-
3287
-            if (! $error)
3288
-            {
3289
-                $this->db->commit();
3290
-                return $result;
3291
-            }
3292
-            else
3293
-            {
3294
-                $this->db->rollback();
3295
-                return -1;
3296
-            }
3297
-        }
3298
-        else
3299
-        {
3300
-            $this->error=$this->db->lasterror();
3301
-            $this->db->rollback();
3302
-            return -1;
3303
-        }
3304
-    }
3305
-
3306
-    /**
3307
-     * 	Delete line in database
3308
-     *
3309
-     *	@param      int     $notrigger  1=Disable call to triggers
3310
-     *	@return     int                 <0 if KO, >0 if OK
3311
-     */
3312
-    function delete($notrigger)
3313
-    {
3314
-        global $user;
3315
-
3316
-        $error=0;
3317
-
3318
-        $this->db->begin();
3319
-
3320
-        $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->rowid;
3321
-
3322
-        dol_syslog(__METHOD__, LOG_DEBUG);
3323
-        $resql=$this->db->query($sql);
3324
-        if ($resql)
3325
-        {
3326
-
3327
-            if (!$notrigger)
3328
-            {
3329
-                // Call trigger
3330
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user);
3331
-                if ($result < 0) $error++;
3332
-                // End call triggers
3333
-            }
3334
-
3335
-            if (!$error)
3336
-            {
3337
-                $this->db->commit();
3338
-                return 1;
3339
-            }
3340
-
3341
-            foreach($this->errors as $errmsg)
3342
-            {
3343
-                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3344
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
3345
-            }
3346
-            $this->db->rollback();
3347
-            return -1*$error;
3348
-        }
3349
-        else
3350
-        {
3351
-            $this->error=$this->db->lasterror();
3352
-            return -1;
3353
-        }
3354
-    }
3235
+		$sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3236
+		$sql.= ", localtax1_tx='".price2num($this->total_localtax1)."'";
3237
+		$sql.= ", localtax2_tx='".price2num($this->total_localtax2)."'";
3238
+		$sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3239
+		$sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3240
+		$sql.= ", qty='".price2num($this->qty)."'";
3241
+		$sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3242
+		$sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3243
+		$sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3244
+		$sql.= ", total_ht='".price2num($this->total_ht)."'";
3245
+		$sql.= ", total_tva='".price2num($this->total_tva)."'";
3246
+		$sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
3247
+		$sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
3248
+		$sql.= ", total_ttc='".price2num($this->total_ttc)."'";
3249
+		$sql.= ", product_type=".$this->product_type;
3250
+		$sql.= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'":", fk_unit=null");
3251
+
3252
+		// Multicurrency
3253
+		$sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3254
+		$sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3255
+		$sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3256
+		$sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3257
+
3258
+		$sql.= " WHERE rowid = ".$this->id;
3259
+
3260
+		dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
3261
+		$result = $this->db->query($sql);
3262
+		if ($result > 0)
3263
+		{
3264
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3265
+			{
3266
+
3267
+				$result=$this->insertExtraFields();
3268
+				if ($result < 0)
3269
+				{
3270
+					$error++;
3271
+				}
3272
+			}
3273
+
3274
+			if (! $error && ! $notrigger)
3275
+			{
3276
+				global $user;
3277
+				// Call trigger
3278
+				$result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE',$user);
3279
+				if ($result < 0)
3280
+				{
3281
+					$this->db->rollback();
3282
+					return -1;
3283
+				}
3284
+				// End call triggers
3285
+			}
3286
+
3287
+			if (! $error)
3288
+			{
3289
+				$this->db->commit();
3290
+				return $result;
3291
+			}
3292
+			else
3293
+			{
3294
+				$this->db->rollback();
3295
+				return -1;
3296
+			}
3297
+		}
3298
+		else
3299
+		{
3300
+			$this->error=$this->db->lasterror();
3301
+			$this->db->rollback();
3302
+			return -1;
3303
+		}
3304
+	}
3305
+
3306
+	/**
3307
+	 * 	Delete line in database
3308
+	 *
3309
+	 *	@param      int     $notrigger  1=Disable call to triggers
3310
+	 *	@return     int                 <0 if KO, >0 if OK
3311
+	 */
3312
+	function delete($notrigger)
3313
+	{
3314
+		global $user;
3315
+
3316
+		$error=0;
3317
+
3318
+		$this->db->begin();
3319
+
3320
+		$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->rowid;
3321
+
3322
+		dol_syslog(__METHOD__, LOG_DEBUG);
3323
+		$resql=$this->db->query($sql);
3324
+		if ($resql)
3325
+		{
3326
+
3327
+			if (!$notrigger)
3328
+			{
3329
+				// Call trigger
3330
+				$result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user);
3331
+				if ($result < 0) $error++;
3332
+				// End call triggers
3333
+			}
3334
+
3335
+			if (!$error)
3336
+			{
3337
+				$this->db->commit();
3338
+				return 1;
3339
+			}
3340
+
3341
+			foreach($this->errors as $errmsg)
3342
+			{
3343
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3344
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
3345
+			}
3346
+			$this->db->rollback();
3347
+			return -1*$error;
3348
+		}
3349
+		else
3350
+		{
3351
+			$this->error=$this->db->lasterror();
3352
+			return -1;
3353
+		}
3354
+	}
3355 3355
 }
3356 3356
 
Please login to merge, or discard this patch.
Spacing   +778 added lines, -778 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 
32 32
 include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
33 33
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
34
-if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
34
+if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
35 35
 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
36 36
 
37 37
 /**
@@ -39,12 +39,12 @@  discard block
 block discarded – undo
39 39
  */
40 40
 class CommandeFournisseur extends CommonOrder
41 41
 {
42
-    public $element='order_supplier';
43
-    public $table_element='commande_fournisseur';
42
+    public $element = 'order_supplier';
43
+    public $table_element = 'commande_fournisseur';
44 44
     public $table_element_line = 'commande_fournisseurdet';
45 45
     public $fk_element = 'fk_commande';
46
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
-    public $picto='order';
46
+    protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
+    public $picto = 'order';
48 48
 
49 49
     /**
50 50
      * {@inheritdoc}
@@ -60,19 +60,19 @@  discard block
 block discarded – undo
60 60
     public $ref;
61 61
     public $ref_supplier;
62 62
     public $brouillon;
63
-    public $statut;			// 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
63
+    public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
64 64
     //                                                              -> 7=Canceled/Never received -> (reopen) 3=Process runing
65 65
     //									              -> 6=Canceled -> (reopen) 2=Approved
66 66
     //  		                                      -> 9=Refused  -> (reopen) 1=Validated
67 67
     //  Note: billed or not is on another field "billed"
68
-    public $statuts;           // List of status
68
+    public $statuts; // List of status
69 69
 
70 70
     public $socid;
71 71
     public $fourn_id;
72 72
     public $date;
73 73
     public $date_valid;
74 74
     public $date_approve;
75
-    public $date_approve2;		// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
75
+    public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
76 76
     public $date_commande;
77 77
 
78 78
     /**
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
     public $date_livraison;
82 82
     public $total_ht;
83 83
     public $total_tva;
84
-    public $total_localtax1;   // Total Local tax 1
85
-    public $total_localtax2;   // Total Local tax 2
84
+    public $total_localtax1; // Total Local tax 1
85
+    public $total_localtax2; // Total Local tax 2
86 86
     public $total_ttc;
87 87
     public $source;
88 88
 	/**
@@ -102,14 +102,14 @@  discard block
 block discarded – undo
102 102
     public $user_author_id;
103 103
     public $user_valid_id;
104 104
     public $user_approve_id;
105
-    public $user_approve_id2;	// Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
105
+    public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
106 106
 
107 107
 	//Incoterms
108 108
     public $fk_incoterms;
109 109
     public $location_incoterms;
110
-    public $libelle_incoterms;  //Used into tooltip
110
+    public $libelle_incoterms; //Used into tooltip
111 111
 
112
-    public $extraparams=array();
112
+    public $extraparams = array();
113 113
 
114 114
 	/**
115 115
 	 * @var CommandeFournisseurLigne[]
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 	//Add for supplier_proposal
119 119
     public $origin;
120 120
     public $origin_id;
121
-    public $linked_objects=array();
121
+    public $linked_objects = array();
122 122
 
123 123
 	// Multicurrency
124 124
     public $fk_multicurrency;
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
         else $this->statuts[3] = 'StatusOrderOnProcessWithValidation';
156 156
         $this->statuts[4] = 'StatusOrderReceivedPartially';
157 157
         $this->statuts[5] = 'StatusOrderReceivedAll';
158
-        $this->statuts[6] = 'StatusOrderCanceled';	// Approved->Canceled
159
-        $this->statuts[7] = 'StatusOrderCanceled';	// Process running->canceled
158
+        $this->statuts[6] = 'StatusOrderCanceled'; // Approved->Canceled
159
+        $this->statuts[7] = 'StatusOrderCanceled'; // Process running->canceled
160 160
         //$this->statuts[8] = 'StatusOrderBilled';	// Everything is finished, order received totally and bill received
161 161
         $this->statuts[9] = 'StatusOrderRefused';
162 162
     }
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
      * 	@param	string	$ref		Ref of object
170 170
      *	@return int 		        >0 if OK, <0 if KO, 0 if not found
171 171
      */
172
-    public function fetch($id,$ref='')
172
+    public function fetch($id, $ref = '')
173 173
     {
174 174
         global $conf;
175 175
 
@@ -177,79 +177,79 @@  discard block
 block discarded – undo
177 177
         if (empty($id) && empty($ref)) return -1;
178 178
 
179 179
         $sql = "SELECT c.rowid, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,";
180
-        $sql.= " c.localtax1, c.localtax2, ";
181
-        $sql.= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
182
-        $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
183
-        $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
184
-        $sql.= " c.fk_account,";
185
-        $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
186
-		$sql.= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
187
-        $sql.= " cm.libelle as methode_commande,";
188
-        $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
189
-        $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
190
-        $sql.= ', c.fk_incoterms, c.location_incoterms';
191
-        $sql.= ', i.libelle as libelle_incoterms';
192
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
193
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
194
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
195
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
196
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
197
-        $sql.= " WHERE c.entity = ".$conf->entity;
198
-        if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
199
-        else $sql.= " AND c.rowid=".$id;
180
+        $sql .= " c.localtax1, c.localtax2, ";
181
+        $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
182
+        $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
183
+        $sql .= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
184
+        $sql .= " c.fk_account,";
185
+        $sql .= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
186
+		$sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
187
+        $sql .= " cm.libelle as methode_commande,";
188
+        $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
189
+        $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
190
+        $sql .= ', c.fk_incoterms, c.location_incoterms';
191
+        $sql .= ', i.libelle as libelle_incoterms';
192
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
193
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid AND cr.entity = ".getEntity('c_payment_term').")";
194
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id AND p.entity = ".getEntity('c_paiement').")";
195
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
196
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
197
+        $sql .= " WHERE c.entity = ".$conf->entity;
198
+        if ($ref) $sql .= " AND c.ref='".$this->db->escape($ref)."'";
199
+        else $sql .= " AND c.rowid=".$id;
200 200
 
201 201
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
202 202
         $resql = $this->db->query($sql);
203 203
         if ($resql)
204 204
         {
205 205
             $obj = $this->db->fetch_object($resql);
206
-            if (! $obj)
206
+            if (!$obj)
207 207
             {
208
-                $this->error='Bill with id '.$id.' not found';
208
+                $this->error = 'Bill with id '.$id.' not found';
209 209
                 dol_syslog(get_class($this).'::fetch '.$this->error);
210 210
                 return 0;
211 211
             }
212 212
 
213
-            $this->id					= $obj->rowid;
214
-            $this->ref					= $obj->ref;
215
-            $this->ref_supplier			= $obj->ref_supplier;
216
-            $this->socid				= $obj->fk_soc;
217
-            $this->fourn_id				= $obj->fk_soc;
213
+            $this->id = $obj->rowid;
214
+            $this->ref = $obj->ref;
215
+            $this->ref_supplier = $obj->ref_supplier;
216
+            $this->socid = $obj->fk_soc;
217
+            $this->fourn_id = $obj->fk_soc;
218 218
             $this->statut				= $obj->fk_statut;
219 219
             $this->billed				= $obj->billed;
220
-            $this->user_author_id		= $obj->fk_user_author;
221
-            $this->user_valid_id		= $obj->fk_user_valid;
222
-            $this->user_approve_id		= $obj->fk_user_approve;
223
-            $this->user_approve_id2		= $obj->fk_user_approve2;
220
+            $this->user_author_id = $obj->fk_user_author;
221
+            $this->user_valid_id = $obj->fk_user_valid;
222
+            $this->user_approve_id = $obj->fk_user_approve;
223
+            $this->user_approve_id2 = $obj->fk_user_approve2;
224 224
             $this->total_ht				= $obj->total_ht;
225 225
             $this->total_tva			= $obj->total_vat;
226 226
             $this->total_localtax1		= $obj->localtax1;
227 227
             $this->total_localtax2		= $obj->localtax2;
228 228
             $this->total_ttc			= $obj->total_ttc;
229
-            $this->date					= $this->db->jdate($obj->date_creation);
230
-            $this->date_valid			= $this->db->jdate($obj->date_valid);
229
+            $this->date = $this->db->jdate($obj->date_creation);
230
+            $this->date_valid = $this->db->jdate($obj->date_valid);
231 231
             $this->date_approve			= $this->db->jdate($obj->date_approve);
232 232
             $this->date_approve2		= $this->db->jdate($obj->date_approve2);
233 233
             $this->date_commande		= $this->db->jdate($obj->date_commande); // date we make the order to supplier
234
-			$this->date_livraison       = $this->db->jdate($obj->date_livraison);
235
-            $this->remise_percent		= $obj->remise_percent;
236
-            $this->methode_commande_id	= $obj->fk_input_method;
237
-            $this->methode_commande		= $obj->methode_commande;
238
-
239
-            $this->source				= $obj->source;
240
-            $this->fk_project			= $obj->fk_project;
241
-            $this->cond_reglement_id	= $obj->fk_cond_reglement;
242
-            $this->cond_reglement_code	= $obj->cond_reglement_code;
243
-            $this->cond_reglement		= $obj->cond_reglement_libelle;
244
-            $this->cond_reglement_doc	= $obj->cond_reglement_libelle;
245
-            $this->fk_account           = $obj->fk_account;
246
-            $this->mode_reglement_id	= $obj->fk_mode_reglement;
247
-            $this->mode_reglement_code	= $obj->mode_reglement_code;
248
-            $this->mode_reglement		= $obj->mode_reglement_libelle;
249
-            $this->note					= $obj->note_private;    // deprecated
250
-            $this->note_private			= $obj->note_private;
251
-            $this->note_public			= $obj->note_public;
252
-            $this->modelpdf				= $obj->model_pdf;
234
+			$this->date_livraison = $this->db->jdate($obj->date_livraison);
235
+            $this->remise_percent = $obj->remise_percent;
236
+            $this->methode_commande_id = $obj->fk_input_method;
237
+            $this->methode_commande = $obj->methode_commande;
238
+
239
+            $this->source = $obj->source;
240
+            $this->fk_project = $obj->fk_project;
241
+            $this->cond_reglement_id = $obj->fk_cond_reglement;
242
+            $this->cond_reglement_code = $obj->cond_reglement_code;
243
+            $this->cond_reglement = $obj->cond_reglement_libelle;
244
+            $this->cond_reglement_doc = $obj->cond_reglement_libelle;
245
+            $this->fk_account = $obj->fk_account;
246
+            $this->mode_reglement_id = $obj->fk_mode_reglement;
247
+            $this->mode_reglement_code = $obj->mode_reglement_code;
248
+            $this->mode_reglement = $obj->mode_reglement_libelle;
249
+            $this->note = $obj->note_private; // deprecated
250
+            $this->note_private = $obj->note_private;
251
+            $this->note_public = $obj->note_public;
252
+            $this->modelpdf = $obj->model_pdf;
253 253
 
254 254
 			//Incoterms
255 255
 			$this->fk_incoterms = $obj->fk_incoterms;
@@ -258,42 +258,42 @@  discard block
 block discarded – undo
258 258
 
259 259
 			// Multicurrency
260 260
 			$this->fk_multicurrency 		= $obj->fk_multicurrency;
261
-			$this->multicurrency_code 		= $obj->multicurrency_code;
261
+			$this->multicurrency_code = $obj->multicurrency_code;
262 262
 			$this->multicurrency_tx 		= $obj->multicurrency_tx;
263
-			$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
263
+			$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
264 264
 			$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
265 265
 			$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
266 266
 
267
-            $this->extraparams			= (array) json_decode($obj->extraparams, true);
267
+            $this->extraparams = (array) json_decode($obj->extraparams, true);
268 268
 
269 269
             $this->db->free($resql);
270 270
 
271 271
             // Retrieve all extrafields
272 272
             // fetch optionals attributes and labels
273 273
             require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
274
-            $extrafields=new ExtraFields($this->db);
275
-            $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
276
-            $this->fetch_optionals($this->id,$extralabels);
274
+            $extrafields = new ExtraFields($this->db);
275
+            $extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true);
276
+            $this->fetch_optionals($this->id, $extralabels);
277 277
 
278 278
             if ($this->statut == 0) $this->brouillon = 1;
279 279
 
280 280
 			$this->fetchObjectLinked();
281 281
 
282 282
 			//$result=$this->fetch_lines();
283
-            $this->lines=array();
283
+            $this->lines = array();
284 284
 
285 285
             $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
286
-            $sql.= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
287
-            $sql.= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
288
-            $sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
289
-            $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,";
290
-	        $sql.= " l.fk_unit,";
291
-            $sql.= " l.date_start, l.date_end,";
292
-			$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
293
-            $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet	as l";
294
-            $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
295
-            $sql.= " WHERE l.fk_commande = ".$this->id;
296
-            $sql.= " ORDER BY l.rang, l.rowid";
286
+            $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
287
+            $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
288
+            $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
289
+            $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,";
290
+	        $sql .= " l.fk_unit,";
291
+            $sql .= " l.date_start, l.date_end,";
292
+			$sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
293
+            $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet	as l";
294
+            $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
295
+            $sql .= " WHERE l.fk_commande = ".$this->id;
296
+            $sql .= " ORDER BY l.rang, l.rowid";
297 297
             //print $sql;
298 298
 
299 299
             dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG);
@@ -305,9 +305,9 @@  discard block
 block discarded – undo
305 305
 
306 306
                 while ($i < $num)
307 307
                 {
308
-                    $objp                  = $this->db->fetch_object($result);
308
+                    $objp = $this->db->fetch_object($result);
309 309
 
310
-                    $line                 = new CommandeFournisseurLigne($this->db);
310
+                    $line = new CommandeFournisseurLigne($this->db);
311 311
 
312 312
                     $line->id                  = $objp->rowid;
313 313
                     $line->desc                = $objp->description;
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
                     $line->localtax1_type	   = $objp->localtax1_type;
320 320
                     $line->localtax2_type	   = $objp->localtax2_type;
321 321
                     $line->subprice            = $objp->subprice;
322
-                    $line->pu_ht	           = $objp->subprice;
322
+                    $line->pu_ht = $objp->subprice;
323 323
                     $line->remise_percent      = $objp->remise_percent;
324 324
 
325 325
                     $line->vat_src_code        = $objp->vat_src_code;
@@ -336,18 +336,18 @@  discard block
 block discarded – undo
336 336
                     $line->product_label       = $objp->product_label;
337 337
                     $line->product_desc        = $objp->product_desc;
338 338
 
339
-                    $line->ref                 = $objp->product_ref;    // Ref of product
340
-                    $line->product_ref         = $objp->product_ref;    // Ref of product
341
-                    $line->ref_fourn           = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
342
-                    $line->ref_supplier        = $objp->ref_supplier;   // The supplier ref of price when product was added. May have change since
339
+                    $line->ref                 = $objp->product_ref; // Ref of product
340
+                    $line->product_ref         = $objp->product_ref; // Ref of product
341
+                    $line->ref_fourn           = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
342
+                    $line->ref_supplier        = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
343 343
 
344 344
                     $line->date_start          = $this->db->jdate($objp->date_start);
345 345
                     $line->date_end            = $this->db->jdate($objp->date_end);
346
-	                $line->fk_unit             = $objp->fk_unit;
346
+	                $line->fk_unit = $objp->fk_unit;
347 347
 
348 348
 					// Multicurrency
349
-					$line->fk_multicurrency 		= $objp->fk_multicurrency;
350
-					$line->multicurrency_code 		= $objp->multicurrency_code;
349
+					$line->fk_multicurrency = $objp->fk_multicurrency;
350
+					$line->multicurrency_code = $objp->multicurrency_code;
351 351
 					$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
352 352
 					$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
353 353
 					$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
@@ -356,9 +356,9 @@  discard block
 block discarded – undo
356 356
 	                $line->special_code        = $objp->special_code;
357 357
 	                $line->fk_parent_line      = $objp->fk_parent_line;
358 358
 
359
-                    $line->rang                = $objp->rang;
359
+                    $line->rang = $objp->rang;
360 360
 
361
-                    $this->lines[$i]      = $line;
361
+                    $this->lines[$i] = $line;
362 362
 
363 363
                     $i++;
364 364
                 }
@@ -368,13 +368,13 @@  discard block
 block discarded – undo
368 368
             }
369 369
             else
370 370
             {
371
-                $this->error=$this->db->error()." sql=".$sql;
371
+                $this->error = $this->db->error()." sql=".$sql;
372 372
                 return -1;
373 373
             }
374 374
         }
375 375
         else
376 376
         {
377
-            $this->error=$this->db->error()." sql=".$sql;
377
+            $this->error = $this->db->error()." sql=".$sql;
378 378
             return -1;
379 379
         }
380 380
     }
@@ -387,17 +387,17 @@  discard block
 block discarded – undo
387 387
      *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
388 388
      *	@return	int						<0 if KO, >0 if OK
389 389
      */
390
-    public function valid($user,$idwarehouse=0,$notrigger=0)
390
+    public function valid($user, $idwarehouse = 0, $notrigger = 0)
391 391
     {
392
-        global $langs,$conf;
392
+        global $langs, $conf;
393 393
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
394 394
 
395
-        $error=0;
395
+        $error = 0;
396 396
 
397 397
         dol_syslog(get_class($this)."::valid");
398 398
         $result = 0;
399
-        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
400
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
399
+        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->commande->creer))
400
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate)))
401 401
         {
402 402
             $this->db->begin();
403 403
 
@@ -417,29 +417,29 @@  discard block
 block discarded – undo
417 417
             $this->newref = $num;
418 418
 
419 419
             $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
420
-            $sql.= " SET ref='".$this->db->escape($num)."',";
421
-            $sql.= " fk_statut = 1,";
422
-            $sql.= " date_valid='".$this->db->idate(dol_now())."',";
423
-            $sql.= " fk_user_valid = ".$user->id;
424
-            $sql.= " WHERE rowid = ".$this->id;
425
-            $sql.= " AND fk_statut = 0";
420
+            $sql .= " SET ref='".$this->db->escape($num)."',";
421
+            $sql .= " fk_statut = 1,";
422
+            $sql .= " date_valid='".$this->db->idate(dol_now())."',";
423
+            $sql .= " fk_user_valid = ".$user->id;
424
+            $sql .= " WHERE rowid = ".$this->id;
425
+            $sql .= " AND fk_statut = 0";
426 426
 
427
-            $resql=$this->db->query($sql);
428
-            if (! $resql)
427
+            $resql = $this->db->query($sql);
428
+            if (!$resql)
429 429
             {
430 430
                 dol_print_error($this->db);
431 431
                 $error++;
432 432
             }
433 433
 
434
-            if (! $error && ! $notrigger)
434
+            if (!$error && !$notrigger)
435 435
             {
436 436
 				// Call trigger
437
-				$result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE',$user);
437
+				$result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
438 438
 				if ($result < 0) $error++;
439 439
 				// End call triggers
440 440
             }
441 441
 
442
-            if (! $error)
442
+            if (!$error)
443 443
             {
444 444
 	            $this->oldref = $this->ref;
445 445
 
@@ -460,13 +460,13 @@  discard block
 block discarded – undo
460 460
                         {
461 461
                             dol_syslog("Rename ok");
462 462
                             // Rename docs starting with $oldref with $newref
463
-	                        $listoffiles=dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
464
-	                        foreach($listoffiles as $fileentry)
463
+	                        $listoffiles = dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
464
+	                        foreach ($listoffiles as $fileentry)
465 465
 	                        {
466
-	                        	$dirsource=$fileentry['name'];
467
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
468
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
469
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
466
+	                        	$dirsource = $fileentry['name'];
467
+	                        	$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
468
+	                        	$dirsource = $fileentry['path'].'/'.$dirsource;
469
+	                        	$dirdest = $fileentry['path'].'/'.$dirdest;
470 470
 	                        	@rename($dirsource, $dirdest);
471 471
 	                        }
472 472
                         }
@@ -474,14 +474,14 @@  discard block
 block discarded – undo
474 474
                 }
475 475
             }
476 476
 
477
-            if (! $error)
477
+            if (!$error)
478 478
             {
479 479
                 $result = 1;
480 480
                 $this->statut = 1;
481 481
                 $this->ref = $num;
482 482
             }
483 483
 
484
-            if (! $error)
484
+            if (!$error)
485 485
             {
486 486
                 $this->db->commit();
487 487
                 return 1;
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
         }
495 495
         else
496 496
         {
497
-            $this->error='NotAuthorized';
497
+            $this->error = 'NotAuthorized';
498 498
             dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
499 499
             return -1;
500 500
         }
@@ -506,9 +506,9 @@  discard block
 block discarded – undo
506 506
 	 *  @param      int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto
507 507
      *  @return 	string        			Label
508 508
      */
509
-    public function getLibStatut($mode=0)
509
+    public function getLibStatut($mode = 0)
510 510
     {
511
-        return $this->LibStatut($this->statut,$mode,$this->billed);
511
+        return $this->LibStatut($this->statut, $mode, $this->billed);
512 512
     }
513 513
 
514 514
     /**
@@ -519,14 +519,14 @@  discard block
 block discarded – undo
519 519
      *  @param  int     $billed     1=Billed
520 520
      *  @return string				Label of status
521 521
      */
522
-    function LibStatut($statut,$mode=0,$billed=0)
522
+    function LibStatut($statut, $mode = 0, $billed = 0)
523 523
     {
524 524
         global $langs;
525 525
         $langs->load('orders');
526 526
 
527
-        $billedtext='';
527
+        $billedtext = '';
528 528
 		//if ($statut==5 && $this->billed == 1) $statut = 8;
529
-        if ($billed == 1) $billedtext=$langs->trans("Billed");
529
+        if ($billed == 1) $billedtext = $langs->trans("Billed");
530 530
 
531 531
         // List of language codes for status
532 532
         $statutshort[0] = 'StatusOrderDraftShort';
@@ -554,39 +554,39 @@  discard block
 block discarded – undo
554 554
         }
555 555
         if ($mode == 3)
556 556
         {
557
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
558
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1');
559
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
560
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
561
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
562
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
563
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
564
-			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
565
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
557
+            if ($statut == 0) return img_picto($langs->trans($this->statuts[$statut]), 'statut0');
558
+            if ($statut == 1) return img_picto($langs->trans($this->statuts[$statut]), 'statut1');
559
+            if ($statut == 2) return img_picto($langs->trans($this->statuts[$statut]), 'statut3');
560
+            if ($statut == 3) return img_picto($langs->trans($this->statuts[$statut]), 'statut3');
561
+            if ($statut == 4) return img_picto($langs->trans($this->statuts[$statut]), 'statut3');
562
+            if ($statut == 5) return img_picto($langs->trans($this->statuts[$statut]), 'statut6');
563
+            if ($statut == 6 || $statut == 7) return img_picto($langs->trans($this->statuts[$statut]), 'statut5');
564
+			if ($statut == 8) return img_picto($langs->trans($this->statuts[$statut]), 'statut6');
565
+            if ($statut == 9) return img_picto($langs->trans($this->statuts[$statut]), 'statut5');
566 566
         }
567 567
         if ($mode == 4)
568 568
         {
569
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
570
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
571
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
572
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
573
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
574
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
575
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
576
-			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
577
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
569
+            if ($statut == 0) return img_picto($langs->trans($this->statuts[$statut]), 'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
570
+            if ($statut == 1) return img_picto($langs->trans($this->statuts[$statut]), 'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
571
+            if ($statut == 2) return img_picto($langs->trans($this->statuts[$statut]), 'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
572
+            if ($statut == 3) return img_picto($langs->trans($this->statuts[$statut]), 'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
573
+            if ($statut == 4) return img_picto($langs->trans($this->statuts[$statut]), 'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
574
+            if ($statut == 5) return img_picto($langs->trans($this->statuts[$statut]), 'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
575
+            if ($statut == 6 || $statut == 7) return img_picto($langs->trans($this->statuts[$statut]), 'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
576
+			if ($statut == 8) return img_picto($langs->trans($this->statuts[$statut]), 'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
577
+            if ($statut == 9) return img_picto($langs->trans($this->statuts[$statut]), 'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext ? ' - '.$billedtext : '');
578 578
         }
579 579
         if ($mode == 5)
580 580
         {
581
-            if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
582
-            if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
583
-            if ($statut==2) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
584
-            if ($statut==3) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
585
-            if ($statut==4) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
586
-            if ($statut==5) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
587
-            if ($statut==6 || $statut==7) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
588
-            if ($statut==8) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
589
-            if ($statut==9) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
581
+            if ($statut == 0) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut0');
582
+            if ($statut == 1) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut1');
583
+            if ($statut == 2) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut3');
584
+            if ($statut == 3) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut3');
585
+            if ($statut == 4) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut3');
586
+            if ($statut == 5) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut6');
587
+            if ($statut == 6 || $statut == 7) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut5');
588
+            if ($statut == 8) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut6');
589
+            if ($statut == 9) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]), 'statut5');
590 590
         }
591 591
     }
592 592
 
@@ -600,53 +600,53 @@  discard block
 block discarded – undo
600 600
      *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
601 601
      *	@return		string								Chain with URL
602 602
      */
603
-    public function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
603
+    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1)
604 604
     {
605 605
         global $langs, $conf;
606 606
 
607
-        $result='';
608
-        $label = '<u>' . $langs->trans("ShowOrder") . '</u>';
609
-        if (! empty($this->ref))
610
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
611
-        if (! empty($this->ref_supplier))
612
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
613
-        if (! empty($this->total_ht))
614
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
615
-        if (! empty($this->total_tva))
616
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
617
-        if (! empty($this->total_ttc))
618
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
619
-
620
-        $picto='order';
607
+        $result = '';
608
+        $label = '<u>'.$langs->trans("ShowOrder").'</u>';
609
+        if (!empty($this->ref))
610
+            $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
611
+        if (!empty($this->ref_supplier))
612
+            $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
613
+        if (!empty($this->total_ht))
614
+            $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
615
+        if (!empty($this->total_tva))
616
+            $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
617
+        if (!empty($this->total_ttc))
618
+            $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
619
+
620
+        $picto = 'order';
621 621
         $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
622 622
 
623 623
         if ($option !== 'nolink')
624 624
         {
625 625
         	// Add param to save lastsearch_values or not
626
-        	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
627
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
628
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
626
+        	$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
627
+        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
628
+        	if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
629 629
         }
630 630
 
631
-        $linkclose='';
631
+        $linkclose = '';
632 632
         if (empty($notooltip))
633 633
         {
634
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
634
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
635 635
             {
636
-                $label=$langs->trans("ShowOrder");
637
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
636
+                $label = $langs->trans("ShowOrder");
637
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
638 638
             }
639
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
640
-            $linkclose.=' class="classfortooltip"';
639
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
640
+            $linkclose .= ' class="classfortooltip"';
641 641
         }
642 642
 
643 643
         $linkstart = '<a href="'.$url.'"';
644
-        $linkstart.=$linkclose.'>';
645
-        $linkend='</a>';
644
+        $linkstart .= $linkclose.'>';
645
+        $linkend = '</a>';
646 646
 
647
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
648
-        if ($withpicto && $withpicto != 2) $result.=' ';
649
-        $result.=$linkstart.$this->ref.$linkend;
647
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
648
+        if ($withpicto && $withpicto != 2) $result .= ' ';
649
+        $result .= $linkstart.$this->ref.$linkend;
650 650
         return $result;
651 651
     }
652 652
 
@@ -663,12 +663,12 @@  discard block
 block discarded – undo
663 663
         global $db, $langs, $conf;
664 664
         $langs->load("orders");
665 665
 
666
-        if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
666
+        if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
667 667
         {
668 668
             $mybool = false;
669 669
 
670 670
             $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
671
-            $classname=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
671
+            $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
672 672
 
673 673
             // Include file with class
674 674
             $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
@@ -678,19 +678,19 @@  discard block
 block discarded – undo
678 678
                 $dir = dol_buildpath($reldir."core/modules/supplier_order/");
679 679
 
680 680
                 // Load file with numbering class (if found)
681
-                $mybool|=@include_once $dir.$file;
681
+                $mybool |= @include_once $dir.$file;
682 682
             }
683 683
 
684
-            if (! $mybool)
684
+            if (!$mybool)
685 685
             {
686
-                dol_print_error('',"Failed to include file ".$file);
686
+                dol_print_error('', "Failed to include file ".$file);
687 687
                 return '';
688 688
             }
689 689
 
690 690
             $obj = new $classname();
691
-            $numref = $obj->getNextValue($soc,$this);
691
+            $numref = $obj->getNextValue($soc, $this);
692 692
 
693
-            if ( $numref != "")
693
+            if ($numref != "")
694 694
             {
695 695
                 return $numref;
696 696
             }
@@ -714,24 +714,24 @@  discard block
 block discarded – undo
714 714
      */
715 715
     public function classifyBilled(User $user)
716 716
     {
717
-        $error=0;
717
+        $error = 0;
718 718
         $this->db->begin();
719 719
 
720 720
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
721 721
         $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0 ';
722 722
         if ($this->db->query($sql))
723 723
         {
724
-        	if (! $error)
724
+        	if (!$error)
725 725
         	{
726 726
         	    // Call trigger
727
-        	    $result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED',$user);
727
+        	    $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
728 728
         	    if ($result < 0) $error++;
729 729
         	    // End call triggers
730 730
         	}
731 731
 
732
-        	if (! $error)
732
+        	if (!$error)
733 733
         	{
734
-        	    $this->billed=1;
734
+        	    $this->billed = 1;
735 735
 
736 736
         	    $this->db->commit();
737 737
         	    return 1;
@@ -759,12 +759,12 @@  discard block
 block discarded – undo
759 759
      *  @param	int		$secondlevel	0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
760 760
      *	@return	int						<0 if KO, >0 if OK
761 761
      */
762
-    public function approve($user, $idwarehouse=0, $secondlevel=0)
762
+    public function approve($user, $idwarehouse = 0, $secondlevel = 0)
763 763
     {
764
-        global $langs,$conf;
764
+        global $langs, $conf;
765 765
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
766 766
 
767
-        $error=0;
767
+        $error = 0;
768 768
 
769 769
         dol_syslog(get_class($this)."::approve");
770 770
 
@@ -790,42 +790,42 @@  discard block
 block discarded – undo
790 790
             $this->newref = $num;
791 791
 
792 792
             // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
793
-			$movetoapprovestatus=true;
794
-			$comment='';
793
+			$movetoapprovestatus = true;
794
+			$comment = '';
795 795
 
796 796
             $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
797
-			$sql.= " SET ref='".$this->db->escape($num)."',";
797
+			$sql .= " SET ref='".$this->db->escape($num)."',";
798 798
 			if (empty($secondlevel))	// standard or first level approval
799 799
 			{
800
-	            $sql.= " date_approve='".$this->db->idate($now)."',";
801
-    	        $sql.= " fk_user_approve = ".$user->id;
802
-    	        if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
800
+	            $sql .= " date_approve='".$this->db->idate($now)."',";
801
+    	        $sql .= " fk_user_approve = ".$user->id;
802
+    	        if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
803 803
     	        {
804 804
     	        	if (empty($this->user_approve_id2))
805 805
     	        	{
806
-    	        	    $movetoapprovestatus=false;		// second level approval not done
807
-    	        	    $comment=' (first level)';
806
+    	        	    $movetoapprovestatus = false; // second level approval not done
807
+    	        	    $comment = ' (first level)';
808 808
     	        	}
809 809
     	        }
810 810
 			}
811 811
 			else	// request a second level approval
812 812
 			{
813
-            	$sql.= " date_approve2='".$this->db->idate($now)."',";
814
-            	$sql.= " fk_user_approve2 = ".$user->id;
815
-    	        if (empty($this->user_approve_id)) $movetoapprovestatus=false;		// first level approval not done
816
-    	        $comment=' (second level)';
813
+            	$sql .= " date_approve2='".$this->db->idate($now)."',";
814
+            	$sql .= " fk_user_approve2 = ".$user->id;
815
+    	        if (empty($this->user_approve_id)) $movetoapprovestatus = false; // first level approval not done
816
+    	        $comment = ' (second level)';
817 817
 			}
818 818
 			// If double approval is required and first approval, we keep status to 1 = validated
819
-			if ($movetoapprovestatus) $sql.= ", fk_statut = 2";
820
-			else $sql.= ", fk_statut = 1";
821
-            $sql.= " WHERE rowid = ".$this->id;
822
-            $sql.= " AND fk_statut = 1";
819
+			if ($movetoapprovestatus) $sql .= ", fk_statut = 2";
820
+			else $sql .= ", fk_statut = 1";
821
+            $sql .= " WHERE rowid = ".$this->id;
822
+            $sql .= " AND fk_statut = 1";
823 823
 
824 824
             if ($this->db->query($sql))
825 825
             {
826
-            	if (! empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
826
+            	if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
827 827
 	            {
828
-					$result=$this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
828
+					$result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
829 829
 					if ($result < 0 && $result != -2)	// -2 means already exists
830 830
 					{
831 831
 						$error++;
@@ -833,12 +833,12 @@  discard block
 block discarded – undo
833 833
 	            }
834 834
 
835 835
                 // If stock is incremented on validate order, we must increment it
836
-                if (! $error && $movetoapprovestatus && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
836
+                if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
837 837
                 {
838 838
                     require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
839 839
                     $langs->load("agenda");
840 840
 
841
-                    $cpt=count($this->lines);
841
+                    $cpt = count($this->lines);
842 842
                     for ($i = 0; $i < $cpt; $i++)
843 843
                     {
844 844
                         // Product with reference
@@ -848,24 +848,24 @@  discard block
 block discarded – undo
848 848
                             $mouvP = new MouvementStock($this->db);
849 849
                             $mouvP->origin = &$this;
850 850
                             // We decrement stock of product (and sub-products)
851
-	                        $up_ht_disc=$this->lines[$i]->subprice;
852
-    	                    if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
853
-                            $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr",$this->ref));
851
+	                        $up_ht_disc = $this->lines[$i]->subprice;
852
+    	                    if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
853
+                            $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
854 854
                             if ($result < 0) { $error++; }
855 855
                             unset($this->line);
856 856
                         }
857 857
                     }
858 858
                 }
859 859
 
860
-                if (! $error)
860
+                if (!$error)
861 861
                 {
862 862
 					// Call trigger
863
-					$result=$this->call_trigger('ORDER_SUPPLIER_APPROVE',$user);
863
+					$result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
864 864
 					if ($result < 0) $error++;
865 865
 					// End call triggers
866 866
                 }
867 867
 
868
-                if (! $error)
868
+                if (!$error)
869 869
                 {
870 870
                 	$this->ref = $this->newref;
871 871
 
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
             else
895 895
             {
896 896
                 $this->db->rollback();
897
-                $this->error=$this->db->lasterror();
897
+                $this->error = $this->db->lasterror();
898 898
                 return -1;
899 899
             }
900 900
         }
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
     {
916 916
         global $conf, $langs;
917 917
 
918
-		$error=0;
918
+		$error = 0;
919 919
 
920 920
         dol_syslog(get_class($this)."::refuse");
921 921
         $result = 0;
@@ -933,7 +933,7 @@  discard block
 block discarded – undo
933 933
                 if ($error == 0)
934 934
                 {
935 935
 					// Call trigger
936
-					$result=$this->call_trigger('ORDER_SUPPLIER_REFUSE',$user);
936
+					$result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
937 937
 					if ($result < 0)
938 938
                     {
939 939
                         $error++;
@@ -947,7 +947,7 @@  discard block
 block discarded – undo
947 947
             else
948 948
             {
949 949
                 $this->db->rollback();
950
-                $this->error=$this->db->lasterror();
950
+                $this->error = $this->db->lasterror();
951 951
                 dol_syslog(get_class($this)."::refuse Error -1");
952 952
                 $result = -1;
953 953
             }
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
         {
957 957
             dol_syslog(get_class($this)."::refuse Not Authorized");
958 958
         }
959
-        return $result ;
959
+        return $result;
960 960
     }
961 961
 
962 962
     /**
@@ -967,11 +967,11 @@  discard block
 block discarded – undo
967 967
      *	@param	int		$idwarehouse	Id warehouse to use for stock change (not used for supplier orders).
968 968
      * 	@return	int						>0 if Ok, <0 if Ko
969 969
      */
970
-    function Cancel($user, $idwarehouse=-1)
970
+    function Cancel($user, $idwarehouse = -1)
971 971
     {
972
-        global $langs,$conf;
972
+        global $langs, $conf;
973 973
 
974
-		$error=0;
974
+		$error = 0;
975 975
 
976 976
         //dol_syslog("CommandeFournisseur::Cancel");
977 977
         $result = 0;
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
                 $result = 0;
990 990
 
991 991
 				// Call trigger
992
-				$result=$this->call_trigger('ORDER_SUPPLIER_CANCEL',$user);
992
+				$result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
993 993
 				if ($result < 0) $error++;
994 994
 				// End call triggers
995 995
 
@@ -1007,7 +1007,7 @@  discard block
 block discarded – undo
1007 1007
             else
1008 1008
             {
1009 1009
                 $this->db->rollback();
1010
-                $this->error=$this->db->lasterror();
1010
+                $this->error = $this->db->lasterror();
1011 1011
                 dol_syslog(get_class($this)."::cancel ".$this->error);
1012 1012
                 return -1;
1013 1013
             }
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
      * 	@param		string	$comment	Comment
1030 1030
      * 	@return		int			        <0 if KO, >0 if OK
1031 1031
      */
1032
-    public function commande($user, $date, $methode, $comment='')
1032
+    public function commande($user, $date, $methode, $comment = '')
1033 1033
     {
1034 1034
         global $langs;
1035 1035
         dol_syslog(get_class($this)."::commande");
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
                 $this->date_commande = $date;
1050 1050
 
1051 1051
                 // Call trigger
1052
-                $result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT',$user);
1052
+                $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
1053 1053
                 if ($result < 0) $error++;
1054 1054
                 // End call triggers
1055 1055
             }
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
                 $this->errors[] = $this->db->lasterror();
1061 1061
             }
1062 1062
 
1063
-            if (! $error)
1063
+            if (!$error)
1064 1064
             {
1065 1065
                 $this->db->commit();
1066 1066
             }
@@ -1087,20 +1087,20 @@  discard block
 block discarded – undo
1087 1087
      *	@param		int		$notrigger	Disable all triggers
1088 1088
      *  @return     int         		<0 if KO, Id of supplier order if OK
1089 1089
      */
1090
-    public function create($user, $notrigger=0)
1090
+    public function create($user, $notrigger = 0)
1091 1091
     {
1092
-        global $langs,$conf,$hookmanager;
1092
+        global $langs, $conf, $hookmanager;
1093 1093
 
1094 1094
         $this->db->begin();
1095 1095
 
1096
-		$error=0;
1097
-        $now=dol_now();
1096
+		$error = 0;
1097
+        $now = dol_now();
1098 1098
 
1099 1099
         // Clean parameters
1100 1100
         if (empty($this->source)) $this->source = 0;
1101 1101
 
1102 1102
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
1103
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1103
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1104 1104
 		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1105 1105
 		if (empty($this->fk_multicurrency))
1106 1106
 		{
@@ -1113,50 +1113,50 @@  discard block
 block discarded – undo
1113 1113
         $this->brouillon = 1;
1114 1114
 
1115 1115
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
1116
-        $sql.= "ref";
1117
-        $sql.= ", ref_supplier";
1118
-        $sql.= ", note_private";
1119
-        $sql.= ", note_public";
1120
-        $sql.= ", entity";
1121
-        $sql.= ", fk_soc";
1122
-        $sql.= ", fk_projet";
1123
-        $sql.= ", date_creation";
1124
-		$sql.= ", date_livraison";
1125
-        $sql.= ", fk_user_author";
1126
-        $sql.= ", fk_statut";
1127
-        $sql.= ", source";
1128
-        $sql.= ", model_pdf";
1129
-        $sql.= ", fk_mode_reglement";
1130
-		$sql.= ", fk_cond_reglement";
1131
-        $sql.= ", fk_account";
1132
-		$sql.= ", fk_incoterms, location_incoterms";
1133
-        $sql.= ", fk_multicurrency";
1134
-        $sql.= ", multicurrency_code";
1135
-        $sql.= ", multicurrency_tx";
1136
-        $sql.= ") ";
1137
-        $sql.= " VALUES (";
1138
-        $sql.= "''";
1139
-        $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
1140
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
1141
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
1142
-        $sql.= ", ".$conf->entity;
1143
-        $sql.= ", ".$this->socid;
1144
-        $sql.= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
1145
-        $sql.= ", '".$this->db->idate($now)."'";
1146
-		$sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
1147
-        $sql.= ", ".$user->id;
1148
-        $sql.= ", 0";
1149
-        $sql.= ", ".$this->db->escape($this->source);
1150
-        $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
1151
-        $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1152
-        $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1153
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
1154
-        $sql.= ", ".(int) $this->fk_incoterms;
1155
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
1156
-		$sql.= ", ".(int) $this->fk_multicurrency;
1157
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
1158
-		$sql.= ", ".(double) $this->multicurrency_tx;
1159
-        $sql.= ")";
1116
+        $sql .= "ref";
1117
+        $sql .= ", ref_supplier";
1118
+        $sql .= ", note_private";
1119
+        $sql .= ", note_public";
1120
+        $sql .= ", entity";
1121
+        $sql .= ", fk_soc";
1122
+        $sql .= ", fk_projet";
1123
+        $sql .= ", date_creation";
1124
+		$sql .= ", date_livraison";
1125
+        $sql .= ", fk_user_author";
1126
+        $sql .= ", fk_statut";
1127
+        $sql .= ", source";
1128
+        $sql .= ", model_pdf";
1129
+        $sql .= ", fk_mode_reglement";
1130
+		$sql .= ", fk_cond_reglement";
1131
+        $sql .= ", fk_account";
1132
+		$sql .= ", fk_incoterms, location_incoterms";
1133
+        $sql .= ", fk_multicurrency";
1134
+        $sql .= ", multicurrency_code";
1135
+        $sql .= ", multicurrency_tx";
1136
+        $sql .= ") ";
1137
+        $sql .= " VALUES (";
1138
+        $sql .= "''";
1139
+        $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
1140
+        $sql .= ", '".$this->db->escape($this->note_private)."'";
1141
+        $sql .= ", '".$this->db->escape($this->note_public)."'";
1142
+        $sql .= ", ".$conf->entity;
1143
+        $sql .= ", ".$this->socid;
1144
+        $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
1145
+        $sql .= ", '".$this->db->idate($now)."'";
1146
+		$sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null");
1147
+        $sql .= ", ".$user->id;
1148
+        $sql .= ", 0";
1149
+        $sql .= ", ".$this->db->escape($this->source);
1150
+        $sql .= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
1151
+        $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1152
+        $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1153
+        $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
1154
+        $sql .= ", ".(int) $this->fk_incoterms;
1155
+        $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1156
+		$sql .= ", ".(int) $this->fk_multicurrency;
1157
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1158
+		$sql .= ", ".(double) $this->multicurrency_tx;
1159
+        $sql .= ")";
1160 1160
 
1161 1161
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
1162 1162
         if ($this->db->query($sql))
@@ -1164,10 +1164,10 @@  discard block
 block discarded – undo
1164 1164
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
1165 1165
 
1166 1166
 			if ($this->id) {
1167
-				$num=count($this->lines);
1167
+				$num = count($this->lines);
1168 1168
 
1169 1169
 	            // insert products details into database
1170
-	            for ($i=0;$i<$num;$i++)
1170
+	            for ($i = 0; $i < $num; $i++)
1171 1171
 	            {
1172 1172
 	                $result = $this->addline(              // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1173 1173
 	                    $this->lines[$i]->desc,
@@ -1178,7 +1178,7 @@  discard block
 block discarded – undo
1178 1178
 	                    $this->lines[$i]->localtax2_tx,
1179 1179
 	                    $this->lines[$i]->fk_product,
1180 1180
 	                    0,
1181
-	                    $this->lines[$i]->ref_fourn,   // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1181
+	                    $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1182 1182
 	                    $this->lines[$i]->remise_percent,
1183 1183
 	                    'HT',
1184 1184
 	                    0,
@@ -1192,30 +1192,30 @@  discard block
 block discarded – undo
1192 1192
 	                );
1193 1193
 	                if ($result < 0)
1194 1194
 	                {
1195
-	                    dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);	// do not use dol_print_error here as it may be a functionnal error
1195
+	                    dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error
1196 1196
 	                    $this->db->rollback();
1197 1197
 	                    return -1;
1198 1198
 	                }
1199 1199
 	            }
1200 1200
 
1201 1201
 	            $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1202
-	            $sql.= " SET ref='(PROV".$this->id.")'";
1203
-	            $sql.= " WHERE rowid=".$this->id;
1202
+	            $sql .= " SET ref='(PROV".$this->id.")'";
1203
+	            $sql .= " WHERE rowid=".$this->id;
1204 1204
 	            dol_syslog(get_class($this)."::create", LOG_DEBUG);
1205 1205
 	            if ($this->db->query($sql))
1206 1206
 	            {
1207 1207
 					// Add link with price request and supplier order
1208 1208
 					if ($this->id)
1209 1209
                     {
1210
-                        $this->ref="(PROV".$this->id.")";
1210
+                        $this->ref = "(PROV".$this->id.")";
1211 1211
 
1212 1212
                         // Add object linked
1213
-                        if (is_array($this->linked_objects) && ! empty($this->linked_objects))
1213
+                        if (is_array($this->linked_objects) && !empty($this->linked_objects))
1214 1214
                         {
1215
-                        	foreach($this->linked_objects as $origin => $origin_id)
1215
+                        	foreach ($this->linked_objects as $origin => $origin_id)
1216 1216
                         	{
1217 1217
                         		$ret = $this->add_object_linked($origin, $origin_id);
1218
-                        		if (! $ret)
1218
+                        		if (!$ret)
1219 1219
                         		{
1220 1220
                         			dol_print_error($this->db);
1221 1221
                         			$error++;
@@ -1224,16 +1224,16 @@  discard block
 block discarded – undo
1224 1224
                         }
1225 1225
                     }
1226 1226
 
1227
-	                if (! $error)
1227
+	                if (!$error)
1228 1228
                     {
1229
-                    	$result=$this->insertExtraFields();
1229
+                    	$result = $this->insertExtraFields();
1230 1230
 	                    if ($result < 0) $error++;
1231 1231
                     }
1232 1232
 
1233
-					if (! $error && ! $notrigger)
1233
+					if (!$error && !$notrigger)
1234 1234
 	                {
1235 1235
 						// Call trigger
1236
-						$result=$this->call_trigger('ORDER_SUPPLIER_CREATE',$user);
1236
+						$result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
1237 1237
 						if ($result < 0)
1238 1238
 	                    {
1239 1239
 	                        $this->db->rollback();
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
 	            }
1248 1248
 	            else
1249 1249
 	            {
1250
-	                $this->error=$this->db->lasterror();
1250
+	                $this->error = $this->db->lasterror();
1251 1251
 	                $this->db->rollback();
1252 1252
 	                return -2;
1253 1253
 	            }
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
         }
1256 1256
         else
1257 1257
         {
1258
-            $this->error=$this->db->lasterror();
1258
+            $this->error = $this->db->lasterror();
1259 1259
             $this->db->rollback();
1260 1260
             return -1;
1261 1261
         }
@@ -1268,9 +1268,9 @@  discard block
 block discarded – undo
1268 1268
      */
1269 1269
     public function createFromClone()
1270 1270
     {
1271
-        global $conf,$user,$langs,$hookmanager;
1271
+        global $conf, $user, $langs, $hookmanager;
1272 1272
 
1273
-        $error=0;
1273
+        $error = 0;
1274 1274
 
1275 1275
 		$this->context['createfromclone'] = 'createfromclone';
1276 1276
 
@@ -1279,8 +1279,8 @@  discard block
 block discarded – undo
1279 1279
 		// Load source object
1280 1280
 		$objFrom = clone $this;
1281 1281
 
1282
-        $this->id=0;
1283
-        $this->statut=0;
1282
+        $this->id = 0;
1283
+        $this->statut = 0;
1284 1284
 
1285 1285
         // Clear fields
1286 1286
         $this->user_author_id     = $user->id;
@@ -1294,22 +1294,22 @@  discard block
 block discarded – undo
1294 1294
         $this->date_approve2      = '';
1295 1295
 
1296 1296
         // Create clone
1297
-        $result=$this->create($user);
1297
+        $result = $this->create($user);
1298 1298
         if ($result < 0) $error++;
1299 1299
 
1300
-        if (! $error)
1300
+        if (!$error)
1301 1301
         {
1302 1302
             // Hook of thirdparty module
1303 1303
             if (is_object($hookmanager))
1304 1304
             {
1305
-                $parameters=array('objFrom'=>$objFrom);
1306
-                $action='';
1307
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1305
+                $parameters = array('objFrom'=>$objFrom);
1306
+                $action = '';
1307
+                $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1308 1308
                 if ($reshook < 0) $error++;
1309 1309
             }
1310 1310
 
1311 1311
 			// Call trigger
1312
-			$result=$this->call_trigger('ORDER_SUPPLIER_CLONE',$user);
1312
+			$result = $this->call_trigger('ORDER_SUPPLIER_CLONE', $user);
1313 1313
 			if ($result < 0) $error++;
1314 1314
 			// End call triggers
1315 1315
         }
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
 		unset($this->context['createfromclone']);
1318 1318
 
1319 1319
 		// End
1320
-        if (! $error)
1320
+        if (!$error)
1321 1321
         {
1322 1322
             $this->db->commit();
1323 1323
             return $this->id;
@@ -1356,9 +1356,9 @@  discard block
 block discarded – undo
1356 1356
 	 *  @param		int		$origin_id				Id of origin object
1357 1357
      *	@return     int             				<=0 if KO, >0 if OK
1358 1358
      */
1359
-	public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $fourn_ref='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null, $array_options=0, $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0)
1359
+	public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $fk_prod_fourn_price = 0, $fourn_ref = '', $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $type = 0, $info_bits = 0, $notrigger = false, $date_start = null, $date_end = null, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $origin = '', $origin_id = 0)
1360 1360
     {
1361
-        global $langs,$mysoc,$conf;
1361
+        global $langs, $mysoc, $conf;
1362 1362
 
1363 1363
         $error = 0;
1364 1364
 
@@ -1366,35 +1366,35 @@  discard block
 block discarded – undo
1366 1366
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1367 1367
 
1368 1368
         // Clean parameters
1369
-        if (! $qty) $qty=1;
1370
-        if (! $info_bits) $info_bits=0;
1371
-        if (empty($txtva)) $txtva=0;
1372
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1373
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1374
-		if (empty($remise_percent)) $remise_percent=0;
1375
-
1376
-        $remise_percent=price2num($remise_percent);
1377
-        $qty=price2num($qty);
1378
-        $pu_ht=price2num($pu_ht);
1379
-        $pu_ttc=price2num($pu_ttc);
1369
+        if (!$qty) $qty = 1;
1370
+        if (!$info_bits) $info_bits = 0;
1371
+        if (empty($txtva)) $txtva = 0;
1372
+        if (empty($txlocaltax1)) $txlocaltax1 = 0;
1373
+        if (empty($txlocaltax2)) $txlocaltax2 = 0;
1374
+		if (empty($remise_percent)) $remise_percent = 0;
1375
+
1376
+        $remise_percent = price2num($remise_percent);
1377
+        $qty = price2num($qty);
1378
+        $pu_ht = price2num($pu_ht);
1379
+        $pu_ttc = price2num($pu_ttc);
1380 1380
         $txtva = price2num($txtva);
1381 1381
         $txlocaltax1 = price2num($txlocaltax1);
1382 1382
         $txlocaltax2 = price2num($txlocaltax2);
1383
-        if ($price_base_type=='HT')
1383
+        if ($price_base_type == 'HT')
1384 1384
         {
1385
-            $pu=$pu_ht;
1385
+            $pu = $pu_ht;
1386 1386
         }
1387 1387
         else
1388 1388
         {
1389
-            $pu=$pu_ttc;
1389
+            $pu = $pu_ttc;
1390 1390
         }
1391
-        $desc=trim($desc);
1392
-        $ref_supplier=''; // Ref of supplier price when we add line
1391
+        $desc = trim($desc);
1392
+        $ref_supplier = ''; // Ref of supplier price when we add line
1393 1393
 
1394 1394
         // Check parameters
1395
-        if ($qty < 1 && ! $fk_product)
1395
+        if ($qty < 1 && !$fk_product)
1396 1396
         {
1397
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Product"));
1397
+            $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("Product"));
1398 1398
             return -1;
1399 1399
         }
1400 1400
         if ($type < 0) return -1;
@@ -1417,21 +1417,21 @@  discard block
 block discarded – undo
1417 1417
 
1418 1418
                         // We use 'none' instead of $fourn_ref, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
1419 1419
                         // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
1420
-                        $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc);   // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc
1420
+                        $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc
1421 1421
                         if ($result > 0)
1422 1422
                         {
1423
-                            $pu           = $prod->fourn_pu;       // Unit price supplier price set by get_buyprice
1424
-                            $ref_supplier = $prod->ref_supplier;   // Ref supplier price set by get_buyprice
1423
+                            $pu           = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
1424
+                            $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
1425 1425
 			    // is remise percent not keyed but present for the product we add it
1426
-                            if ($remise_percent == 0 && $prod->remise_percent !=0)
1427
-                            	$remise_percent =$prod->remise_percent;
1426
+                            if ($remise_percent == 0 && $prod->remise_percent != 0)
1427
+                            	$remise_percent = $prod->remise_percent;
1428 1428
 
1429 1429
 
1430 1430
                         }
1431 1431
                         if ($result == 0)                   // If result == 0, we failed to found the supplier reference price
1432 1432
                         {
1433 1433
                             $langs->load("errors");
1434
-                            $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1434
+                            $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
1435 1435
                             $this->db->rollback();
1436 1436
                             dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
1437 1437
                             //$pu    = $prod->fourn_pu;     // We do not overwrite unit price
@@ -1441,14 +1441,14 @@  discard block
 block discarded – undo
1441 1441
                         if ($result == -1)
1442 1442
                         {
1443 1443
                             $langs->load("errors");
1444
-                            $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1444
+                            $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
1445 1445
                             $this->db->rollback();
1446 1446
                             dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
1447 1447
                             return -1;
1448 1448
                         }
1449 1449
                         if ($result < -1)
1450 1450
                         {
1451
-                            $this->error=$prod->error;
1451
+                            $this->error = $prod->error;
1452 1452
                             $this->db->rollback();
1453 1453
                             dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1454 1454
                             return -1;
@@ -1456,7 +1456,7 @@  discard block
 block discarded – undo
1456 1456
                     }
1457 1457
                     else
1458 1458
     				{
1459
-                        $this->error=$prod->error;
1459
+                        $this->error = $prod->error;
1460 1460
                         return -1;
1461 1461
                     }
1462 1462
                 }
@@ -1471,17 +1471,17 @@  discard block
 block discarded – undo
1471 1471
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1472 1472
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1473 1473
 
1474
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc,$this->thirdparty);
1474
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1475 1475
 
1476 1476
             // Clean vat code
1477
-            $vat_src_code='';
1477
+            $vat_src_code = '';
1478 1478
             if (preg_match('/\((.*)\)/', $txtva, $reg))
1479 1479
             {
1480 1480
                 $vat_src_code = $reg[1];
1481
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1481
+                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1482 1482
             }
1483 1483
 
1484
-            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx,$pu_ht_devise);
1484
+            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1485 1485
             $total_ht  = $tabprice[0];
1486 1486
             $total_tva = $tabprice[1];
1487 1487
             $total_ttc = $tabprice[2];
@@ -1490,82 +1490,82 @@  discard block
 block discarded – undo
1490 1490
 			$pu_ht = $tabprice[3];
1491 1491
 
1492 1492
 			// MultiCurrency
1493
-			$multicurrency_total_ht  = $tabprice[16];
1493
+			$multicurrency_total_ht = $tabprice[16];
1494 1494
             $multicurrency_total_tva = $tabprice[17];
1495 1495
             $multicurrency_total_ttc = $tabprice[18];
1496 1496
 			$pu_ht_devise = $tabprice[19];
1497 1497
 
1498
-            $localtax1_type=$localtaxes_type[0];
1499
-			$localtax2_type=$localtaxes_type[2];
1498
+            $localtax1_type = $localtaxes_type[0];
1499
+			$localtax2_type = $localtaxes_type[2];
1500 1500
 
1501
-            $subprice = price2num($pu,'MU');
1501
+            $subprice = price2num($pu, 'MU');
1502 1502
 
1503 1503
             $rangmax = $this->line_max();
1504 1504
             $rang = $rangmax + 1;
1505 1505
 
1506 1506
             // Insert line
1507
-            $this->line=new CommandeFournisseurLigne($this->db);
1507
+            $this->line = new CommandeFournisseurLigne($this->db);
1508 1508
 
1509 1509
             $this->line->context = $this->context;
1510 1510
 
1511
-            $this->line->fk_commande=$this->id;
1512
-            $this->line->label=$label;
1511
+            $this->line->fk_commande = $this->id;
1512
+            $this->line->label = $label;
1513 1513
             $this->line->ref_fourn = $ref_supplier;
1514 1514
             $this->line->ref_supplier = $ref_supplier;
1515
-            $this->line->desc=$desc;
1516
-            $this->line->qty=$qty;
1517
-            $this->line->tva_tx=$txtva;
1518
-            $this->line->localtax1_tx=$txlocaltax1;
1519
-            $this->line->localtax2_tx=$txlocaltax2;
1515
+            $this->line->desc = $desc;
1516
+            $this->line->qty = $qty;
1517
+            $this->line->tva_tx = $txtva;
1518
+            $this->line->localtax1_tx = $txlocaltax1;
1519
+            $this->line->localtax2_tx = $txlocaltax2;
1520 1520
             $this->line->localtax1_type = $localtaxes_type[0];
1521 1521
             $this->line->localtax2_type = $localtaxes_type[2];
1522
-            $this->line->fk_product=$fk_product;
1523
-            $this->line->product_type=$product_type;
1524
-            $this->line->remise_percent=$remise_percent;
1525
-            $this->line->subprice=$pu_ht;
1526
-            $this->line->rang=$this->rang;
1527
-            $this->line->info_bits=$info_bits;
1528
-
1529
-            $this->line->vat_src_code=$vat_src_code;
1530
-            $this->line->total_ht=$total_ht;
1531
-            $this->line->total_tva=$total_tva;
1532
-            $this->line->total_localtax1=$total_localtax1;
1533
-            $this->line->total_localtax2=$total_localtax2;
1534
-            $this->line->total_ttc=$total_ttc;
1535
-            $this->line->product_type=$type;
1536
-            $this->line->special_code=$this->special_code;
1537
-            $this->line->origin=$origin;
1538
-            $this->line->origin_id=$origin_id;
1539
-            $this->line->fk_unit=$fk_unit;
1540
-
1541
-            $this->line->date_start=$date_start;
1542
-            $this->line->date_end=$date_end;
1522
+            $this->line->fk_product = $fk_product;
1523
+            $this->line->product_type = $product_type;
1524
+            $this->line->remise_percent = $remise_percent;
1525
+            $this->line->subprice = $pu_ht;
1526
+            $this->line->rang = $this->rang;
1527
+            $this->line->info_bits = $info_bits;
1528
+
1529
+            $this->line->vat_src_code = $vat_src_code;
1530
+            $this->line->total_ht = $total_ht;
1531
+            $this->line->total_tva = $total_tva;
1532
+            $this->line->total_localtax1 = $total_localtax1;
1533
+            $this->line->total_localtax2 = $total_localtax2;
1534
+            $this->line->total_ttc = $total_ttc;
1535
+            $this->line->product_type = $type;
1536
+            $this->line->special_code = $this->special_code;
1537
+            $this->line->origin = $origin;
1538
+            $this->line->origin_id = $origin_id;
1539
+            $this->line->fk_unit = $fk_unit;
1540
+
1541
+            $this->line->date_start = $date_start;
1542
+            $this->line->date_end = $date_end;
1543 1543
 
1544 1544
             // Multicurrency
1545
-            $this->line->fk_multicurrency			= $this->fk_multicurrency;
1546
-            $this->line->multicurrency_code			= $this->multicurrency_code;
1545
+            $this->line->fk_multicurrency = $this->fk_multicurrency;
1546
+            $this->line->multicurrency_code = $this->multicurrency_code;
1547 1547
             $this->line->multicurrency_subprice		= $pu_ht_devise;
1548 1548
             $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1549 1549
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1550 1550
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1551 1551
 
1552
-            $this->line->subprice=$pu_ht;
1553
-            $this->line->price=$this->line->subprice;
1552
+            $this->line->subprice = $pu_ht;
1553
+            $this->line->price = $this->line->subprice;
1554 1554
 
1555
-            $this->line->remise_percent=$remise_percent;
1555
+            $this->line->remise_percent = $remise_percent;
1556 1556
 
1557
-            if (is_array($array_options) && count($array_options)>0) {
1558
-                $this->line->array_options=$array_options;
1557
+            if (is_array($array_options) && count($array_options) > 0) {
1558
+                $this->line->array_options = $array_options;
1559 1559
             }
1560 1560
 
1561
-            $result=$this->line->insert($notrigger);
1561
+            $result = $this->line->insert($notrigger);
1562 1562
             if ($result > 0)
1563 1563
             {
1564 1564
                 // Reorder if child line
1565
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1565
+                if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
1566 1566
 
1567 1567
                 // Mise a jour informations denormalisees au niveau de la commande meme
1568
-                $result=$this->update_price(1,'auto',0,$this->thirdparty);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1568
+                $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1569 1569
                 if ($result > 0)
1570 1570
                 {
1571 1571
                     $this->db->commit();
@@ -1579,8 +1579,8 @@  discard block
 block discarded – undo
1579 1579
             }
1580 1580
             else
1581 1581
             {
1582
-                $this->error=$this->line->error;
1583
-                $this->errors=$this->line->errors;
1582
+                $this->error = $this->line->error;
1583
+                $this->errors = $this->line->errors;
1584 1584
                 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1585 1585
                 $this->db->rollback();
1586 1586
                 return -1;
@@ -1605,49 +1605,49 @@  discard block
 block discarded – undo
1605 1605
      * @param	int			$notrigger          	1 = notrigger
1606 1606
      * @return 	int						<0 if KO, >0 if OK
1607 1607
      */
1608
-    public function dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0)
1608
+    public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0)
1609 1609
     {
1610 1610
         global $conf, $langs;
1611 1611
 
1612 1612
         $error = 0;
1613
-        require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
1613
+        require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1614 1614
 
1615 1615
         // Check parameters (if test are wrong here, there is bug into caller)
1616 1616
         if ($entrepot <= 0)
1617 1617
         {
1618
-            $this->error='ErrorBadValueForParameterWarehouse';
1618
+            $this->error = 'ErrorBadValueForParameterWarehouse';
1619 1619
             return -1;
1620 1620
         }
1621 1621
         if ($qty <= 0)
1622 1622
         {
1623
-            $this->error='ErrorBadValueForParameterQty';
1623
+            $this->error = 'ErrorBadValueForParameterQty';
1624 1624
             return -1;
1625 1625
         }
1626 1626
 
1627 1627
         $dispatchstatus = 1;
1628
-        if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0;	// Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1628
+        if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1629 1629
 
1630
-        $now=dol_now();
1630
+        $now = dol_now();
1631 1631
 
1632 1632
         if (($this->statut == 3 || $this->statut == 4 || $this->statut == 5))
1633 1633
         {
1634 1634
             $this->db->begin();
1635 1635
 
1636 1636
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
1637
-            $sql.= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
1638
-            $sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
1639
-            $sql.= ($eatby?"'".$this->db->idate($eatby)."'":"null").", ".($sellby?"'".$this->db->idate($sellby)."'":"null").", ".($batch?"'".$batch."'":"null");
1640
-            $sql.= ")";
1637
+            $sql .= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
1638
+            $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
1639
+            $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$batch."'" : "null");
1640
+            $sql .= ")";
1641 1641
 
1642 1642
             dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
1643 1643
             $resql = $this->db->query($sql);
1644 1644
             if ($resql)
1645 1645
             {
1646
-                if (! $notrigger)
1646
+                if (!$notrigger)
1647 1647
                 {
1648 1648
                     global $conf, $langs, $user;
1649 1649
 					// Call trigger
1650
-					$result=$this->call_trigger('LINEORDER_SUPPLIER_DISPATCH',$user);
1650
+					$result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user);
1651 1651
 					if ($result < 0)
1652 1652
                     {
1653 1653
                         $error++;
@@ -1658,12 +1658,12 @@  discard block
 block discarded – undo
1658 1658
             }
1659 1659
             else
1660 1660
 			{
1661
-                $this->error=$this->db->lasterror();
1661
+                $this->error = $this->db->lasterror();
1662 1662
                 $error++;
1663 1663
             }
1664 1664
 
1665 1665
             // Si module stock gere et que incrementation faite depuis un dispatching en stock
1666
-            if (! $error && $entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
1666
+            if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
1667 1667
             {
1668 1668
 
1669 1669
                 $mouv = new MouvementStock($this->db);
@@ -1671,12 +1671,12 @@  discard block
 block discarded – undo
1671 1671
                 {
1672 1672
                 	// $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
1673 1673
                 	$mouv->origin = &$this;
1674
-					$result=$mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch);
1674
+					$result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch);
1675 1675
                     if ($result < 0)
1676 1676
                     {
1677
-                        $this->error=$mouv->error;
1678
-                        $this->errors=$mouv->errors;
1679
-                        dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',',$this->errors), LOG_ERR);
1677
+                        $this->error = $mouv->error;
1678
+                        $this->errors = $mouv->errors;
1679
+                        dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR);
1680 1680
                         $error++;
1681 1681
                     }
1682 1682
                 }
@@ -1695,7 +1695,7 @@  discard block
 block discarded – undo
1695 1695
         }
1696 1696
         else
1697 1697
 		{
1698
-            $this->error='BadStatusForObject';
1698
+            $this->error = 'BadStatusForObject';
1699 1699
             return -2;
1700 1700
         }
1701 1701
     }
@@ -1707,7 +1707,7 @@  discard block
 block discarded – undo
1707 1707
      *	@param	int		$notrigger	1=Disable call to triggers
1708 1708
      *	@return	int					<0 if KO, >0 if OK
1709 1709
      */
1710
-    public function deleteline($idline, $notrigger=0)
1710
+    public function deleteline($idline, $notrigger = 0)
1711 1711
     {
1712 1712
         if ($this->statut == 0)
1713 1713
         {
@@ -1743,9 +1743,9 @@  discard block
 block discarded – undo
1743 1743
      *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1744 1744
      *	@return	int					<0 if KO, >0 if OK
1745 1745
      */
1746
-    public function delete(User $user, $notrigger=0)
1746
+    public function delete(User $user, $notrigger = 0)
1747 1747
     {
1748
-        global $langs,$conf;
1748
+        global $langs, $conf;
1749 1749
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1750 1750
 
1751 1751
         $error = 0;
@@ -1755,51 +1755,51 @@  discard block
 block discarded – undo
1755 1755
         if (empty($notrigger))
1756 1756
         {
1757 1757
             // Call trigger
1758
-            $result=$this->call_trigger('ORDER_SUPPLIER_DELETE',$user);
1758
+            $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user);
1759 1759
             if ($result < 0)
1760 1760
             {
1761
-            	$this->errors[]='ErrorWhenRunningTrigger';
1761
+            	$this->errors[] = 'ErrorWhenRunningTrigger';
1762 1762
             	dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1763 1763
             	return -1;
1764 1764
             }
1765 1765
             // End call triggers
1766 1766
         }
1767 1767
 
1768
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ;
1768
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =".$this->id;
1769 1769
         dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1770
-        if (! $this->db->query($sql) )
1770
+        if (!$this->db->query($sql))
1771 1771
         {
1772
-            $this->error=$this->db->lasterror();
1773
-            $this->errors[]=$this->db->lasterror();
1772
+            $this->error = $this->db->lasterror();
1773
+            $this->errors[] = $this->db->lasterror();
1774 1774
             $error++;
1775 1775
         }
1776 1776
 
1777 1777
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id;
1778 1778
         dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1779
-        if ($resql = $this->db->query($sql) )
1779
+        if ($resql = $this->db->query($sql))
1780 1780
         {
1781 1781
             if ($this->db->affected_rows($resql) < 1)
1782 1782
             {
1783
-                $this->error=$this->db->lasterror();
1784
-                $this->errors[]=$this->db->lasterror();
1783
+                $this->error = $this->db->lasterror();
1784
+                $this->errors[] = $this->db->lasterror();
1785 1785
                 $error++;
1786 1786
             }
1787 1787
         }
1788 1788
         else
1789 1789
         {
1790
-            $this->error=$this->db->lasterror();
1791
-            $this->errors[]=$this->db->lasterror();
1790
+            $this->error = $this->db->lasterror();
1791
+            $this->errors[] = $this->db->lasterror();
1792 1792
             $error++;
1793 1793
         }
1794 1794
 
1795 1795
         // Remove extrafields
1796
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1796
+        if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1797 1797
         {
1798
-        	$result=$this->deleteExtraFields();
1798
+        	$result = $this->deleteExtraFields();
1799 1799
         	if ($result < 0)
1800 1800
         	{
1801
-        		$this->error='FailToDeleteExtraFields';
1802
-        		$this->errors[]='FailToDeleteExtraFields';
1801
+        		$this->error = 'FailToDeleteExtraFields';
1802
+        		$this->errors[] = 'FailToDeleteExtraFields';
1803 1803
         		$error++;
1804 1804
         		dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1805 1805
         	}
@@ -1808,42 +1808,42 @@  discard block
 block discarded – undo
1808 1808
 		// Delete linked object
1809 1809
     	$res = $this->deleteObjectLinked();
1810 1810
     	if ($res < 0) {
1811
-    		$this->error='FailToDeleteObjectLinked';
1812
-    		$this->errors[]='FailToDeleteObjectLinked';
1811
+    		$this->error = 'FailToDeleteObjectLinked';
1812
+    		$this->errors[] = 'FailToDeleteObjectLinked';
1813 1813
     		$error++;
1814 1814
     	}
1815 1815
 
1816
-        if (! $error)
1816
+        if (!$error)
1817 1817
         {
1818 1818
         	// We remove directory
1819 1819
         	$ref = dol_sanitizeFileName($this->ref);
1820 1820
         	if ($conf->fournisseur->commande->dir_output)
1821 1821
         	{
1822
-        		$dir = $conf->fournisseur->commande->dir_output . "/" . $ref ;
1823
-        		$file = $dir . "/" . $ref . ".pdf";
1822
+        		$dir = $conf->fournisseur->commande->dir_output."/".$ref;
1823
+        		$file = $dir."/".$ref.".pdf";
1824 1824
         		if (file_exists($file))
1825 1825
         		{
1826
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1826
+        			if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
1827 1827
         			{
1828
-        				$this->error='ErrorFailToDeleteFile';
1829
-        				$this->errors[]='ErrorFailToDeleteFile';
1828
+        				$this->error = 'ErrorFailToDeleteFile';
1829
+        				$this->errors[] = 'ErrorFailToDeleteFile';
1830 1830
         				$error++;
1831 1831
         			}
1832 1832
         		}
1833 1833
         		if (file_exists($dir))
1834 1834
         		{
1835
-        			$res=@dol_delete_dir_recursive($dir);
1836
-        			if (! $res)
1835
+        			$res = @dol_delete_dir_recursive($dir);
1836
+        			if (!$res)
1837 1837
         			{
1838
-        				$this->error='ErrorFailToDeleteDir';
1839
-        				$this->errors[]='ErrorFailToDeleteDir';
1838
+        				$this->error = 'ErrorFailToDeleteDir';
1839
+        				$this->errors[] = 'ErrorFailToDeleteDir';
1840 1840
         				$error++;
1841 1841
         			}
1842 1842
         		}
1843 1843
         	}
1844 1844
         }
1845 1845
 
1846
-		if (! $error)
1846
+		if (!$error)
1847 1847
 		{
1848 1848
 			dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1849 1849
 			$this->db->commit();
@@ -1865,10 +1865,10 @@  discard block
 block discarded – undo
1865 1865
     function get_methodes_commande()
1866 1866
     {
1867 1867
         $sql = "SELECT rowid, libelle";
1868
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
1869
-        $sql.= " WHERE active = 1";
1868
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method";
1869
+        $sql .= " WHERE active = 1";
1870 1870
 
1871
-        $resql=$this->db->query($sql);
1871
+        $resql = $this->db->query($sql);
1872 1872
         if ($resql)
1873 1873
         {
1874 1874
             $i = 0;
@@ -1896,21 +1896,21 @@  discard block
 block discarded – undo
1896 1896
 	 * @param	int		$status		Filter on stats (-1 = no filter, 0 = lines draft to be approved, 1 = approved lines)
1897 1897
 	 * @return	array				Array of lines
1898 1898
      */
1899
-    public function getDispachedLines($status=-1)
1899
+    public function getDispachedLines($status = -1)
1900 1900
     {
1901 1901
     	$ret = array();
1902 1902
 
1903 1903
     	// List of already dispatched lines
1904 1904
 		$sql = "SELECT p.ref, p.label,";
1905
-		$sql.= " e.rowid as warehouse_id, e.label as entrepot,";
1906
-		$sql.= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
1907
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p,";
1908
-		$sql.= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
1909
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
1910
-		$sql.= " WHERE cfd.fk_commande = ".$this->id;
1911
-		$sql.= " AND cfd.fk_product = p.rowid";
1912
-		if ($status >= 0) $sql.=" AND cfd.status = ".$status;
1913
-		$sql.= " ORDER BY cfd.rowid ASC";
1905
+		$sql .= " e.rowid as warehouse_id, e.label as entrepot,";
1906
+		$sql .= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
1907
+		$sql .= " FROM ".MAIN_DB_PREFIX."product as p,";
1908
+		$sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
1909
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
1910
+		$sql .= " WHERE cfd.fk_commande = ".$this->id;
1911
+		$sql .= " AND cfd.fk_product = p.rowid";
1912
+		if ($status >= 0) $sql .= " AND cfd.status = ".$status;
1913
+		$sql .= " ORDER BY cfd.rowid ASC";
1914 1914
 
1915 1915
 		$resql = $this->db->query($sql);
1916 1916
 		if ($resql)
@@ -1921,7 +1921,7 @@  discard block
 block discarded – undo
1921 1921
 			while ($i < $num)
1922 1922
 			{
1923 1923
 				$objp = $this->db->fetch_object($resql);
1924
-				if ($objp) $ret[]=array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
1924
+				if ($objp) $ret[] = array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
1925 1925
 
1926 1926
 				$i++;
1927 1927
 			}
@@ -1958,29 +1958,29 @@  discard block
 block discarded – undo
1958 1958
             if ($type == 'can') $statut = 7;
1959 1959
 
1960 1960
             // Some checks to accept the record
1961
-            if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
1961
+            if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
1962 1962
             {
1963 1963
 				// If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
1964
-	        	if (! $error && ($type == 'tot'))
1964
+	        	if (!$error && ($type == 'tot'))
1965 1965
 		    	{
1966
-		    		$dispatchedlinearray=$this->getDispachedLines(0);
1966
+		    		$dispatchedlinearray = $this->getDispachedLines(0);
1967 1967
 		    		if (count($dispatchedlinearray) > 0)
1968 1968
 		    		{
1969
-		    			$result=-1;
1969
+		    			$result = -1;
1970 1970
 		    			$error++;
1971
-		    			$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
1971
+		    			$this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
1972 1972
 		    			dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
1973 1973
 		    		}
1974 1974
 
1975 1975
 		    	}
1976
-	    		if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot'))	// Accept to move to reception done, only if status of all line are ok (refuse denied)
1976
+	    		if (!$error && !empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot'))	// Accept to move to reception done, only if status of all line are ok (refuse denied)
1977 1977
 	    		{
1978
-	    			$dispatcheddenied=$this->getDispachedLines(2);
1978
+	    			$dispatcheddenied = $this->getDispachedLines(2);
1979 1979
 	    			if (count($dispatchedlinearray) > 0)
1980 1980
 	    			{
1981
-		    			$result=-1;
1981
+		    			$result = -1;
1982 1982
 		    			$error++;
1983
-		    			$this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
1983
+		    			$this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
1984 1984
 		    			dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
1985 1985
 	    			}
1986 1986
 	    		}
@@ -1989,24 +1989,24 @@  discard block
 block discarded – undo
1989 1989
             // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
1990 1990
 
1991 1991
 
1992
-            if (! $error && ! ($statut == 4 or $statut == 5 or $statut == 7))
1992
+            if (!$error && !($statut == 4 or $statut == 5 or $statut == 7))
1993 1993
             {
1994 1994
             	$error++;
1995 1995
                 dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
1996 1996
                 $result = -2;
1997 1997
             }
1998 1998
 
1999
-            if (! $error)
1999
+            if (!$error)
2000 2000
             {
2001 2001
                 $this->db->begin();
2002 2002
 
2003 2003
                 $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2004
-                $sql.= " SET fk_statut = ".$statut;
2005
-                $sql.= " WHERE rowid = ".$this->id;
2006
-                $sql.= " AND fk_statut IN (3,4)";	// Process running or Partially received
2004
+                $sql .= " SET fk_statut = ".$statut;
2005
+                $sql .= " WHERE rowid = ".$this->id;
2006
+                $sql .= " AND fk_statut IN (3,4)"; // Process running or Partially received
2007 2007
 
2008 2008
                 dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2009
-                $resql=$this->db->query($sql);
2009
+                $resql = $this->db->query($sql);
2010 2010
                 if ($resql)
2011 2011
                 {
2012 2012
                     $result = 0;
@@ -2015,11 +2015,11 @@  discard block
 block discarded – undo
2015 2015
 					$this->actionmsg2 = $comment;
2016 2016
 
2017 2017
                     // Call trigger
2018
-                    $result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE',$user);
2018
+                    $result = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
2019 2019
                     if ($result < 0) $error++;
2020 2020
                     // End call triggers
2021 2021
 
2022
-                    if (! $error)
2022
+                    if (!$error)
2023 2023
                     {
2024 2024
                         $this->db->commit();
2025 2025
                     }
@@ -2027,14 +2027,14 @@  discard block
 block discarded – undo
2027 2027
                     {
2028 2028
                         $this->statut = $old_statut;
2029 2029
                         $this->db->rollback();
2030
-                        $this->error=$this->db->lasterror();
2030
+                        $this->error = $this->db->lasterror();
2031 2031
                         $result = -1;
2032 2032
                     }
2033 2033
                 }
2034 2034
                 else
2035 2035
                 {
2036 2036
                     $this->db->rollback();
2037
-                    $this->error=$this->db->lasterror();
2037
+                    $this->error = $this->db->lasterror();
2038 2038
                     $result = -1;
2039 2039
                 }
2040 2040
             }
@@ -2046,7 +2046,7 @@  discard block
 block discarded – undo
2046 2046
             dol_syslog(get_class($this)."::Livraison Not Authorized");
2047 2047
             $result = -3;
2048 2048
         }
2049
-        return $result ;
2049
+        return $result;
2050 2050
     }
2051 2051
 
2052 2052
 	/**
@@ -2057,54 +2057,54 @@  discard block
 block discarded – undo
2057 2057
      *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2058 2058
      *	@return     int         						<0 if KO, >0 if OK
2059 2059
      */
2060
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
2060
+    function set_date_livraison($user, $date_livraison, $notrigger = 0)
2061 2061
     {
2062 2062
         if ($user->rights->fournisseur->commande->creer)
2063 2063
         {
2064
-        	$error=0;
2064
+        	$error = 0;
2065 2065
 
2066 2066
         	$this->db->begin();
2067 2067
 
2068 2068
         	$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2069
-            $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2070
-            $sql.= " WHERE rowid = ".$this->id;
2069
+            $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2070
+            $sql .= " WHERE rowid = ".$this->id;
2071 2071
 
2072 2072
         	dol_syslog(__METHOD__, LOG_DEBUG);
2073
-        	$resql=$this->db->query($sql);
2073
+        	$resql = $this->db->query($sql);
2074 2074
         	if (!$resql)
2075 2075
         	{
2076
-        		$this->errors[]=$this->db->error();
2076
+        		$this->errors[] = $this->db->error();
2077 2077
         		$error++;
2078 2078
         	}
2079 2079
 
2080
-        	if (! $error)
2080
+        	if (!$error)
2081 2081
         	{
2082
-        		$this->oldcopy= clone $this;
2082
+        		$this->oldcopy = clone $this;
2083 2083
         		$this->date_livraison = $date_livraison;
2084 2084
         	}
2085 2085
 
2086
-        	if (! $notrigger && empty($error))
2086
+        	if (!$notrigger && empty($error))
2087 2087
         	{
2088 2088
         		// Call trigger
2089
-        		$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2089
+        		$result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2090 2090
         		if ($result < 0) $error++;
2091 2091
         		// End call triggers
2092 2092
         	}
2093 2093
 
2094
-        	if (! $error)
2094
+        	if (!$error)
2095 2095
         	{
2096 2096
         		$this->db->commit();
2097 2097
         		return 1;
2098 2098
         	}
2099 2099
         	else
2100 2100
         	{
2101
-        		foreach($this->errors as $errmsg)
2101
+        		foreach ($this->errors as $errmsg)
2102 2102
         		{
2103 2103
         			dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2104
-        			$this->error.=($this->error?', '.$errmsg:$errmsg);
2104
+        			$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2105 2105
         		}
2106 2106
         		$this->db->rollback();
2107
-        		return -1*$error;
2107
+        		return -1 * $error;
2108 2108
         	}
2109 2109
         }
2110 2110
         else
@@ -2121,54 +2121,54 @@  discard block
 block discarded – undo
2121 2121
      *  @param     	int				$notrigger			1=Does not execute triggers, 0= execute triggers
2122 2122
      *	@return     int         						<0 si ko, >0 si ok
2123 2123
      */
2124
-    function set_id_projet($user, $id_projet, $notrigger=0)
2124
+    function set_id_projet($user, $id_projet, $notrigger = 0)
2125 2125
     {
2126 2126
         if ($user->rights->fournisseur->commande->creer)
2127 2127
         {
2128
-        	$error=0;
2128
+        	$error = 0;
2129 2129
 
2130 2130
         	$this->db->begin();
2131 2131
 
2132 2132
             $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2133
-            $sql.= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2134
-            $sql.= " WHERE rowid = ".$this->id;
2133
+            $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2134
+            $sql .= " WHERE rowid = ".$this->id;
2135 2135
 
2136 2136
             dol_syslog(__METHOD__, LOG_DEBUG);
2137
-            $resql=$this->db->query($sql);
2137
+            $resql = $this->db->query($sql);
2138 2138
             if (!$resql)
2139 2139
             {
2140
-            	$this->errors[]=$this->db->error();
2140
+            	$this->errors[] = $this->db->error();
2141 2141
             	$error++;
2142 2142
             }
2143 2143
 
2144
-            if (! $error)
2144
+            if (!$error)
2145 2145
             {
2146
-            	$this->oldcopy= clone $this;
2146
+            	$this->oldcopy = clone $this;
2147 2147
             	$this->fk_projet = $id_projet;
2148 2148
             }
2149 2149
 
2150
-            if (! $notrigger && empty($error))
2150
+            if (!$notrigger && empty($error))
2151 2151
             {
2152 2152
             	// Call trigger
2153
-            	$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2153
+            	$result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2154 2154
             	if ($result < 0) $error++;
2155 2155
             	// End call triggers
2156 2156
             }
2157 2157
 
2158
-            if (! $error)
2158
+            if (!$error)
2159 2159
             {
2160 2160
             	$this->db->commit();
2161 2161
             	return 1;
2162 2162
             }
2163 2163
             else
2164 2164
             {
2165
-            	foreach($this->errors as $errmsg)
2165
+            	foreach ($this->errors as $errmsg)
2166 2166
             	{
2167 2167
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2168
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2168
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2169 2169
             	}
2170 2170
             	$this->db->rollback();
2171
-            	return -1*$error;
2171
+            	return -1 * $error;
2172 2172
             }
2173 2173
         }
2174 2174
         else
@@ -2194,7 +2194,7 @@  discard block
 block discarded – undo
2194 2194
 
2195 2195
         $this->lines = array();
2196 2196
 
2197
-        $num=count($comclient->lines);
2197
+        $num = count($comclient->lines);
2198 2198
         for ($i = 0; $i < $num; $i++)
2199 2199
         {
2200 2200
             $prod = new Product($this->db);
@@ -2206,7 +2206,7 @@  discard block
 block discarded – undo
2206 2206
 
2207 2207
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
2208 2208
             $sql .= " (fk_commande,label,description,fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2209
-            $sql .= " VALUES (".$idc.", '" . $this->db->escape($libelle) . "','" . $this->db->escape($comclient->lines[$i]->desc) . "'";
2209
+            $sql .= " VALUES (".$idc.", '".$this->db->escape($libelle)."','".$this->db->escape($comclient->lines[$i]->desc)."'";
2210 2210
             $sql .= ",".$comclient->lines[$i]->fk_product.",'".price2num($comclient->lines[$i]->price)."'";
2211 2211
             $sql .= ", '".$comclient->lines[$i]->qty."', ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent;
2212 2212
             $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0','".$ref."');";
@@ -2226,16 +2226,16 @@  discard block
 block discarded – undo
2226 2226
      *  @param      int		$status		New status
2227 2227
      *  @return     int         		<0 if KO, >0 if OK
2228 2228
      */
2229
-    public function setStatus($user,$status)
2229
+    public function setStatus($user, $status)
2230 2230
     {
2231
-        global $conf,$langs;
2232
-        $error=0;
2231
+        global $conf, $langs;
2232
+        $error = 0;
2233 2233
 
2234 2234
         $this->db->begin();
2235 2235
 
2236 2236
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
2237
-        $sql.= ' SET fk_statut='.$status;
2238
-        $sql.= ' WHERE rowid = '.$this->id;
2237
+        $sql .= ' SET fk_statut='.$status;
2238
+        $sql .= ' WHERE rowid = '.$this->id;
2239 2239
 
2240 2240
         dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2241 2241
         $resql = $this->db->query($sql);
@@ -2254,18 +2254,18 @@  discard block
 block discarded – undo
2254 2254
             $trigger_name[9] = 'REFUSED';
2255 2255
 
2256 2256
             // Call trigger
2257
-            $result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status],$user);
2257
+            $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status], $user);
2258 2258
             if ($result < 0) { $error++; }
2259 2259
             // End call triggers
2260 2260
         }
2261 2261
         else
2262 2262
         {
2263 2263
             $error++;
2264
-            $this->error=$this->db->lasterror();
2264
+            $this->error = $this->db->lasterror();
2265 2265
             dol_syslog(get_class($this)."::setStatus ".$this->error);
2266 2266
         }
2267 2267
 
2268
-        if (! $error)
2268
+        if (!$error)
2269 2269
         {
2270 2270
             $this->statut = $status;
2271 2271
             $this->db->commit();
@@ -2300,7 +2300,7 @@  discard block
 block discarded – undo
2300 2300
 	 * 	@param		double		$pu_ht_devise		Unit price in currency
2301 2301
      *	@return    	int         	    			< 0 if error, > 0 if ok
2302 2302
      */
2303
-    public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0)
2303
+    public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $notrigger = false, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0)
2304 2304
     {
2305 2305
     	global $mysoc, $conf;
2306 2306
         dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
@@ -2313,21 +2313,21 @@  discard block
 block discarded – undo
2313 2313
             $this->db->begin();
2314 2314
 
2315 2315
             // Clean parameters
2316
-            if (empty($qty)) $qty=0;
2317
-            if (empty($info_bits)) $info_bits=0;
2318
-            if (empty($txtva)) $txtva=0;
2319
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2320
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2321
-            if (empty($remise)) $remise=0;
2322
-            if (empty($remise_percent)) $remise_percent=0;
2323
-
2324
-            $remise_percent=price2num($remise_percent);
2325
-            $qty=price2num($qty);
2326
-            if (! $qty) $qty=1;
2316
+            if (empty($qty)) $qty = 0;
2317
+            if (empty($info_bits)) $info_bits = 0;
2318
+            if (empty($txtva)) $txtva = 0;
2319
+            if (empty($txlocaltax1)) $txlocaltax1 = 0;
2320
+            if (empty($txlocaltax2)) $txlocaltax2 = 0;
2321
+            if (empty($remise)) $remise = 0;
2322
+            if (empty($remise_percent)) $remise_percent = 0;
2323
+
2324
+            $remise_percent = price2num($remise_percent);
2325
+            $qty = price2num($qty);
2326
+            if (!$qty) $qty = 1;
2327 2327
             $pu = price2num($pu);
2328
-            $txtva=price2num($txtva);
2329
-            $txlocaltax1=price2num($txlocaltax1);
2330
-            $txlocaltax2=price2num($txlocaltax2);
2328
+            $txtva = price2num($txtva);
2329
+            $txlocaltax1 = price2num($txlocaltax1);
2330
+            $txlocaltax2 = price2num($txlocaltax2);
2331 2331
 
2332 2332
             // Check parameters
2333 2333
             if ($type < 0) return -1;
@@ -2337,17 +2337,17 @@  discard block
 block discarded – undo
2337 2337
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2338 2338
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2339 2339
 
2340
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc, $this->thirdparty);
2340
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2341 2341
 
2342 2342
             // Clean vat code
2343
-            $vat_src_code='';
2343
+            $vat_src_code = '';
2344 2344
             if (preg_match('/\((.*)\)/', $txtva, $reg))
2345 2345
             {
2346 2346
                 $vat_src_code = $reg[1];
2347
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2347
+                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2348 2348
             }
2349 2349
 
2350
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2350
+            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2351 2351
             $total_ht  = $tabprice[0];
2352 2352
             $total_tva = $tabprice[1];
2353 2353
             $total_ttc = $tabprice[2];
@@ -2358,30 +2358,30 @@  discard block
 block discarded – undo
2358 2358
 			$pu_ttc = $tabprice[5];
2359 2359
 
2360 2360
 			// MultiCurrency
2361
-			$multicurrency_total_ht  = $tabprice[16];
2361
+			$multicurrency_total_ht = $tabprice[16];
2362 2362
             $multicurrency_total_tva = $tabprice[17];
2363 2363
             $multicurrency_total_ttc = $tabprice[18];
2364 2364
 			$pu_ht_devise = $tabprice[19];
2365 2365
 
2366
-            $localtax1_type=$localtaxes_type[0];
2367
-			$localtax2_type=$localtaxes_type[2];
2366
+            $localtax1_type = $localtaxes_type[0];
2367
+			$localtax2_type = $localtaxes_type[2];
2368 2368
 
2369
-            $subprice = price2num($pu_ht,'MU');
2369
+            $subprice = price2num($pu_ht, 'MU');
2370 2370
 
2371 2371
             //Fetch current line from the database and then clone the object and set it in $oldline property
2372
-            $this->line=new CommandeFournisseurLigne($this->db);
2372
+            $this->line = new CommandeFournisseurLigne($this->db);
2373 2373
             $this->line->fetch($rowid);
2374 2374
             $oldline = clone $this->line;
2375 2375
             $this->line->oldline = $oldline;
2376 2376
 
2377 2377
             $this->line->context = $this->context;
2378 2378
 
2379
-            $this->line->fk_commande=$this->id;
2379
+            $this->line->fk_commande = $this->id;
2380 2380
             //$this->line->label=$label;
2381
-            $this->line->desc=$desc;
2382
-            $this->line->qty=$qty;
2381
+            $this->line->desc = $desc;
2382
+            $this->line->qty = $qty;
2383 2383
 
2384
-	        $this->line->vat_src_code   = $vat_src_code;
2384
+	        $this->line->vat_src_code = $vat_src_code;
2385 2385
             $this->line->tva_tx         = $txtva;
2386 2386
             $this->line->localtax1_tx   = $txlocaltax1;
2387 2387
             $this->line->localtax2_tx   = $txlocaltax2;
@@ -2393,8 +2393,8 @@  discard block
 block discarded – undo
2393 2393
             $this->line->info_bits      = $info_bits;
2394 2394
             $this->line->total_ht       = $total_ht;
2395 2395
             $this->line->total_tva      = $total_tva;
2396
-            $this->line->total_localtax1= $total_localtax1;
2397
-            $this->line->total_localtax2= $total_localtax2;
2396
+            $this->line->total_localtax1 = $total_localtax1;
2397
+            $this->line->total_localtax2 = $total_localtax2;
2398 2398
             $this->line->total_ttc      = $total_ttc;
2399 2399
             $this->line->product_type   = $type;
2400 2400
             $this->line->special_code   = $this->special_code;
@@ -2405,42 +2405,42 @@  discard block
 block discarded – undo
2405 2405
             $this->line->date_end       = $date_end;
2406 2406
 
2407 2407
             // Multicurrency
2408
-            $this->line->fk_multicurrency			= $this->fk_multicurrency;
2409
-            $this->line->multicurrency_code			= $this->multicurrency_code;
2408
+            $this->line->fk_multicurrency = $this->fk_multicurrency;
2409
+            $this->line->multicurrency_code = $this->multicurrency_code;
2410 2410
             $this->line->multicurrency_subprice		= $pu_ht_devise;
2411 2411
             $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2412 2412
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2413 2413
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2414 2414
 
2415
-            $this->line->subprice=$pu_ht;
2416
-            $this->line->price=$this->line->subprice;
2415
+            $this->line->subprice = $pu_ht;
2416
+            $this->line->price = $this->line->subprice;
2417 2417
 
2418
-            $this->line->remise_percent=$remise_percent;
2418
+            $this->line->remise_percent = $remise_percent;
2419 2419
 
2420
-            if (is_array($array_options) && count($array_options)>0) {
2421
-                $this->line->array_options=$array_options;
2420
+            if (is_array($array_options) && count($array_options) > 0) {
2421
+                $this->line->array_options = $array_options;
2422 2422
             }
2423 2423
 
2424
-            $result=$this->line->update($notrigger);
2424
+            $result = $this->line->update($notrigger);
2425 2425
 
2426 2426
 
2427 2427
             // Mise a jour info denormalisees au niveau facture
2428 2428
             if ($result >= 0)
2429 2429
             {
2430
-                $this->update_price('','auto');
2430
+                $this->update_price('', 'auto');
2431 2431
 				$this->db->commit();
2432 2432
 				return $result;
2433 2433
             }
2434 2434
             else
2435 2435
             {
2436
-                $this->error=$this->db->lasterror();
2436
+                $this->error = $this->db->lasterror();
2437 2437
                 $this->db->rollback();
2438 2438
                 return -1;
2439 2439
             }
2440 2440
         }
2441 2441
         else
2442 2442
         {
2443
-            $this->error="Order status makes operation forbidden";
2443
+            $this->error = "Order status makes operation forbidden";
2444 2444
             dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
2445 2445
             return -2;
2446 2446
         }
@@ -2456,20 +2456,20 @@  discard block
 block discarded – undo
2456 2456
      */
2457 2457
     public function initAsSpecimen()
2458 2458
     {
2459
-        global $user,$langs,$conf;
2459
+        global $user, $langs, $conf;
2460 2460
 
2461 2461
         dol_syslog(get_class($this)."::initAsSpecimen");
2462 2462
 
2463
-        $now=dol_now();
2463
+        $now = dol_now();
2464 2464
 
2465 2465
         // Find first product
2466
-        $prodid=0;
2467
-        $product=new ProductFournisseur($this->db);
2466
+        $prodid = 0;
2467
+        $product = new ProductFournisseur($this->db);
2468 2468
         $sql = "SELECT rowid";
2469
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
2470
-        $sql.= " WHERE entity IN (".getEntity('product').")";
2471
-        $sql.=$this->db->order("rowid","ASC");
2472
-        $sql.=$this->db->plimit(1);
2469
+        $sql .= " FROM ".MAIN_DB_PREFIX."product";
2470
+        $sql .= " WHERE entity IN (".getEntity('product').")";
2471
+        $sql .= $this->db->order("rowid", "ASC");
2472
+        $sql .= $this->db->plimit(1);
2473 2473
         $resql = $this->db->query($sql);
2474 2474
         if ($resql)
2475 2475
         {
@@ -2478,49 +2478,49 @@  discard block
 block discarded – undo
2478 2478
         }
2479 2479
 
2480 2480
         // Initialise parametres
2481
-        $this->id=0;
2481
+        $this->id = 0;
2482 2482
         $this->ref = 'SPECIMEN';
2483
-        $this->specimen=1;
2483
+        $this->specimen = 1;
2484 2484
         $this->socid = 1;
2485 2485
         $this->date = $now;
2486 2486
         $this->date_commande = $now;
2487
-        $this->date_lim_reglement=$this->date+3600*24*30;
2487
+        $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
2488 2488
         $this->cond_reglement_code = 'RECEP';
2489 2489
         $this->mode_reglement_code = 'CHQ';
2490
-        $this->note_public='This is a comment (public)';
2491
-        $this->note_private='This is a comment (private)';
2492
-        $this->statut=0;
2490
+        $this->note_public = 'This is a comment (public)';
2491
+        $this->note_private = 'This is a comment (private)';
2492
+        $this->statut = 0;
2493 2493
 
2494 2494
         // Lines
2495 2495
         $nbp = 5;
2496 2496
         $xnbp = 0;
2497 2497
         while ($xnbp < $nbp)
2498 2498
         {
2499
-            $line=new CommandeFournisseurLigne($this->db);
2500
-            $line->desc=$langs->trans("Description")." ".$xnbp;
2501
-            $line->qty=1;
2502
-            $line->subprice=100;
2503
-            $line->price=100;
2504
-            $line->tva_tx=19.6;
2505
-            $line->localtax1_tx=0;
2506
-            $line->localtax2_tx=0;
2499
+            $line = new CommandeFournisseurLigne($this->db);
2500
+            $line->desc = $langs->trans("Description")." ".$xnbp;
2501
+            $line->qty = 1;
2502
+            $line->subprice = 100;
2503
+            $line->price = 100;
2504
+            $line->tva_tx = 19.6;
2505
+            $line->localtax1_tx = 0;
2506
+            $line->localtax2_tx = 0;
2507 2507
             if ($xnbp == 2)
2508 2508
             {
2509
-                $line->total_ht=50;
2510
-                $line->total_ttc=59.8;
2511
-                $line->total_tva=9.8;
2512
-                $line->remise_percent=50;
2509
+                $line->total_ht = 50;
2510
+                $line->total_ttc = 59.8;
2511
+                $line->total_tva = 9.8;
2512
+                $line->remise_percent = 50;
2513 2513
             }
2514 2514
             else
2515 2515
             {
2516
-                $line->total_ht=100;
2517
-                $line->total_ttc=119.6;
2518
-                $line->total_tva=19.6;
2519
-                $line->remise_percent=00;
2516
+                $line->total_ht = 100;
2517
+                $line->total_ttc = 119.6;
2518
+                $line->total_tva = 19.6;
2519
+                $line->remise_percent = 00;
2520 2520
             }
2521
-            $line->fk_product=$prodid;
2521
+            $line->fk_product = $prodid;
2522 2522
 
2523
-            $this->lines[$xnbp]=$line;
2523
+            $this->lines[$xnbp] = $line;
2524 2524
 
2525 2525
             $this->total_ht       += $line->total_ht;
2526 2526
             $this->total_tva      += $line->total_tva;
@@ -2539,11 +2539,11 @@  discard block
 block discarded – undo
2539 2539
     public function info($id)
2540 2540
     {
2541 2541
         $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
2542
-        $sql.= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
2543
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
2544
-        $sql.= ' WHERE c.rowid = '.$id;
2542
+        $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
2543
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
2544
+        $sql .= ' WHERE c.rowid = '.$id;
2545 2545
 
2546
-        $result=$this->db->query($sql);
2546
+        $result = $this->db->query($sql);
2547 2547
         if ($result)
2548 2548
         {
2549 2549
             if ($this->db->num_rows($result))
@@ -2552,7 +2552,7 @@  discard block
 block discarded – undo
2552 2552
                 $this->id = $obj->rowid;
2553 2553
                 if ($obj->fk_user_author)   $this->user_creation_id = $obj->fk_user_author;
2554 2554
                 if ($obj->fk_user_valid)    $this->user_validation_id = $obj->fk_user_valid;
2555
-                if ($obj->fk_user_modif)    $this->user_modification_id =$obj->fk_user_modif;
2555
+                if ($obj->fk_user_modif)    $this->user_modification_id = $obj->fk_user_modif;
2556 2556
                 if ($obj->fk_user_approve)  $this->user_approve_id = $obj->fk_user_approve;
2557 2557
                 if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2;
2558 2558
 
@@ -2579,26 +2579,26 @@  discard block
 block discarded – undo
2579 2579
     {
2580 2580
         global $conf, $user;
2581 2581
 
2582
-        $this->nb=array();
2582
+        $this->nb = array();
2583 2583
         $clause = "WHERE";
2584 2584
 
2585 2585
         $sql = "SELECT count(co.rowid) as nb";
2586
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
2587
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
2586
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
2587
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
2588 2588
         if (!$user->rights->societe->client->voir && !$user->societe_id)
2589 2589
         {
2590
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2591
-            $sql.= " WHERE sc.fk_user = " .$user->id;
2590
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2591
+            $sql .= " WHERE sc.fk_user = ".$user->id;
2592 2592
             $clause = "AND";
2593 2593
         }
2594
-        $sql.= " ".$clause." co.entity = ".$conf->entity;
2594
+        $sql .= " ".$clause." co.entity = ".$conf->entity;
2595 2595
 
2596
-        $resql=$this->db->query($sql);
2596
+        $resql = $this->db->query($sql);
2597 2597
         if ($resql)
2598 2598
         {
2599
-            while ($obj=$this->db->fetch_object($resql))
2599
+            while ($obj = $this->db->fetch_object($resql))
2600 2600
             {
2601
-                $this->nb["supplier_orders"]=$obj->nb;
2601
+                $this->nb["supplier_orders"] = $obj->nb;
2602 2602
             }
2603 2603
             $this->db->free($resql);
2604 2604
             return 1;
@@ -2606,7 +2606,7 @@  discard block
 block discarded – undo
2606 2606
         else
2607 2607
         {
2608 2608
             dol_print_error($this->db);
2609
-            $this->error=$this->db->error();
2609
+            $this->error = $this->db->error();
2610 2610
             return -1;
2611 2611
         }
2612 2612
     }
@@ -2624,29 +2624,29 @@  discard block
 block discarded – undo
2624 2624
         $clause = " WHERE";
2625 2625
 
2626 2626
         $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date";
2627
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
2627
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
2628 2628
         if (!$user->rights->societe->client->voir && !$user->societe_id)
2629 2629
         {
2630
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
2631
-            $sql.= " WHERE sc.fk_user = " .$user->id;
2630
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
2631
+            $sql .= " WHERE sc.fk_user = ".$user->id;
2632 2632
             $clause = " AND";
2633 2633
         }
2634
-        $sql.= $clause." c.entity = ".$conf->entity;
2635
-        $sql.= " AND (c.fk_statut BETWEEN 1 AND 2)";
2636
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2634
+        $sql .= $clause." c.entity = ".$conf->entity;
2635
+        $sql .= " AND (c.fk_statut BETWEEN 1 AND 2)";
2636
+        if ($user->societe_id) $sql .= " AND c.fk_soc = ".$user->societe_id;
2637 2637
 
2638
-        $resql=$this->db->query($sql);
2638
+        $resql = $this->db->query($sql);
2639 2639
         if ($resql)
2640 2640
         {
2641 2641
             $commandestatic = new CommandeFournisseur($this->db);
2642 2642
 
2643 2643
 	        $response = new WorkboardResponse();
2644
-	        $response->warning_delay=$conf->commande->fournisseur->warning_delay/60/60/24;
2645
-	        $response->label=$langs->trans("SuppliersOrdersToProcess");
2646
-	        $response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2,3&mainmenu=commercial&leftmenu=orders_suppliers';
2647
-	        $response->img=img_object('',"order");
2644
+	        $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
2645
+	        $response->label = $langs->trans("SuppliersOrdersToProcess");
2646
+	        $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2,3&mainmenu=commercial&leftmenu=orders_suppliers';
2647
+	        $response->img = img_object('', "order");
2648 2648
 
2649
-            while ($obj=$this->db->fetch_object($resql))
2649
+            while ($obj = $this->db->fetch_object($resql))
2650 2650
             {
2651 2651
                 $response->nbtodo++;
2652 2652
 
@@ -2663,7 +2663,7 @@  discard block
 block discarded – undo
2663 2663
         }
2664 2664
         else
2665 2665
         {
2666
-            $this->error=$this->db->error();
2666
+            $this->error = $this->db->error();
2667 2667
             return -1;
2668 2668
         }
2669 2669
     }
@@ -2681,8 +2681,8 @@  discard block
 block discarded – undo
2681 2681
         if ($this->methode_commande_id > 0)
2682 2682
         {
2683 2683
             $sql = "SELECT rowid, code, libelle as label";
2684
-            $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_method';
2685
-            $sql.= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
2684
+            $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_method';
2685
+            $sql .= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
2686 2686
 
2687 2687
             $resql = $db->query($sql);
2688 2688
             if ($resql)
@@ -2715,19 +2715,19 @@  discard block
 block discarded – undo
2715 2715
 	 *  @param      int			$hideref        Hide ref
2716 2716
 	 *  @return     int          				0 if KO, 1 if OK
2717 2717
 	 */
2718
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
2718
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2719 2719
 	{
2720 2720
 		global $conf, $langs;
2721 2721
 
2722 2722
 		$langs->load("suppliers");
2723 2723
 
2724
-		if (! dol_strlen($modele)) {
2724
+		if (!dol_strlen($modele)) {
2725 2725
 
2726 2726
 			$modele = 'muscadet';
2727 2727
 
2728 2728
 			if ($this->modelpdf) {
2729 2729
 				$modele = $this->modelpdf;
2730
-			} elseif (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
2730
+			} elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
2731 2731
 				$modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF;
2732 2732
 			}
2733 2733
 		}
@@ -2805,7 +2805,7 @@  discard block
 block discarded – undo
2805 2805
     {
2806 2806
         global $conf;
2807 2807
 
2808
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2808
+        if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility
2809 2809
 
2810 2810
         $now = dol_now();
2811 2811
         $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery;
@@ -2822,11 +2822,11 @@  discard block
 block discarded – undo
2822 2822
     {
2823 2823
         global $conf, $langs;
2824 2824
 
2825
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2825
+        if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility
2826 2826
 
2827
-        if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2828
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2829
-        $text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
2827
+        if (empty($this->date_delivery)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2828
+        else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2829
+        $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
2830 2830
 
2831 2831
         return $text;
2832 2832
     }
@@ -2840,46 +2840,46 @@  discard block
 block discarded – undo
2840 2840
      * @param		string	$comment				Comment
2841 2841
      * @return		int		                        <0 if KO, 0 if not applicable, >0 if OK
2842 2842
      */
2843
-    public function calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
2843
+    public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '')
2844 2844
     {
2845 2845
     	global $conf, $langs;
2846 2846
 
2847
-    	if (! empty($conf->fournisseur->enabled))
2847
+    	if (!empty($conf->fournisseur->enabled))
2848 2848
     	{
2849 2849
     		require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
2850 2850
 
2851
-    		$qtydelivered=array();
2852
-    		$qtywished=array();
2851
+    		$qtydelivered = array();
2852
+    		$qtywished = array();
2853 2853
 
2854 2854
     		$supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
2855
-    		$filter=array('t.fk_commande'=>$this->id);
2856
-    		if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2857
-    			$filter['t.status']=1;	// Restrict to lines with status validated
2855
+    		$filter = array('t.fk_commande'=>$this->id);
2856
+    		if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2857
+    			$filter['t.status'] = 1; // Restrict to lines with status validated
2858 2858
     		}
2859 2859
 
2860
-    		$ret=$supplierorderdispatch->fetchAll('','',0,0,$filter);
2861
-    		if ($ret<0)
2860
+    		$ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
2861
+    		if ($ret < 0)
2862 2862
     		{
2863
-    			$this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors;
2863
+    			$this->error = $supplierorderdispatch->error; $this->errors = $supplierorderdispatch->errors;
2864 2864
     			return $ret;
2865 2865
     		}
2866 2866
     		else
2867 2867
     		{
2868
-    			if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0)
2868
+    			if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0)
2869 2869
     			{
2870 2870
     				$date_liv = dol_now();
2871 2871
 
2872 2872
     				// Build array with quantity deliverd by product
2873
-    				foreach($supplierorderdispatch->lines as $line) {
2874
-    					$qtydelivered[$line->fk_product]+=$line->qty;
2873
+    				foreach ($supplierorderdispatch->lines as $line) {
2874
+    					$qtydelivered[$line->fk_product] += $line->qty;
2875 2875
     				}
2876
-    				foreach($this->lines as $line) {
2877
-    					$qtywished[$line->fk_product]+=$line->qty;
2876
+    				foreach ($this->lines as $line) {
2877
+    					$qtywished[$line->fk_product] += $line->qty;
2878 2878
     				}
2879 2879
     				//Compare array
2880
-    				$diff_array=array_diff_assoc($qtydelivered,$qtywished);		// Warning: $diff_array is done only on common keys.
2881
-    				$keysinwishednotindelivered=array_diff(array_keys($qtywished),array_keys($qtydelivered));		// To check we also have same number of keys
2882
-    				$keysindeliverednotinwished=array_diff(array_keys($qtydelivered),array_keys($qtywished));		// To check we also have same number of keys
2880
+    				$diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys.
2881
+    				$keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys
2882
+    				$keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys
2883 2883
     				/*var_dump(array_keys($qtydelivered));
2884 2884
     				var_dump(array_keys($qtywished));
2885 2885
     				var_dump($diff_array);
@@ -2887,13 +2887,13 @@  discard block
 block discarded – undo
2887 2887
     				var_dump($keysindeliverednotinwished);
2888 2888
     				exit;*/
2889 2889
 
2890
-    				if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received
2890
+    				if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) //No diff => mean everythings is received
2891 2891
     				{
2892 2892
     					if ($closeopenorder)
2893 2893
     					{
2894 2894
         					//$ret=$this->setStatus($user,5);
2895
-    						$ret = $this->Livraison($user, $date_liv, 'tot', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2896
-        					if ($ret<0) {
2895
+    						$ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2896
+        					if ($ret < 0) {
2897 2897
         						return -1;
2898 2898
         					}
2899 2899
     					    return 5;
@@ -2902,8 +2902,8 @@  discard block
 block discarded – undo
2902 2902
     					{
2903 2903
     					    //Diff => received partially
2904 2904
     					    //$ret=$this->setStatus($user,4);
2905
-    						$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2906
-    					    if ($ret<0) {
2905
+    						$ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2906
+    					    if ($ret < 0) {
2907 2907
     					        return -1;
2908 2908
     					    }
2909 2909
     					    return 4;
@@ -2912,8 +2912,8 @@  discard block
 block discarded – undo
2912 2912
     				else
2913 2913
     				{
2914 2914
     					//Diff => received partially
2915
-    					$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2916
-    					if ($ret<0) {
2915
+    					$ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
2916
+    					if ($ret < 0) {
2917 2917
     						return -1;
2918 2918
     					}
2919 2919
     					return 4;
@@ -2933,8 +2933,8 @@  discard block
 block discarded – undo
2933 2933
  */
2934 2934
 class CommandeFournisseurLigne extends CommonOrderLine
2935 2935
 {
2936
-    public $element='commande_fournisseurdet';
2937
-	public $table_element='commande_fournisseurdet';
2936
+    public $element = 'commande_fournisseurdet';
2937
+	public $table_element = 'commande_fournisseurdet';
2938 2938
 
2939 2939
     public $oldline;
2940 2940
 
@@ -2977,7 +2977,7 @@  discard block
 block discarded – undo
2977 2977
      */
2978 2978
     public function __construct($db)
2979 2979
     {
2980
-        $this->db= $db;
2980
+        $this->db = $db;
2981 2981
     }
2982 2982
 
2983 2983
     /**
@@ -2989,16 +2989,16 @@  discard block
 block discarded – undo
2989 2989
     public function fetch($rowid)
2990 2990
     {
2991 2991
         $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx,';
2992
-        $sql.= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,';
2993
-        $sql.= ' cd.remise, cd.remise_percent, cd.subprice,';
2994
-        $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
2995
-        $sql.= ' cd.total_localtax1, cd.total_localtax2,';
2996
-        $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,';
2997
-        $sql.= ' cd.date_start, cd.date_end, cd.fk_unit,';
2998
-		$sql.= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc';
2999
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3000
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3001
-        $sql.= ' WHERE cd.rowid = '.$rowid;
2992
+        $sql .= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,';
2993
+        $sql .= ' cd.remise, cd.remise_percent, cd.subprice,';
2994
+        $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
2995
+        $sql .= ' cd.total_localtax1, cd.total_localtax2,';
2996
+        $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,';
2997
+        $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,';
2998
+		$sql .= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc';
2999
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3000
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3001
+        $sql .= ' WHERE cd.rowid = '.$rowid;
3002 3002
         $result = $this->db->query($sql);
3003 3003
         if ($result)
3004 3004
         {
@@ -3028,14 +3028,14 @@  discard block
 block discarded – undo
3028 3028
             $this->total_ttc        = $objp->total_ttc;
3029 3029
             $this->product_type     = $objp->product_type;
3030 3030
 
3031
-            $this->ref	            = $objp->product_ref;
3031
+            $this->ref = $objp->product_ref;
3032 3032
             $this->product_ref      = $objp->product_ref;
3033 3033
             $this->product_libelle  = $objp->product_libelle;
3034 3034
             $this->product_desc     = $objp->product_desc;
3035 3035
 
3036 3036
             $this->date_start       		= $this->db->jdate($objp->date_start);
3037 3037
             $this->date_end         		= $this->db->jdate($objp->date_end);
3038
-	        $this->fk_unit          		= $objp->fk_unit;
3038
+	        $this->fk_unit = $objp->fk_unit;
3039 3039
 
3040 3040
 			$this->multicurrency_subprice	= $objp->multicurrency_subprice;
3041 3041
 			$this->multicurrency_total_ht	= $objp->multicurrency_total_ht;
@@ -3063,16 +3063,16 @@  discard block
 block discarded – undo
3063 3063
 
3064 3064
         // Mise a jour ligne en base
3065 3065
         $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseurdet SET";
3066
-        $sql.= " total_ht='".price2num($this->total_ht)."'";
3067
-        $sql.= ",total_tva='".price2num($this->total_tva)."'";
3068
-        $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
3069
-        $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
3070
-        $sql.= ",total_ttc='".price2num($this->total_ttc)."'";
3071
-        $sql.= " WHERE rowid = ".$this->rowid;
3066
+        $sql .= " total_ht='".price2num($this->total_ht)."'";
3067
+        $sql .= ",total_tva='".price2num($this->total_tva)."'";
3068
+        $sql .= ",total_localtax1='".price2num($this->total_localtax1)."'";
3069
+        $sql .= ",total_localtax2='".price2num($this->total_localtax2)."'";
3070
+        $sql .= ",total_ttc='".price2num($this->total_ttc)."'";
3071
+        $sql .= " WHERE rowid = ".$this->rowid;
3072 3072
 
3073 3073
         dol_syslog(get_class($this)."::updateTotal", LOG_DEBUG);
3074 3074
 
3075
-        $resql=$this->db->query($sql);
3075
+        $resql = $this->db->query($sql);
3076 3076
         if ($resql)
3077 3077
         {
3078 3078
             $this->db->commit();
@@ -3080,7 +3080,7 @@  discard block
 block discarded – undo
3080 3080
         }
3081 3081
         else
3082 3082
         {
3083
-            $this->error=$this->db->error();
3083
+            $this->error = $this->db->error();
3084 3084
             $this->db->rollback();
3085 3085
             return -2;
3086 3086
         }
@@ -3092,32 +3092,32 @@  discard block
 block discarded – undo
3092 3092
      *	@param      int		$notrigger		1 = disable triggers
3093 3093
      *	@return		int						<0 if KO, >0 if OK
3094 3094
      */
3095
-    public function insert($notrigger=0)
3095
+    public function insert($notrigger = 0)
3096 3096
     {
3097 3097
         global $conf, $user;
3098 3098
 
3099
-        $error=0;
3099
+        $error = 0;
3100 3100
 
3101 3101
         dol_syslog(get_class($this)."::insert rang=".$this->rang);
3102 3102
 
3103 3103
         // Clean parameters
3104
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3105
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3106
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3107
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
3108
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
3109
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3110
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3111
-        if (empty($this->rang)) $this->rang=0;
3112
-        if (empty($this->remise)) $this->remise=0;
3113
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3114
-        if (empty($this->info_bits)) $this->info_bits=0;
3115
-        if (empty($this->special_code)) $this->special_code=0;
3116
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3117
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3104
+        if (empty($this->tva_tx)) $this->tva_tx = 0;
3105
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
3106
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
3107
+        if (empty($this->localtax1_type)) $this->localtax1_type = '0';
3108
+        if (empty($this->localtax2_type)) $this->localtax2_type = '0';
3109
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
3110
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
3111
+        if (empty($this->rang)) $this->rang = 0;
3112
+        if (empty($this->remise)) $this->remise = 0;
3113
+        if (empty($this->remise_percent)) $this->remise_percent = 0;
3114
+        if (empty($this->info_bits)) $this->info_bits = 0;
3115
+        if (empty($this->special_code)) $this->special_code = 0;
3116
+        if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
3117
+        if (empty($this->pa_ht)) $this->pa_ht = 0;
3118 3118
 
3119 3119
         // Multicurrency
3120
-        if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3120
+        if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3121 3121
         if (empty($this->fk_multicurrency))
3122 3122
         {
3123 3123
             $this->multicurrency_code = $conf->currency;
@@ -3132,62 +3132,62 @@  discard block
 block discarded – undo
3132 3132
 
3133 3133
         // Insertion dans base de la ligne
3134 3134
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
3135
-        $sql.= " (fk_commande, label, description, date_start, date_end,";
3136
-        $sql.= " fk_product, product_type,";
3137
-        $sql.= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3138
-        $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3139
-        $sql.= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3140
-        $sql.= ")";
3141
-        $sql.= " VALUES (".$this->fk_commande.", '" . $this->db->escape($this->label) . "','" . $this->db->escape($this->desc) . "',";
3142
-        $sql.= " ".($this->date_start?"'".$this->db->idate($this->date_start)."'":"null").",";
3143
-        $sql.= " ".($this->date_end?"'".$this->db->idate($this->date_end)."'":"null").",";
3144
-        if ($this->fk_product) { $sql.= $this->fk_product.","; }
3145
-        else { $sql.= "null,"; }
3146
-        $sql.= "'".$this->db->escape($this->product_type)."',";
3147
-        $sql.= "'".$this->db->escape($this->qty)."', ";
3148
-
3149
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3150
-        $sql.= " ".$this->tva_tx.", ";
3151
-        $sql.= " ".$this->localtax1_tx.",";
3152
-        $sql.= " ".$this->localtax2_tx.",";
3153
-        $sql.= " '".$this->db->escape($this->localtax1_type)."',";
3154
-        $sql.= " '".$this->db->escape($this->localtax2_type)."',";
3155
-        $sql.= " ".$this->remise_percent.", ".price2num($this->subprice,'MU').", '".$this->db->escape($this->ref_supplier)."',";
3156
-        $sql.= " ".price2num($this->total_ht).",";
3157
-        $sql.= " ".price2num($this->total_tva).",";
3158
-        $sql.= " ".price2num($this->total_localtax1).",";
3159
-        $sql.= " ".price2num($this->total_localtax2).",";
3160
-        $sql.= " ".price2num($this->total_ttc).",";
3161
-        $sql.= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'":"null");
3162
-        $sql.= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null");
3163
-        $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3164
-        $sql.= ", ".price2num($this->multicurrency_subprice);
3165
-        $sql.= ", ".price2num($this->multicurrency_total_ht);
3166
-        $sql.= ", ".price2num($this->multicurrency_total_tva);
3167
-        $sql.= ", ".price2num($this->multicurrency_total_ttc);
3168
-        $sql.= ")";
3135
+        $sql .= " (fk_commande, label, description, date_start, date_end,";
3136
+        $sql .= " fk_product, product_type,";
3137
+        $sql .= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3138
+        $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3139
+        $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3140
+        $sql .= ")";
3141
+        $sql .= " VALUES (".$this->fk_commande.", '".$this->db->escape($this->label)."','".$this->db->escape($this->desc)."',";
3142
+        $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3143
+        $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3144
+        if ($this->fk_product) { $sql .= $this->fk_product.","; }
3145
+        else { $sql .= "null,"; }
3146
+        $sql .= "'".$this->db->escape($this->product_type)."',";
3147
+        $sql .= "'".$this->db->escape($this->qty)."', ";
3148
+
3149
+        $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
3150
+        $sql .= " ".$this->tva_tx.", ";
3151
+        $sql .= " ".$this->localtax1_tx.",";
3152
+        $sql .= " ".$this->localtax2_tx.",";
3153
+        $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3154
+        $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3155
+        $sql .= " ".$this->remise_percent.", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',";
3156
+        $sql .= " ".price2num($this->total_ht).",";
3157
+        $sql .= " ".price2num($this->total_tva).",";
3158
+        $sql .= " ".price2num($this->total_localtax1).",";
3159
+        $sql .= " ".price2num($this->total_localtax2).",";
3160
+        $sql .= " ".price2num($this->total_ttc).",";
3161
+        $sql .= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null");
3162
+        $sql .= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null");
3163
+        $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
3164
+        $sql .= ", ".price2num($this->multicurrency_subprice);
3165
+        $sql .= ", ".price2num($this->multicurrency_total_ht);
3166
+        $sql .= ", ".price2num($this->multicurrency_total_tva);
3167
+        $sql .= ", ".price2num($this->multicurrency_total_ttc);
3168
+        $sql .= ")";
3169 3169
 
3170 3170
         dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3171
-        $resql=$this->db->query($sql);
3171
+        $resql = $this->db->query($sql);
3172 3172
         if ($resql)
3173 3173
         {
3174
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3175
-            $this->rowid =$this->id;
3174
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3175
+            $this->rowid = $this->id;
3176 3176
 
3177 3177
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3178 3178
             {
3179 3179
 
3180
-                $result=$this->insertExtraFields();
3180
+                $result = $this->insertExtraFields();
3181 3181
                 if ($result < 0)
3182 3182
                 {
3183 3183
                     $error++;
3184 3184
                 }
3185 3185
             }
3186 3186
 
3187
-            if (! $error && ! $notrigger)
3187
+            if (!$error && !$notrigger)
3188 3188
             {
3189 3189
                 // Call trigger
3190
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user);
3190
+                $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user);
3191 3191
                 if ($result < 0) $error++;
3192 3192
                 // End call triggers
3193 3193
             }
@@ -3197,17 +3197,17 @@  discard block
 block discarded – undo
3197 3197
                 return 1;
3198 3198
             }
3199 3199
 
3200
-            foreach($this->errors as $errmsg)
3200
+            foreach ($this->errors as $errmsg)
3201 3201
             {
3202 3202
                 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3203
-                $this->errors[]=($this->errors?', '.$errmsg:$errmsg);
3203
+                $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg);
3204 3204
             }
3205 3205
             $this->db->rollback();
3206
-            return -1*$error;
3206
+            return -1 * $error;
3207 3207
         }
3208 3208
         else
3209 3209
         {
3210
-            $this->errors[]=$this->db->error();
3210
+            $this->errors[] = $this->db->error();
3211 3211
             $this->db->rollback();
3212 3212
             return -2;
3213 3213
         }
@@ -3218,44 +3218,44 @@  discard block
 block discarded – undo
3218 3218
      *	@param      int		$notrigger		1 = disable triggers
3219 3219
      *	@return		int		<0 si ko, >0 si ok
3220 3220
      */
3221
-    public function update($notrigger=0)
3221
+    public function update($notrigger = 0)
3222 3222
     {
3223
-        global $conf,$user;
3223
+        global $conf, $user;
3224 3224
 
3225
-        $error=0;
3225
+        $error = 0;
3226 3226
 
3227 3227
         // Mise a jour ligne en base
3228 3228
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3229
-        $sql.= "  description='".$this->db->escape($this->desc)."'";
3230
-        $sql.= ", subprice='".price2num($this->subprice)."'";
3229
+        $sql .= "  description='".$this->db->escape($this->desc)."'";
3230
+        $sql .= ", subprice='".price2num($this->subprice)."'";
3231 3231
         //$sql.= ",remise='".price2num($remise)."'";
3232
-        $sql.= ", remise_percent='".price2num($this->remise_percent)."'";
3233
-
3234
-		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
3235
-        $sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3236
-        $sql.= ", localtax1_tx='".price2num($this->total_localtax1)."'";
3237
-        $sql.= ", localtax2_tx='".price2num($this->total_localtax2)."'";
3238
-        $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3239
-        $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3240
-        $sql.= ", qty='".price2num($this->qty)."'";
3241
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3242
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3243
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3244
-        $sql.= ", total_ht='".price2num($this->total_ht)."'";
3245
-        $sql.= ", total_tva='".price2num($this->total_tva)."'";
3246
-        $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
3247
-        $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
3248
-        $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
3249
-        $sql.= ", product_type=".$this->product_type;
3250
-        $sql.= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'":", fk_unit=null");
3232
+        $sql .= ", remise_percent='".price2num($this->remise_percent)."'";
3233
+
3234
+		$sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
3235
+        $sql .= ", tva_tx='".price2num($this->tva_tx)."'";
3236
+        $sql .= ", localtax1_tx='".price2num($this->total_localtax1)."'";
3237
+        $sql .= ", localtax2_tx='".price2num($this->total_localtax2)."'";
3238
+        $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3239
+        $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3240
+        $sql .= ", qty='".price2num($this->qty)."'";
3241
+        $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
3242
+        $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
3243
+        $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
3244
+        $sql .= ", total_ht='".price2num($this->total_ht)."'";
3245
+        $sql .= ", total_tva='".price2num($this->total_tva)."'";
3246
+        $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'";
3247
+        $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'";
3248
+        $sql .= ", total_ttc='".price2num($this->total_ttc)."'";
3249
+        $sql .= ", product_type=".$this->product_type;
3250
+        $sql .= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'" : ", fk_unit=null");
3251 3251
 
3252 3252
         // Multicurrency
3253
-        $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3254
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3255
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3256
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3253
+        $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3254
+        $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3255
+        $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3256
+        $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3257 3257
 
3258
-        $sql.= " WHERE rowid = ".$this->id;
3258
+        $sql .= " WHERE rowid = ".$this->id;
3259 3259
 
3260 3260
         dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
3261 3261
         $result = $this->db->query($sql);
@@ -3264,18 +3264,18 @@  discard block
 block discarded – undo
3264 3264
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3265 3265
             {
3266 3266
 
3267
-                $result=$this->insertExtraFields();
3267
+                $result = $this->insertExtraFields();
3268 3268
                 if ($result < 0)
3269 3269
                 {
3270 3270
                     $error++;
3271 3271
                 }
3272 3272
             }
3273 3273
 
3274
-            if (! $error && ! $notrigger)
3274
+            if (!$error && !$notrigger)
3275 3275
             {
3276 3276
                 global $user;
3277 3277
                 // Call trigger
3278
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE',$user);
3278
+                $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user);
3279 3279
                 if ($result < 0)
3280 3280
                 {
3281 3281
                     $this->db->rollback();
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                 // End call triggers
3285 3285
             }
3286 3286
 
3287
-            if (! $error)
3287
+            if (!$error)
3288 3288
             {
3289 3289
                 $this->db->commit();
3290 3290
                 return $result;
@@ -3297,7 +3297,7 @@  discard block
 block discarded – undo
3297 3297
         }
3298 3298
         else
3299 3299
         {
3300
-            $this->error=$this->db->lasterror();
3300
+            $this->error = $this->db->lasterror();
3301 3301
             $this->db->rollback();
3302 3302
             return -1;
3303 3303
         }
@@ -3313,21 +3313,21 @@  discard block
 block discarded – undo
3313 3313
     {
3314 3314
         global $user;
3315 3315
 
3316
-        $error=0;
3316
+        $error = 0;
3317 3317
 
3318 3318
         $this->db->begin();
3319 3319
 
3320 3320
         $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->rowid;
3321 3321
 
3322 3322
         dol_syslog(__METHOD__, LOG_DEBUG);
3323
-        $resql=$this->db->query($sql);
3323
+        $resql = $this->db->query($sql);
3324 3324
         if ($resql)
3325 3325
         {
3326 3326
 
3327 3327
             if (!$notrigger)
3328 3328
             {
3329 3329
                 // Call trigger
3330
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user);
3330
+                $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user);
3331 3331
                 if ($result < 0) $error++;
3332 3332
                 // End call triggers
3333 3333
             }
@@ -3338,17 +3338,17 @@  discard block
 block discarded – undo
3338 3338
                 return 1;
3339 3339
             }
3340 3340
 
3341
-            foreach($this->errors as $errmsg)
3341
+            foreach ($this->errors as $errmsg)
3342 3342
             {
3343 3343
                 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3344
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
3344
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3345 3345
             }
3346 3346
             $this->db->rollback();
3347
-            return -1*$error;
3347
+            return -1 * $error;
3348 3348
         }
3349 3349
         else
3350 3350
         {
3351
-            $this->error=$this->db->lasterror();
3351
+            $this->error = $this->db->lasterror();
3352 3352
             return -1;
3353 3353
         }
3354 3354
     }
Please login to merge, or discard this patch.
Braces   +469 added lines, -271 removed lines patch added patch discarded remove patch
@@ -31,7 +31,9 @@  discard block
 block discarded – undo
31 31
 
32 32
 include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
33 33
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
34
-if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
34
+if (! empty($conf->productbatch->enabled)) {
35
+	require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
36
+}
35 37
 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
36 38
 
37 39
 /**
@@ -151,8 +153,11 @@  discard block
 block discarded – undo
151 153
         $this->statuts[0] = 'StatusOrderDraft';
152 154
         $this->statuts[1] = 'StatusOrderValidated';
153 155
         $this->statuts[2] = 'StatusOrderApproved';
154
-        if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusOrderOnProcess';
155
-        else $this->statuts[3] = 'StatusOrderOnProcessWithValidation';
156
+        if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
157
+        	$this->statuts[3] = 'StatusOrderOnProcess';
158
+        } else {
159
+        	$this->statuts[3] = 'StatusOrderOnProcessWithValidation';
160
+        }
156 161
         $this->statuts[4] = 'StatusOrderReceivedPartially';
157 162
         $this->statuts[5] = 'StatusOrderReceivedAll';
158 163
         $this->statuts[6] = 'StatusOrderCanceled';	// Approved->Canceled
@@ -174,7 +179,9 @@  discard block
 block discarded – undo
174 179
         global $conf;
175 180
 
176 181
         // Check parameters
177
-        if (empty($id) && empty($ref)) return -1;
182
+        if (empty($id) && empty($ref)) {
183
+        	return -1;
184
+        }
178 185
 
179 186
         $sql = "SELECT c.rowid, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,";
180 187
         $sql.= " c.localtax1, c.localtax2, ";
@@ -195,8 +202,11 @@  discard block
 block discarded – undo
195 202
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
196 203
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
197 204
         $sql.= " WHERE c.entity = ".$conf->entity;
198
-        if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
199
-        else $sql.= " AND c.rowid=".$id;
205
+        if ($ref) {
206
+        	$sql.= " AND c.ref='".$this->db->escape($ref)."'";
207
+        } else {
208
+        	$sql.= " AND c.rowid=".$id;
209
+        }
200 210
 
201 211
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
202 212
         $resql = $this->db->query($sql);
@@ -275,7 +285,9 @@  discard block
 block discarded – undo
275 285
             $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
276 286
             $this->fetch_optionals($this->id,$extralabels);
277 287
 
278
-            if ($this->statut == 0) $this->brouillon = 1;
288
+            if ($this->statut == 0) {
289
+            	$this->brouillon = 1;
290
+            }
279 291
 
280 292
 			$this->fetchObjectLinked();
281 293
 
@@ -365,14 +377,12 @@  discard block
 block discarded – undo
365 377
                 $this->db->free($result);
366 378
 
367 379
                 return 1;
368
-            }
369
-            else
380
+            } else
370 381
             {
371 382
                 $this->error=$this->db->error()." sql=".$sql;
372 383
                 return -1;
373 384
             }
374
-        }
375
-        else
385
+        } else
376 386
         {
377 387
             $this->error=$this->db->error()." sql=".$sql;
378 388
             return -1;
@@ -406,11 +416,12 @@  discard block
 block discarded – undo
406 416
             $soc->fetch($this->fourn_id);
407 417
 
408 418
             // Check if object has a temporary ref
409
-            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
419
+            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) {
420
+            	// empty should not happened, but when it occurs, the test save life
410 421
             {
411 422
                 $num = $this->getNextNumRef($soc);
412 423
             }
413
-            else
424
+            } else
414 425
 			{
415 426
                 $num = $this->ref;
416 427
             }
@@ -435,7 +446,9 @@  discard block
 block discarded – undo
435 446
             {
436 447
 				// Call trigger
437 448
 				$result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE',$user);
438
-				if ($result < 0) $error++;
449
+				if ($result < 0) {
450
+					$error++;
451
+				}
439 452
 				// End call triggers
440 453
             }
441 454
 
@@ -485,14 +498,12 @@  discard block
 block discarded – undo
485 498
             {
486 499
                 $this->db->commit();
487 500
                 return 1;
488
-            }
489
-            else
501
+            } else
490 502
             {
491 503
                 $this->db->rollback();
492 504
                 return -1;
493 505
             }
494
-        }
495
-        else
506
+        } else
496 507
         {
497 508
             $this->error='NotAuthorized';
498 509
             dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
@@ -526,7 +537,9 @@  discard block
 block discarded – undo
526 537
 
527 538
         $billedtext='';
528 539
 		//if ($statut==5 && $this->billed == 1) $statut = 8;
529
-        if ($billed == 1) $billedtext=$langs->trans("Billed");
540
+        if ($billed == 1) {
541
+        	$billedtext=$langs->trans("Billed");
542
+        }
530 543
 
531 544
         // List of language codes for status
532 545
         $statutshort[0] = 'StatusOrderDraftShort';
@@ -554,39 +567,93 @@  discard block
 block discarded – undo
554 567
         }
555 568
         if ($mode == 3)
556 569
         {
557
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
558
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1');
559
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
560
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
561
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
562
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
563
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
564
-			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
565
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
570
+            if ($statut==0) {
571
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut0');
572
+            }
573
+            if ($statut==1) {
574
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut1');
575
+            }
576
+            if ($statut==2) {
577
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3');
578
+            }
579
+            if ($statut==3) {
580
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3');
581
+            }
582
+            if ($statut==4) {
583
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3');
584
+            }
585
+            if ($statut==5) {
586
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut6');
587
+            }
588
+            if ($statut==6 || $statut==7) {
589
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut5');
590
+            }
591
+			if ($statut==8) {
592
+				return img_picto($langs->trans($this->statuts[$statut]),'statut6');
593
+			}
594
+            if ($statut==9) {
595
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut5');
596
+            }
566 597
         }
567 598
         if ($mode == 4)
568 599
         {
569
-            if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
570
-            if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
571
-            if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
572
-            if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
573
-            if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
574
-            if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
575
-            if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
576
-			if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
577
-            if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
600
+            if ($statut==0) {
601
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
602
+            }
603
+            if ($statut==1) {
604
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
605
+            }
606
+            if ($statut==2) {
607
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
608
+            }
609
+            if ($statut==3) {
610
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
611
+            }
612
+            if ($statut==4) {
613
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
614
+            }
615
+            if ($statut==5) {
616
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
617
+            }
618
+            if ($statut==6 || $statut==7) {
619
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
620
+            }
621
+			if ($statut==8) {
622
+				return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
623
+			}
624
+            if ($statut==9) {
625
+            	return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
626
+            }
578 627
         }
579 628
         if ($mode == 5)
580 629
         {
581
-            if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
582
-            if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
583
-            if ($statut==2) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
584
-            if ($statut==3) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
585
-            if ($statut==4) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
586
-            if ($statut==5) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
587
-            if ($statut==6 || $statut==7) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
588
-            if ($statut==8) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
589
-            if ($statut==9) return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
630
+            if ($statut==0) {
631
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
632
+            }
633
+            if ($statut==1) {
634
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
635
+            }
636
+            if ($statut==2) {
637
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
638
+            }
639
+            if ($statut==3) {
640
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
641
+            }
642
+            if ($statut==4) {
643
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
644
+            }
645
+            if ($statut==5) {
646
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
647
+            }
648
+            if ($statut==6 || $statut==7) {
649
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
650
+            }
651
+            if ($statut==8) {
652
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
653
+            }
654
+            if ($statut==9) {
655
+            	return '<span class="hideonsmartphone">'.$langs->trans($statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
656
+            }
590 657
         }
591 658
     }
592 659
 
@@ -606,16 +673,21 @@  discard block
 block discarded – undo
606 673
 
607 674
         $result='';
608 675
         $label = '<u>' . $langs->trans("ShowOrder") . '</u>';
609
-        if (! empty($this->ref))
610
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
611
-        if (! empty($this->ref_supplier))
612
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
613
-        if (! empty($this->total_ht))
614
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
615
-        if (! empty($this->total_tva))
616
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
617
-        if (! empty($this->total_ttc))
618
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
676
+        if (! empty($this->ref)) {
677
+                    $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
678
+        }
679
+        if (! empty($this->ref_supplier)) {
680
+                    $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
681
+        }
682
+        if (! empty($this->total_ht)) {
683
+                    $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
684
+        }
685
+        if (! empty($this->total_tva)) {
686
+                    $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
687
+        }
688
+        if (! empty($this->total_ttc)) {
689
+                    $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
690
+        }
619 691
 
620 692
         $picto='order';
621 693
         $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
@@ -624,8 +696,12 @@  discard block
 block discarded – undo
624 696
         {
625 697
         	// Add param to save lastsearch_values or not
626 698
         	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
627
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
628
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
699
+        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
700
+        		$add_save_lastsearch_values=1;
701
+        	}
702
+        	if ($add_save_lastsearch_values) {
703
+        		$url.='&save_lastsearch_values=1';
704
+        	}
629 705
         }
630 706
 
631 707
         $linkclose='';
@@ -644,8 +720,12 @@  discard block
 block discarded – undo
644 720
         $linkstart.=$linkclose.'>';
645 721
         $linkend='</a>';
646 722
 
647
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
648
-        if ($withpicto && $withpicto != 2) $result.=' ';
723
+        if ($withpicto) {
724
+        	$result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
725
+        }
726
+        if ($withpicto && $withpicto != 2) {
727
+        	$result.=' ';
728
+        }
649 729
         $result.=$linkstart.$this->ref.$linkend;
650 730
         return $result;
651 731
     }
@@ -693,14 +773,12 @@  discard block
 block discarded – undo
693 773
             if ( $numref != "")
694 774
             {
695 775
                 return $numref;
696
-            }
697
-            else
776
+            } else
698 777
 			{
699 778
                 $this->error = $obj->error;
700 779
                 return -1;
701 780
             }
702
-        }
703
-        else
781
+        } else
704 782
 		{
705 783
             $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
706 784
             return -2;
@@ -725,7 +803,9 @@  discard block
 block discarded – undo
725 803
         	{
726 804
         	    // Call trigger
727 805
         	    $result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED',$user);
728
-        	    if ($result < 0) $error++;
806
+        	    if ($result < 0) {
807
+        	    	$error++;
808
+        	    }
729 809
         	    // End call triggers
730 810
         	}
731 811
 
@@ -735,14 +815,12 @@  discard block
 block discarded – undo
735 815
 
736 816
         	    $this->db->commit();
737 817
         	    return 1;
738
-        	}
739
-        	else
818
+        	} else
740 819
         	{
741 820
         	    $this->db->rollback();
742 821
                 return -1;
743 822
         	}
744
-        }
745
-        else
823
+        } else
746 824
         {
747 825
         	dol_print_error($this->db);
748 826
 
@@ -779,11 +857,12 @@  discard block
 block discarded – undo
779 857
             $soc->fetch($this->fourn_id);
780 858
 
781 859
             // Check if object has a temporary ref
782
-            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
860
+            if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) {
861
+            	// empty should not happened, but when it occurs, the test save life
783 862
             {
784 863
                 $num = $this->getNextNumRef($soc);
785 864
             }
786
-            else
865
+            } else
787 866
 			{
788 867
                 $num = $this->ref;
789 868
             }
@@ -795,9 +874,11 @@  discard block
 block discarded – undo
795 874
 
796 875
             $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
797 876
 			$sql.= " SET ref='".$this->db->escape($num)."',";
798
-			if (empty($secondlevel))	// standard or first level approval
877
+			if (empty($secondlevel)) {
878
+				// standard or first level approval
799 879
 			{
800 880
 	            $sql.= " date_approve='".$this->db->idate($now)."',";
881
+			}
801 882
     	        $sql.= " fk_user_approve = ".$user->id;
802 883
     	        if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
803 884
     	        {
@@ -807,17 +888,22 @@  discard block
 block discarded – undo
807 888
     	        	    $comment=' (first level)';
808 889
     	        	}
809 890
     	        }
810
-			}
811
-			else	// request a second level approval
891
+			} else	// request a second level approval
812 892
 			{
813 893
             	$sql.= " date_approve2='".$this->db->idate($now)."',";
814 894
             	$sql.= " fk_user_approve2 = ".$user->id;
815
-    	        if (empty($this->user_approve_id)) $movetoapprovestatus=false;		// first level approval not done
895
+    	        if (empty($this->user_approve_id)) {
896
+    	        	$movetoapprovestatus=false;
897
+    	        }
898
+    	        // first level approval not done
816 899
     	        $comment=' (second level)';
817 900
 			}
818 901
 			// If double approval is required and first approval, we keep status to 1 = validated
819
-			if ($movetoapprovestatus) $sql.= ", fk_statut = 2";
820
-			else $sql.= ", fk_statut = 1";
902
+			if ($movetoapprovestatus) {
903
+				$sql.= ", fk_statut = 2";
904
+			} else {
905
+				$sql.= ", fk_statut = 1";
906
+			}
821 907
             $sql.= " WHERE rowid = ".$this->id;
822 908
             $sql.= " AND fk_statut = 1";
823 909
 
@@ -826,10 +912,12 @@  discard block
 block discarded – undo
826 912
             	if (! empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
827 913
 	            {
828 914
 					$result=$this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
829
-					if ($result < 0 && $result != -2)	// -2 means already exists
915
+					if ($result < 0 && $result != -2) {
916
+						// -2 means already exists
830 917
 					{
831 918
 						$error++;
832 919
 					}
920
+					}
833 921
 	            }
834 922
 
835 923
                 // If stock is incremented on validate order, we must increment it
@@ -849,7 +937,9 @@  discard block
 block discarded – undo
849 937
                             $mouvP->origin = &$this;
850 938
                             // We decrement stock of product (and sub-products)
851 939
 	                        $up_ht_disc=$this->lines[$i]->subprice;
852
-    	                    if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
940
+    	                    if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) {
941
+    	                    	$up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
942
+    	                    }
853 943
                             $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr",$this->ref));
854 944
                             if ($result < 0) { $error++; }
855 945
                             unset($this->line);
@@ -861,7 +951,9 @@  discard block
 block discarded – undo
861 951
                 {
862 952
 					// Call trigger
863 953
 					$result=$this->call_trigger('ORDER_SUPPLIER_APPROVE',$user);
864
-					if ($result < 0) $error++;
954
+					if ($result < 0) {
955
+						$error++;
956
+					}
865 957
 					// End call triggers
866 958
                 }
867 959
 
@@ -869,14 +961,18 @@  discard block
 block discarded – undo
869 961
                 {
870 962
                 	$this->ref = $this->newref;
871 963
 
872
-                	if ($movetoapprovestatus) $this->statut = 2;
873
-					else $this->statut = 1;
874
-           			if (empty($secondlevel))	// standard or first level approval
964
+                	if ($movetoapprovestatus) {
965
+                		$this->statut = 2;
966
+                	} else {
967
+						$this->statut = 1;
968
+					}
969
+           			if (empty($secondlevel)) {
970
+           				// standard or first level approval
875 971
 					{
876 972
 			            $this->date_approve = $now;
973
+           			}
877 974
 		    	        $this->user_approve_id = $user->id;
878
-					}
879
-					else	// request a second level approval
975
+					} else	// request a second level approval
880 976
 					{
881 977
 			            $this->date_approve2 = $now;
882 978
 		    	        $this->user_approve_id2 = $user->id;
@@ -884,21 +980,18 @@  discard block
 block discarded – undo
884 980
 
885 981
                     $this->db->commit();
886 982
                     return 1;
887
-                }
888
-                else
983
+                } else
889 984
                 {
890 985
                     $this->db->rollback();
891 986
                     return -1;
892 987
                 }
893
-            }
894
-            else
988
+            } else
895 989
             {
896 990
                 $this->db->rollback();
897 991
                 $this->error=$this->db->lasterror();
898 992
                 return -1;
899 993
             }
900
-        }
901
-        else
994
+        } else
902 995
         {
903 996
             dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
904 997
         }
@@ -938,21 +1031,19 @@  discard block
 block discarded – undo
938 1031
                     {
939 1032
                         $error++;
940 1033
                         $this->db->rollback();
1034
+                    } else {
1035
+                                        	$this->db->commit();
941 1036
                     }
942
-                    else
943
-                    	$this->db->commit();
944 1037
 					// End call triggers
945 1038
                 }
946
-            }
947
-            else
1039
+            } else
948 1040
             {
949 1041
                 $this->db->rollback();
950 1042
                 $this->error=$this->db->lasterror();
951 1043
                 dol_syslog(get_class($this)."::refuse Error -1");
952 1044
                 $result = -1;
953 1045
             }
954
-        }
955
-        else
1046
+        } else
956 1047
         {
957 1048
             dol_syslog(get_class($this)."::refuse Not Authorized");
958 1049
         }
@@ -990,29 +1081,28 @@  discard block
 block discarded – undo
990 1081
 
991 1082
 				// Call trigger
992 1083
 				$result=$this->call_trigger('ORDER_SUPPLIER_CANCEL',$user);
993
-				if ($result < 0) $error++;
1084
+				if ($result < 0) {
1085
+					$error++;
1086
+				}
994 1087
 				// End call triggers
995 1088
 
996 1089
                 if ($error == 0)
997 1090
                 {
998 1091
                     $this->db->commit();
999 1092
                     return 1;
1000
-                }
1001
-                else
1093
+                } else
1002 1094
                 {
1003 1095
                     $this->db->rollback();
1004 1096
                     return -1;
1005 1097
                 }
1006
-            }
1007
-            else
1098
+            } else
1008 1099
             {
1009 1100
                 $this->db->rollback();
1010 1101
                 $this->error=$this->db->lasterror();
1011 1102
                 dol_syslog(get_class($this)."::cancel ".$this->error);
1012 1103
                 return -1;
1013 1104
             }
1014
-        }
1015
-        else
1105
+        } else
1016 1106
         {
1017 1107
             dol_syslog(get_class($this)."::cancel Not Authorized");
1018 1108
             return -1;
@@ -1050,10 +1140,11 @@  discard block
 block discarded – undo
1050 1140
 
1051 1141
                 // Call trigger
1052 1142
                 $result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT',$user);
1053
-                if ($result < 0) $error++;
1143
+                if ($result < 0) {
1144
+                	$error++;
1145
+                }
1054 1146
                 // End call triggers
1055
-            }
1056
-            else
1147
+            } else
1057 1148
             {
1058 1149
                 $error++;
1059 1150
                 $this->error = $this->db->lasterror();
@@ -1063,13 +1154,11 @@  discard block
 block discarded – undo
1063 1154
             if (! $error)
1064 1155
             {
1065 1156
                 $this->db->commit();
1066
-            }
1067
-            else
1157
+            } else
1068 1158
             {
1069 1159
                 $this->db->rollback();
1070 1160
             }
1071
-        }
1072
-        else
1161
+        } else
1073 1162
         {
1074 1163
             $error++;
1075 1164
             $this->error = $langs->trans('NotAuthorized');
@@ -1097,11 +1186,16 @@  discard block
 block discarded – undo
1097 1186
         $now=dol_now();
1098 1187
 
1099 1188
         // Clean parameters
1100
-        if (empty($this->source)) $this->source = 0;
1189
+        if (empty($this->source)) {
1190
+        	$this->source = 0;
1191
+        }
1101 1192
 
1102 1193
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
1103
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1104
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1194
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1195
+			list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1196
+		} else {
1197
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1198
+		}
1105 1199
 		if (empty($this->fk_multicurrency))
1106 1200
 		{
1107 1201
 			$this->multicurrency_code = $conf->currency;
@@ -1227,7 +1321,9 @@  discard block
 block discarded – undo
1227 1321
 	                if (! $error)
1228 1322
                     {
1229 1323
                     	$result=$this->insertExtraFields();
1230
-	                    if ($result < 0) $error++;
1324
+	                    if ($result < 0) {
1325
+	                    	$error++;
1326
+	                    }
1231 1327
                     }
1232 1328
 
1233 1329
 					if (! $error && ! $notrigger)
@@ -1244,16 +1340,14 @@  discard block
 block discarded – undo
1244 1340
 
1245 1341
 	                $this->db->commit();
1246 1342
 	                return $this->id;
1247
-	            }
1248
-	            else
1343
+	            } else
1249 1344
 	            {
1250 1345
 	                $this->error=$this->db->lasterror();
1251 1346
 	                $this->db->rollback();
1252 1347
 	                return -2;
1253 1348
 	            }
1254 1349
             }
1255
-        }
1256
-        else
1350
+        } else
1257 1351
         {
1258 1352
             $this->error=$this->db->lasterror();
1259 1353
             $this->db->rollback();
@@ -1295,7 +1389,9 @@  discard block
 block discarded – undo
1295 1389
 
1296 1390
         // Create clone
1297 1391
         $result=$this->create($user);
1298
-        if ($result < 0) $error++;
1392
+        if ($result < 0) {
1393
+        	$error++;
1394
+        }
1299 1395
 
1300 1396
         if (! $error)
1301 1397
         {
@@ -1305,12 +1401,16 @@  discard block
 block discarded – undo
1305 1401
                 $parameters=array('objFrom'=>$objFrom);
1306 1402
                 $action='';
1307 1403
                 $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1308
-                if ($reshook < 0) $error++;
1404
+                if ($reshook < 0) {
1405
+                	$error++;
1406
+                }
1309 1407
             }
1310 1408
 
1311 1409
 			// Call trigger
1312 1410
 			$result=$this->call_trigger('ORDER_SUPPLIER_CLONE',$user);
1313
-			if ($result < 0) $error++;
1411
+			if ($result < 0) {
1412
+				$error++;
1413
+			}
1314 1414
 			// End call triggers
1315 1415
         }
1316 1416
 
@@ -1321,8 +1421,7 @@  discard block
 block discarded – undo
1321 1421
         {
1322 1422
             $this->db->commit();
1323 1423
             return $this->id;
1324
-        }
1325
-        else
1424
+        } else
1326 1425
         {
1327 1426
             $this->db->rollback();
1328 1427
             return -1;
@@ -1366,12 +1465,24 @@  discard block
 block discarded – undo
1366 1465
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1367 1466
 
1368 1467
         // Clean parameters
1369
-        if (! $qty) $qty=1;
1370
-        if (! $info_bits) $info_bits=0;
1371
-        if (empty($txtva)) $txtva=0;
1372
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1373
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1374
-		if (empty($remise_percent)) $remise_percent=0;
1468
+        if (! $qty) {
1469
+        	$qty=1;
1470
+        }
1471
+        if (! $info_bits) {
1472
+        	$info_bits=0;
1473
+        }
1474
+        if (empty($txtva)) {
1475
+        	$txtva=0;
1476
+        }
1477
+        if (empty($txlocaltax1)) {
1478
+        	$txlocaltax1=0;
1479
+        }
1480
+        if (empty($txlocaltax2)) {
1481
+        	$txlocaltax2=0;
1482
+        }
1483
+		if (empty($remise_percent)) {
1484
+			$remise_percent=0;
1485
+		}
1375 1486
 
1376 1487
         $remise_percent=price2num($remise_percent);
1377 1488
         $qty=price2num($qty);
@@ -1383,8 +1494,7 @@  discard block
 block discarded – undo
1383 1494
         if ($price_base_type=='HT')
1384 1495
         {
1385 1496
             $pu=$pu_ht;
1386
-        }
1387
-        else
1497
+        } else
1388 1498
         {
1389 1499
             $pu=$pu_ttc;
1390 1500
         }
@@ -1397,7 +1507,9 @@  discard block
 block discarded – undo
1397 1507
             $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Product"));
1398 1508
             return -1;
1399 1509
         }
1400
-        if ($type < 0) return -1;
1510
+        if ($type < 0) {
1511
+        	return -1;
1512
+        }
1401 1513
 
1402 1514
         if ($this->statut == 0)
1403 1515
         {
@@ -1423,14 +1535,17 @@  discard block
 block discarded – undo
1423 1535
                             $pu           = $prod->fourn_pu;       // Unit price supplier price set by get_buyprice
1424 1536
                             $ref_supplier = $prod->ref_supplier;   // Ref supplier price set by get_buyprice
1425 1537
 			    // is remise percent not keyed but present for the product we add it
1426
-                            if ($remise_percent == 0 && $prod->remise_percent !=0)
1427
-                            	$remise_percent =$prod->remise_percent;
1538
+                            if ($remise_percent == 0 && $prod->remise_percent !=0) {
1539
+                                                        	$remise_percent =$prod->remise_percent;
1540
+                            }
1428 1541
 
1429 1542
 
1430 1543
                         }
1431
-                        if ($result == 0)                   // If result == 0, we failed to found the supplier reference price
1544
+                        if ($result == 0) {
1545
+                        	// If result == 0, we failed to found the supplier reference price
1432 1546
                         {
1433 1547
                             $langs->load("errors");
1548
+                        }
1434 1549
                             $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1435 1550
                             $this->db->rollback();
1436 1551
                             dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
@@ -1453,15 +1568,13 @@  discard block
 block discarded – undo
1453 1568
                             dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1454 1569
                             return -1;
1455 1570
                         }
1456
-                    }
1457
-                    else
1571
+                    } else
1458 1572
     				{
1459 1573
                         $this->error=$prod->error;
1460 1574
                         return -1;
1461 1575
                     }
1462 1576
                 }
1463
-            }
1464
-            else
1577
+            } else
1465 1578
             {
1466 1579
                 $product_type = $type;
1467 1580
             }
@@ -1562,7 +1675,9 @@  discard block
 block discarded – undo
1562 1675
             if ($result > 0)
1563 1676
             {
1564 1677
                 // Reorder if child line
1565
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1678
+                if (! empty($fk_parent_line)) {
1679
+                	$this->line_order(true,'DESC');
1680
+                }
1566 1681
 
1567 1682
                 // Mise a jour informations denormalisees au niveau de la commande meme
1568 1683
                 $result=$this->update_price(1,'auto',0,$this->thirdparty);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
@@ -1570,14 +1685,12 @@  discard block
 block discarded – undo
1570 1685
                 {
1571 1686
                     $this->db->commit();
1572 1687
                     return $this->line->id;
1573
-                }
1574
-                else
1688
+                } else
1575 1689
                 {
1576 1690
                     $this->db->rollback();
1577 1691
                     return -1;
1578 1692
                 }
1579
-            }
1580
-            else
1693
+            } else
1581 1694
             {
1582 1695
                 $this->error=$this->line->error;
1583 1696
                 $this->errors=$this->line->errors;
@@ -1625,7 +1738,10 @@  discard block
 block discarded – undo
1625 1738
         }
1626 1739
 
1627 1740
         $dispatchstatus = 1;
1628
-        if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0;	// Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1741
+        if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
1742
+        	$dispatchstatus = 0;
1743
+        }
1744
+        // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1629 1745
 
1630 1746
         $now=dol_now();
1631 1747
 
@@ -1655,8 +1771,7 @@  discard block
 block discarded – undo
1655 1771
                     }
1656 1772
 					// End call triggers
1657 1773
                 }
1658
-            }
1659
-            else
1774
+            } else
1660 1775
 			{
1661 1776
                 $this->error=$this->db->lasterror();
1662 1777
                 $error++;
@@ -1686,14 +1801,12 @@  discard block
 block discarded – undo
1686 1801
             {
1687 1802
                 $this->db->commit();
1688 1803
                 return 1;
1689
-            }
1690
-            else
1804
+            } else
1691 1805
             {
1692 1806
                 $this->db->rollback();
1693 1807
                 return -1;
1694 1808
             }
1695
-        }
1696
-        else
1809
+        } else
1697 1810
 		{
1698 1811
             $this->error='BadStatusForObject';
1699 1812
             return -2;
@@ -1722,15 +1835,13 @@  discard block
 block discarded – undo
1722 1835
             {
1723 1836
                 $this->update_price();
1724 1837
                 return 1;
1725
-            }
1726
-            else
1838
+            } else
1727 1839
             {
1728 1840
                 $this->error = $line->error;
1729 1841
                 $this->errors = $line->errors;
1730 1842
                 return -1;
1731 1843
             }
1732
-        }
1733
-        else
1844
+        } else
1734 1845
         {
1735 1846
             return -2;
1736 1847
         }
@@ -1784,8 +1895,7 @@  discard block
 block discarded – undo
1784 1895
                 $this->errors[]=$this->db->lasterror();
1785 1896
                 $error++;
1786 1897
             }
1787
-        }
1788
-        else
1898
+        } else
1789 1899
         {
1790 1900
             $this->error=$this->db->lasterror();
1791 1901
             $this->errors[]=$this->db->lasterror();
@@ -1793,9 +1903,11 @@  discard block
 block discarded – undo
1793 1903
         }
1794 1904
 
1795 1905
         // Remove extrafields
1796
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1906
+        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
1907
+        	// For avoid conflicts if trigger used
1797 1908
         {
1798 1909
         	$result=$this->deleteExtraFields();
1910
+        }
1799 1911
         	if ($result < 0)
1800 1912
         	{
1801 1913
         		$this->error='FailToDeleteExtraFields';
@@ -1823,9 +1935,11 @@  discard block
 block discarded – undo
1823 1935
         		$file = $dir . "/" . $ref . ".pdf";
1824 1936
         		if (file_exists($file))
1825 1937
         		{
1826
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1938
+        			if (! dol_delete_file($file,0,0,0,$this)) {
1939
+        				// For triggers
1827 1940
         			{
1828 1941
         				$this->error='ErrorFailToDeleteFile';
1942
+        			}
1829 1943
         				$this->errors[]='ErrorFailToDeleteFile';
1830 1944
         				$error++;
1831 1945
         			}
@@ -1848,8 +1962,7 @@  discard block
 block discarded – undo
1848 1962
 			dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1849 1963
 			$this->db->commit();
1850 1964
 			return 1;
1851
-		}
1852
-		else
1965
+		} else
1853 1966
 		{
1854 1967
 			dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1855 1968
 			$this->db->rollback();
@@ -1883,8 +1996,7 @@  discard block
 block discarded – undo
1883 1996
                 $i++;
1884 1997
             }
1885 1998
             return 0;
1886
-        }
1887
-        else
1999
+        } else
1888 2000
         {
1889 2001
             return -1;
1890 2002
         }
@@ -1909,7 +2021,9 @@  discard block
 block discarded – undo
1909 2021
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
1910 2022
 		$sql.= " WHERE cfd.fk_commande = ".$this->id;
1911 2023
 		$sql.= " AND cfd.fk_product = p.rowid";
1912
-		if ($status >= 0) $sql.=" AND cfd.status = ".$status;
2024
+		if ($status >= 0) {
2025
+			$sql.=" AND cfd.status = ".$status;
2026
+		}
1913 2027
 		$sql.= " ORDER BY cfd.rowid ASC";
1914 2028
 
1915 2029
 		$resql = $this->db->query($sql);
@@ -1921,12 +2035,15 @@  discard block
 block discarded – undo
1921 2035
 			while ($i < $num)
1922 2036
 			{
1923 2037
 				$objp = $this->db->fetch_object($resql);
1924
-				if ($objp) $ret[]=array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
2038
+				if ($objp) {
2039
+					$ret[]=array('id'=>$objp->dispatchedlineid, 'productid'=>$objp->fk_product, 'warehouseid'=>$objp->warehouse_id);
2040
+				}
1925 2041
 
1926 2042
 				$i++;
1927 2043
 			}
2044
+		} else {
2045
+			dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
1928 2046
 		}
1929
-		else dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
1930 2047
 
1931 2048
 		return $ret;
1932 2049
     }
@@ -1952,10 +2069,18 @@  discard block
 block discarded – undo
1952 2069
 
1953 2070
         if ($user->rights->fournisseur->commande->receptionner)
1954 2071
         {
1955
-            if ($type == 'par') $statut = 4;
1956
-            if ($type == 'tot')	$statut = 5;
1957
-            if ($type == 'nev') $statut = 7;
1958
-            if ($type == 'can') $statut = 7;
2072
+            if ($type == 'par') {
2073
+            	$statut = 4;
2074
+            }
2075
+            if ($type == 'tot') {
2076
+            	$statut = 5;
2077
+            }
2078
+            if ($type == 'nev') {
2079
+            	$statut = 7;
2080
+            }
2081
+            if ($type == 'can') {
2082
+            	$statut = 7;
2083
+            }
1959 2084
 
1960 2085
             // Some checks to accept the record
1961 2086
             if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
@@ -1973,9 +2098,11 @@  discard block
 block discarded – undo
1973 2098
 		    		}
1974 2099
 
1975 2100
 		    	}
1976
-	    		if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot'))	// Accept to move to reception done, only if status of all line are ok (refuse denied)
2101
+	    		if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) {
2102
+	    			// Accept to move to reception done, only if status of all line are ok (refuse denied)
1977 2103
 	    		{
1978 2104
 	    			$dispatcheddenied=$this->getDispachedLines(2);
2105
+	    		}
1979 2106
 	    			if (count($dispatchedlinearray) > 0)
1980 2107
 	    			{
1981 2108
 		    			$result=-1;
@@ -2016,30 +2143,29 @@  discard block
 block discarded – undo
2016 2143
 
2017 2144
                     // Call trigger
2018 2145
                     $result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE',$user);
2019
-                    if ($result < 0) $error++;
2146
+                    if ($result < 0) {
2147
+                    	$error++;
2148
+                    }
2020 2149
                     // End call triggers
2021 2150
 
2022 2151
                     if (! $error)
2023 2152
                     {
2024 2153
                         $this->db->commit();
2025
-                    }
2026
-                    else
2154
+                    } else
2027 2155
                     {
2028 2156
                         $this->statut = $old_statut;
2029 2157
                         $this->db->rollback();
2030 2158
                         $this->error=$this->db->lasterror();
2031 2159
                         $result = -1;
2032 2160
                     }
2033
-                }
2034
-                else
2161
+                } else
2035 2162
                 {
2036 2163
                     $this->db->rollback();
2037 2164
                     $this->error=$this->db->lasterror();
2038 2165
                     $result = -1;
2039 2166
                 }
2040 2167
             }
2041
-        }
2042
-        else
2168
+        } else
2043 2169
         {
2044 2170
             $this->error = $langs->trans('NotAuthorized');
2045 2171
             $this->errors[] = $langs->trans('NotAuthorized');
@@ -2087,7 +2213,9 @@  discard block
 block discarded – undo
2087 2213
         	{
2088 2214
         		// Call trigger
2089 2215
         		$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2090
-        		if ($result < 0) $error++;
2216
+        		if ($result < 0) {
2217
+        			$error++;
2218
+        		}
2091 2219
         		// End call triggers
2092 2220
         	}
2093 2221
 
@@ -2095,8 +2223,7 @@  discard block
 block discarded – undo
2095 2223
         	{
2096 2224
         		$this->db->commit();
2097 2225
         		return 1;
2098
-        	}
2099
-        	else
2226
+        	} else
2100 2227
         	{
2101 2228
         		foreach($this->errors as $errmsg)
2102 2229
         		{
@@ -2106,8 +2233,7 @@  discard block
 block discarded – undo
2106 2233
         		$this->db->rollback();
2107 2234
         		return -1*$error;
2108 2235
         	}
2109
-        }
2110
-        else
2236
+        } else
2111 2237
         {
2112 2238
             return -2;
2113 2239
         }
@@ -2151,7 +2277,9 @@  discard block
 block discarded – undo
2151 2277
             {
2152 2278
             	// Call trigger
2153 2279
             	$result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2154
-            	if ($result < 0) $error++;
2280
+            	if ($result < 0) {
2281
+            		$error++;
2282
+            	}
2155 2283
             	// End call triggers
2156 2284
             }
2157 2285
 
@@ -2159,8 +2287,7 @@  discard block
 block discarded – undo
2159 2287
             {
2160 2288
             	$this->db->commit();
2161 2289
             	return 1;
2162
-            }
2163
-            else
2290
+            } else
2164 2291
             {
2165 2292
             	foreach($this->errors as $errmsg)
2166 2293
             	{
@@ -2170,8 +2297,7 @@  discard block
 block discarded – undo
2170 2297
             	$this->db->rollback();
2171 2298
             	return -1*$error;
2172 2299
             }
2173
-        }
2174
-        else
2300
+        } else
2175 2301
         {
2176 2302
             return -2;
2177 2303
         }
@@ -2257,8 +2383,7 @@  discard block
 block discarded – undo
2257 2383
             $result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status],$user);
2258 2384
             if ($result < 0) { $error++; }
2259 2385
             // End call triggers
2260
-        }
2261
-        else
2386
+        } else
2262 2387
         {
2263 2388
             $error++;
2264 2389
             $this->error=$this->db->lasterror();
@@ -2270,8 +2395,7 @@  discard block
 block discarded – undo
2270 2395
             $this->statut = $status;
2271 2396
             $this->db->commit();
2272 2397
             return 1;
2273
-        }
2274
-        else
2398
+        } else
2275 2399
         {
2276 2400
             $this->db->rollback();
2277 2401
             return -1;
@@ -2313,24 +2437,42 @@  discard block
 block discarded – undo
2313 2437
             $this->db->begin();
2314 2438
 
2315 2439
             // Clean parameters
2316
-            if (empty($qty)) $qty=0;
2317
-            if (empty($info_bits)) $info_bits=0;
2318
-            if (empty($txtva)) $txtva=0;
2319
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2320
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2321
-            if (empty($remise)) $remise=0;
2322
-            if (empty($remise_percent)) $remise_percent=0;
2440
+            if (empty($qty)) {
2441
+            	$qty=0;
2442
+            }
2443
+            if (empty($info_bits)) {
2444
+            	$info_bits=0;
2445
+            }
2446
+            if (empty($txtva)) {
2447
+            	$txtva=0;
2448
+            }
2449
+            if (empty($txlocaltax1)) {
2450
+            	$txlocaltax1=0;
2451
+            }
2452
+            if (empty($txlocaltax2)) {
2453
+            	$txlocaltax2=0;
2454
+            }
2455
+            if (empty($remise)) {
2456
+            	$remise=0;
2457
+            }
2458
+            if (empty($remise_percent)) {
2459
+            	$remise_percent=0;
2460
+            }
2323 2461
 
2324 2462
             $remise_percent=price2num($remise_percent);
2325 2463
             $qty=price2num($qty);
2326
-            if (! $qty) $qty=1;
2464
+            if (! $qty) {
2465
+            	$qty=1;
2466
+            }
2327 2467
             $pu = price2num($pu);
2328 2468
             $txtva=price2num($txtva);
2329 2469
             $txlocaltax1=price2num($txlocaltax1);
2330 2470
             $txlocaltax2=price2num($txlocaltax2);
2331 2471
 
2332 2472
             // Check parameters
2333
-            if ($type < 0) return -1;
2473
+            if ($type < 0) {
2474
+            	return -1;
2475
+            }
2334 2476
 
2335 2477
             // Calcul du total TTC et de la TVA pour la ligne a partir de
2336 2478
             // qty, pu, remise_percent et txtva
@@ -2430,15 +2572,13 @@  discard block
 block discarded – undo
2430 2572
                 $this->update_price('','auto');
2431 2573
 				$this->db->commit();
2432 2574
 				return $result;
2433
-            }
2434
-            else
2575
+            } else
2435 2576
             {
2436 2577
                 $this->error=$this->db->lasterror();
2437 2578
                 $this->db->rollback();
2438 2579
                 return -1;
2439 2580
             }
2440
-        }
2441
-        else
2581
+        } else
2442 2582
         {
2443 2583
             $this->error="Order status makes operation forbidden";
2444 2584
             dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
@@ -2510,8 +2650,7 @@  discard block
 block discarded – undo
2510 2650
                 $line->total_ttc=59.8;
2511 2651
                 $line->total_tva=9.8;
2512 2652
                 $line->remise_percent=50;
2513
-            }
2514
-            else
2653
+            } else
2515 2654
             {
2516 2655
                 $line->total_ht=100;
2517 2656
                 $line->total_ttc=119.6;
@@ -2550,11 +2689,21 @@  discard block
 block discarded – undo
2550 2689
             {
2551 2690
                 $obj = $this->db->fetch_object($result);
2552 2691
                 $this->id = $obj->rowid;
2553
-                if ($obj->fk_user_author)   $this->user_creation_id = $obj->fk_user_author;
2554
-                if ($obj->fk_user_valid)    $this->user_validation_id = $obj->fk_user_valid;
2555
-                if ($obj->fk_user_modif)    $this->user_modification_id =$obj->fk_user_modif;
2556
-                if ($obj->fk_user_approve)  $this->user_approve_id = $obj->fk_user_approve;
2557
-                if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2;
2692
+                if ($obj->fk_user_author) {
2693
+                	$this->user_creation_id = $obj->fk_user_author;
2694
+                }
2695
+                if ($obj->fk_user_valid) {
2696
+                	$this->user_validation_id = $obj->fk_user_valid;
2697
+                }
2698
+                if ($obj->fk_user_modif) {
2699
+                	$this->user_modification_id =$obj->fk_user_modif;
2700
+                }
2701
+                if ($obj->fk_user_approve) {
2702
+                	$this->user_approve_id = $obj->fk_user_approve;
2703
+                }
2704
+                if ($obj->fk_user_approve2) {
2705
+                	$this->user_approve_id2 = $obj->fk_user_approve2;
2706
+                }
2558 2707
 
2559 2708
                 $this->date_creation     = $this->db->idate($obj->datec);
2560 2709
                 $this->date_modification = $this->db->idate($obj->datem);
@@ -2563,8 +2712,7 @@  discard block
 block discarded – undo
2563 2712
                 $this->date_validation   = $this->db->idate($obj->date_validation);
2564 2713
             }
2565 2714
             $this->db->free($result);
2566
-        }
2567
-        else
2715
+        } else
2568 2716
         {
2569 2717
             dol_print_error($this->db);
2570 2718
         }
@@ -2602,8 +2750,7 @@  discard block
 block discarded – undo
2602 2750
             }
2603 2751
             $this->db->free($resql);
2604 2752
             return 1;
2605
-        }
2606
-        else
2753
+        } else
2607 2754
         {
2608 2755
             dol_print_error($this->db);
2609 2756
             $this->error=$this->db->error();
@@ -2633,7 +2780,9 @@  discard block
 block discarded – undo
2633 2780
         }
2634 2781
         $sql.= $clause." c.entity = ".$conf->entity;
2635 2782
         $sql.= " AND (c.fk_statut BETWEEN 1 AND 2)";
2636
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2783
+        if ($user->societe_id) {
2784
+        	$sql.=" AND c.fk_soc = ".$user->societe_id;
2785
+        }
2637 2786
 
2638 2787
         $resql=$this->db->query($sql);
2639 2788
         if ($resql)
@@ -2660,8 +2809,7 @@  discard block
 block discarded – undo
2660 2809
             }
2661 2810
 
2662 2811
             return $response;
2663
-        }
2664
-        else
2812
+        } else
2665 2813
         {
2666 2814
             $this->error=$this->db->error();
2667 2815
             return -1;
@@ -2698,8 +2846,9 @@  discard block
 block discarded – undo
2698 2846
                     }
2699 2847
                     return $string;
2700 2848
                 }
2849
+            } else {
2850
+            	dol_print_error($db);
2701 2851
             }
2702
-            else dol_print_error($db);
2703 2852
         }
2704 2853
 
2705 2854
         return '';
@@ -2745,7 +2894,9 @@  discard block
 block discarded – undo
2745 2894
      */
2746 2895
     public function getMaxDeliveryTimeDay($langs)
2747 2896
 	{
2748
-		if (empty($this->lines)) return '';
2897
+		if (empty($this->lines)) {
2898
+			return '';
2899
+		}
2749 2900
 
2750 2901
 		$obj = new ProductFournisseur($this->db);
2751 2902
 
@@ -2758,13 +2909,18 @@  discard block
 block discarded – undo
2758 2909
 				if ($idp)
2759 2910
 				{
2760 2911
 					$obj->fetch($idp);
2761
-					if ($obj->delivery_time_days > $nb) $nb = $obj->delivery_time_days;
2912
+					if ($obj->delivery_time_days > $nb) {
2913
+						$nb = $obj->delivery_time_days;
2914
+					}
2762 2915
 				}
2763 2916
 			}
2764 2917
 		}
2765 2918
 
2766
-		if ($nb === 0) return '';
2767
-		else return $nb.' '.$langs->trans('Days');
2919
+		if ($nb === 0) {
2920
+			return '';
2921
+		} else {
2922
+			return $nb.' '.$langs->trans('Days');
2923
+		}
2768 2924
 	}
2769 2925
 
2770 2926
 	/**
@@ -2805,7 +2961,10 @@  discard block
 block discarded – undo
2805 2961
     {
2806 2962
         global $conf;
2807 2963
 
2808
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2964
+        if (empty($this->date_delivery) && ! empty($this->date_livraison)) {
2965
+        	$this->date_delivery = $this->date_livraison;
2966
+        }
2967
+        // For backward compatibility
2809 2968
 
2810 2969
         $now = dol_now();
2811 2970
         $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery;
@@ -2822,10 +2981,16 @@  discard block
 block discarded – undo
2822 2981
     {
2823 2982
         global $conf, $langs;
2824 2983
 
2825
-        if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison;    // For backward compatibility
2984
+        if (empty($this->date_delivery) && ! empty($this->date_livraison)) {
2985
+        	$this->date_delivery = $this->date_livraison;
2986
+        }
2987
+        // For backward compatibility
2826 2988
 
2827
-        if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2828
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2989
+        if (empty($this->date_delivery)) {
2990
+        	$text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
2991
+        } else {
2992
+        	$text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
2993
+        }
2829 2994
         $text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
2830 2995
 
2831 2996
         return $text;
@@ -2862,8 +3027,7 @@  discard block
 block discarded – undo
2862 3027
     		{
2863 3028
     			$this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors;
2864 3029
     			return $ret;
2865
-    		}
2866
-    		else
3030
+    		} else
2867 3031
     		{
2868 3032
     			if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0)
2869 3033
     			{
@@ -2887,18 +3051,20 @@  discard block
 block discarded – undo
2887 3051
     				var_dump($keysindeliverednotinwished);
2888 3052
     				exit;*/
2889 3053
 
2890
-    				if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received
3054
+    				if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) {
3055
+    					//No diff => mean everythings is received
2891 3056
     				{
2892 3057
     					if ($closeopenorder)
2893 3058
     					{
2894 3059
         					//$ret=$this->setStatus($user,5);
2895
-    						$ret = $this->Livraison($user, $date_liv, 'tot', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3060
+    						$ret = $this->Livraison($user, $date_liv, 'tot', $comment);
3061
+    				}
3062
+    				// GETPOST("type") is 'tot', 'par', 'nev', 'can'
2896 3063
         					if ($ret<0) {
2897 3064
         						return -1;
2898 3065
         					}
2899 3066
     					    return 5;
2900
-    					}
2901
-    					else
3067
+    					} else
2902 3068
     					{
2903 3069
     					    //Diff => received partially
2904 3070
     					    //$ret=$this->setStatus($user,4);
@@ -2908,8 +3074,7 @@  discard block
 block discarded – undo
2908 3074
     					    }
2909 3075
     					    return 4;
2910 3076
     					}
2911
-    				}
2912
-    				else
3077
+    				} else
2913 3078
     				{
2914 3079
     					//Diff => received partially
2915 3080
     					$ret = $this->Livraison($user, $date_liv, 'par', $comment);   // GETPOST("type") is 'tot', 'par', 'nev', 'can'
@@ -3044,8 +3209,7 @@  discard block
 block discarded – undo
3044 3209
 
3045 3210
             $this->db->free($result);
3046 3211
             return 1;
3047
-        }
3048
-        else
3212
+        } else
3049 3213
         {
3050 3214
             dol_print_error($this->db);
3051 3215
             return -1;
@@ -3077,8 +3241,7 @@  discard block
 block discarded – undo
3077 3241
         {
3078 3242
             $this->db->commit();
3079 3243
             return 1;
3080
-        }
3081
-        else
3244
+        } else
3082 3245
         {
3083 3246
             $this->error=$this->db->error();
3084 3247
             $this->db->rollback();
@@ -3101,23 +3264,53 @@  discard block
 block discarded – undo
3101 3264
         dol_syslog(get_class($this)."::insert rang=".$this->rang);
3102 3265
 
3103 3266
         // Clean parameters
3104
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3105
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3106
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3107
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
3108
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
3109
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3110
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3111
-        if (empty($this->rang)) $this->rang=0;
3112
-        if (empty($this->remise)) $this->remise=0;
3113
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3114
-        if (empty($this->info_bits)) $this->info_bits=0;
3115
-        if (empty($this->special_code)) $this->special_code=0;
3116
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3117
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3267
+        if (empty($this->tva_tx)) {
3268
+        	$this->tva_tx=0;
3269
+        }
3270
+        if (empty($this->localtax1_tx)) {
3271
+        	$this->localtax1_tx=0;
3272
+        }
3273
+        if (empty($this->localtax2_tx)) {
3274
+        	$this->localtax2_tx=0;
3275
+        }
3276
+        if (empty($this->localtax1_type)) {
3277
+        	$this->localtax1_type='0';
3278
+        }
3279
+        if (empty($this->localtax2_type)) {
3280
+        	$this->localtax2_type='0';
3281
+        }
3282
+        if (empty($this->total_localtax1)) {
3283
+        	$this->total_localtax1=0;
3284
+        }
3285
+        if (empty($this->total_localtax2)) {
3286
+        	$this->total_localtax2=0;
3287
+        }
3288
+        if (empty($this->rang)) {
3289
+        	$this->rang=0;
3290
+        }
3291
+        if (empty($this->remise)) {
3292
+        	$this->remise=0;
3293
+        }
3294
+        if (empty($this->remise_percent)) {
3295
+        	$this->remise_percent=0;
3296
+        }
3297
+        if (empty($this->info_bits)) {
3298
+        	$this->info_bits=0;
3299
+        }
3300
+        if (empty($this->special_code)) {
3301
+        	$this->special_code=0;
3302
+        }
3303
+        if (empty($this->fk_parent_line)) {
3304
+        	$this->fk_parent_line=0;
3305
+        }
3306
+        if (empty($this->pa_ht)) {
3307
+        	$this->pa_ht=0;
3308
+        }
3118 3309
 
3119 3310
         // Multicurrency
3120
-        if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3311
+        if (!empty($this->multicurrency_code)) {
3312
+        	list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3313
+        }
3121 3314
         if (empty($this->fk_multicurrency))
3122 3315
         {
3123 3316
             $this->multicurrency_code = $conf->currency;
@@ -3126,7 +3319,9 @@  discard block
 block discarded – undo
3126 3319
         }
3127 3320
 
3128 3321
         // Check parameters
3129
-        if ($this->product_type < 0) return -1;
3322
+        if ($this->product_type < 0) {
3323
+        	return -1;
3324
+        }
3130 3325
 
3131 3326
         $this->db->begin();
3132 3327
 
@@ -3141,8 +3336,7 @@  discard block
 block discarded – undo
3141 3336
         $sql.= " VALUES (".$this->fk_commande.", '" . $this->db->escape($this->label) . "','" . $this->db->escape($this->desc) . "',";
3142 3337
         $sql.= " ".($this->date_start?"'".$this->db->idate($this->date_start)."'":"null").",";
3143 3338
         $sql.= " ".($this->date_end?"'".$this->db->idate($this->date_end)."'":"null").",";
3144
-        if ($this->fk_product) { $sql.= $this->fk_product.","; }
3145
-        else { $sql.= "null,"; }
3339
+        if ($this->fk_product) { $sql.= $this->fk_product.","; } else { $sql.= "null,"; }
3146 3340
         $sql.= "'".$this->db->escape($this->product_type)."',";
3147 3341
         $sql.= "'".$this->db->escape($this->qty)."', ";
3148 3342
 
@@ -3174,10 +3368,12 @@  discard block
 block discarded – undo
3174 3368
             $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3175 3369
             $this->rowid =$this->id;
3176 3370
 
3177
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3371
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
3372
+            	// For avoid conflicts if trigger used
3178 3373
             {
3179 3374
 
3180 3375
                 $result=$this->insertExtraFields();
3376
+            }
3181 3377
                 if ($result < 0)
3182 3378
                 {
3183 3379
                     $error++;
@@ -3188,7 +3384,9 @@  discard block
 block discarded – undo
3188 3384
             {
3189 3385
                 // Call trigger
3190 3386
                 $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user);
3191
-                if ($result < 0) $error++;
3387
+                if ($result < 0) {
3388
+                	$error++;
3389
+                }
3192 3390
                 // End call triggers
3193 3391
             }
3194 3392
 
@@ -3204,8 +3402,7 @@  discard block
 block discarded – undo
3204 3402
             }
3205 3403
             $this->db->rollback();
3206 3404
             return -1*$error;
3207
-        }
3208
-        else
3405
+        } else
3209 3406
         {
3210 3407
             $this->errors[]=$this->db->error();
3211 3408
             $this->db->rollback();
@@ -3261,10 +3458,12 @@  discard block
 block discarded – undo
3261 3458
         $result = $this->db->query($sql);
3262 3459
         if ($result > 0)
3263 3460
         {
3264
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3461
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
3462
+            	// For avoid conflicts if trigger used
3265 3463
             {
3266 3464
 
3267 3465
                 $result=$this->insertExtraFields();
3466
+            }
3268 3467
                 if ($result < 0)
3269 3468
                 {
3270 3469
                     $error++;
@@ -3288,14 +3487,12 @@  discard block
 block discarded – undo
3288 3487
             {
3289 3488
                 $this->db->commit();
3290 3489
                 return $result;
3291
-            }
3292
-            else
3490
+            } else
3293 3491
             {
3294 3492
                 $this->db->rollback();
3295 3493
                 return -1;
3296 3494
             }
3297
-        }
3298
-        else
3495
+        } else
3299 3496
         {
3300 3497
             $this->error=$this->db->lasterror();
3301 3498
             $this->db->rollback();
@@ -3328,7 +3525,9 @@  discard block
 block discarded – undo
3328 3525
             {
3329 3526
                 // Call trigger
3330 3527
                 $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user);
3331
-                if ($result < 0) $error++;
3528
+                if ($result < 0) {
3529
+                	$error++;
3530
+                }
3332 3531
                 // End call triggers
3333 3532
             }
3334 3533
 
@@ -3345,8 +3544,7 @@  discard block
 block discarded – undo
3345 3544
             }
3346 3545
             $this->db->rollback();
3347 3546
             return -1*$error;
3348
-        }
3349
-        else
3547
+        } else
3350 3548
         {
3351 3549
             $this->error=$this->db->lasterror();
3352 3550
             return -1;
Please login to merge, or discard this patch.
htdocs/fourn/class/fournisseur.facture.class.php 4 patches
Doc Comments   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1302,19 +1302,19 @@  discard block
 block discarded – undo
1302 1302
      *	@param		double	$txlocaltax2		LocalTax2 Rate
1303 1303
      *	@param    	double	$qty             	Quantite
1304 1304
      *	@param    	int		$fk_product      	Id du produit/service predefini
1305
-     *	@param    	double	$remise_percent  	Pourcentage de remise de la ligne
1305
+     *	@param    	integer	$remise_percent  	Pourcentage de remise de la ligne
1306 1306
      *	@param    	date	$date_start      	Date de debut de validite du service
1307 1307
      * 	@param    	date	$date_end        	Date de fin de validite du service
1308
-     * 	@param    	string	$ventil          	Code de ventilation comptable
1308
+     * 	@param    	integer	$ventil          	Code de ventilation comptable
1309 1309
      *	@param    	int		$info_bits			Bits de type de lines
1310 1310
      *	@param    	string	$price_base_type 	HT ou TTC
1311 1311
      *	@param		int		$type				Type of line (0=product, 1=service)
1312 1312
      *  @param      int		$rang            	Position of line
1313 1313
      *  @param		int		$notrigger			Disable triggers
1314
-	 *  @param		array	$array_options		extrafields array
1314
+	 *  @param		integer	$array_options		extrafields array
1315 1315
      * 	@param 		string	$fk_unit 			Code of the unit to use. Null to use the default one
1316 1316
      *  @param      int     $origin_id          id origin document
1317
-	 *  @param		double	$pu_ht_devise		Amount in currency
1317
+	 *  @param		integer	$pu_ht_devise		Amount in currency
1318 1318
      *	@return    	int             			>0 if OK, <0 if KO
1319 1319
      *
1320 1320
      *  FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order.
@@ -1452,20 +1452,20 @@  discard block
 block discarded – undo
1452 1452
      * @param     	string		$desc         		Description of line
1453 1453
      * @param     	double		$pu          		Prix unitaire (HT ou TTC selon price_base_type)
1454 1454
      * @param     	double		$vatrate       		VAT Rate
1455
-     * @param		double		$txlocaltax1		LocalTax1 Rate
1456
-     * @param		double		$txlocaltax2		LocalTax2 Rate
1457
-     * @param     	double		$qty           		Quantity
1455
+     * @param		integer		$txlocaltax1		LocalTax1 Rate
1456
+     * @param		integer		$txlocaltax2		LocalTax2 Rate
1457
+     * @param     	integer		$qty           		Quantity
1458 1458
      * @param     	int			$idproduct			Id produit
1459 1459
      * @param	  	double		$price_base_type	HT or TTC
1460 1460
      * @param	  	int			$info_bits			Miscellaneous informations of line
1461 1461
      * @param		int			$type				Type of line (0=product, 1=service)
1462
-     * @param     	double		$remise_percent  	Pourcentage de remise de la ligne
1462
+     * @param     	integer		$remise_percent  	Pourcentage de remise de la ligne
1463 1463
      * @param		int			$notrigger			Disable triggers
1464 1464
      * @param      	timestamp	$date_start     	Date start of service
1465 1465
      * @param      	timestamp   $date_end       	Date end of service
1466
-	 * @param		array		$array_options		extrafields array
1466
+	 * @param		integer		$array_options		extrafields array
1467 1467
      * @param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
1468
-	 * @param		double		$pu_ht_devise		Amount in currency
1468
+	 * @param		integer		$pu_ht_devise		Amount in currency
1469 1469
      * @return    	int           					<0 if KO, >0 if OK
1470 1470
      */
1471 1471
     public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit = null, $pu_ht_devise=0)
@@ -2456,7 +2456,7 @@  discard block
 block discarded – undo
2456 2456
 	/**
2457 2457
 	 * Deletes a line
2458 2458
 	 *
2459
-	 * @param     bool|int   $notrigger     1=Does not execute triggers, 0= execute triggers
2459
+	 * @param     integer   $notrigger     1=Does not execute triggers, 0= execute triggers
2460 2460
 	 * @return    int                       0 if KO, 1 if OK
2461 2461
 	 */
2462 2462
 	public function delete($notrigger = 0)
Please login to merge, or discard this patch.
Indentation   +2043 added lines, -2043 removed lines patch added patch discarded remove patch
@@ -40,194 +40,194 @@  discard block
 block discarded – undo
40 40
  */
41 41
 class FactureFournisseur extends CommonInvoice
42 42
 {
43
-    public $element='invoice_supplier';
44
-    public $table_element='facture_fourn';
45
-    public $table_element_line='facture_fourn_det';
46
-    public $fk_element='fk_facture_fourn';
47
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
-    public $picto='bill';
49
-
50
-    /**
51
-     * {@inheritdoc}
52
-     */
53
-    protected $table_ref_field = 'ref';
54
-
55
-    public $rowid;
56
-    public $ref;
57
-    public $product_ref;
58
-    public $ref_supplier;
59
-    public $socid;
60
-    //Check constants for types
61
-    public $type = self::TYPE_STANDARD;
43
+	public $element='invoice_supplier';
44
+	public $table_element='facture_fourn';
45
+	public $table_element_line='facture_fourn_det';
46
+	public $fk_element='fk_facture_fourn';
47
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
+	public $picto='bill';
49
+
50
+	/**
51
+	 * {@inheritdoc}
52
+	 */
53
+	protected $table_ref_field = 'ref';
54
+
55
+	public $rowid;
56
+	public $ref;
57
+	public $product_ref;
58
+	public $ref_supplier;
59
+	public $socid;
60
+	//Check constants for types
61
+	public $type = self::TYPE_STANDARD;
62 62
 
63 63
 	/**
64 64
 	 * Supplier invoice status
65 65
 	 * @var int
66 66
 	 * @see FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_PAID, FactureFournisseur::STATUS_ABANDONED
67 67
 	 */
68
-    public $statut;
69
-
70
-    /**
71
-     * Set to 1 if the invoice is completely paid, otherwise is 0
72
-     * @var int
73
-     * @deprecated Use statuses stored in self::statut
74
-     */
75
-    public $paye;
76
-
77
-    public $author;
78
-    public $libelle;
79
-    public $datec;            // Creation date
80
-    public $tms;              // Last update date
81
-    public $date;             // Invoice date
82
-    public $date_echeance;    // Max payment date
83
-    public $amount;
84
-    public $remise;
85
-    public $tva;
86
-    public $localtax1;
87
-    public $localtax2;
88
-    public $total_ht;
89
-    public $total_tva;
90
-    public $total_localtax1;
91
-    public $total_localtax2;
92
-    public $total_ttc;
68
+	public $statut;
69
+
70
+	/**
71
+	 * Set to 1 if the invoice is completely paid, otherwise is 0
72
+	 * @var int
73
+	 * @deprecated Use statuses stored in self::statut
74
+	 */
75
+	public $paye;
76
+
77
+	public $author;
78
+	public $libelle;
79
+	public $datec;            // Creation date
80
+	public $tms;              // Last update date
81
+	public $date;             // Invoice date
82
+	public $date_echeance;    // Max payment date
83
+	public $amount;
84
+	public $remise;
85
+	public $tva;
86
+	public $localtax1;
87
+	public $localtax2;
88
+	public $total_ht;
89
+	public $total_tva;
90
+	public $total_localtax1;
91
+	public $total_localtax2;
92
+	public $total_ttc;
93 93
 	/**
94 94
 	 * @deprecated
95 95
 	 * @see note_private, note_public
96 96
 	 */
97
-    public $note;
98
-    public $note_private;
99
-    public $note_public;
100
-    public $propalid;
101
-    public $cond_reglement_id;
102
-    public $cond_reglement_code;
103
-    public $fk_account;
104
-    public $mode_reglement_id;
105
-    public $mode_reglement_code;
97
+	public $note;
98
+	public $note_private;
99
+	public $note_public;
100
+	public $propalid;
101
+	public $cond_reglement_id;
102
+	public $cond_reglement_code;
103
+	public $fk_account;
104
+	public $mode_reglement_id;
105
+	public $mode_reglement_code;
106 106
 
107 107
 	/**
108 108
 	 * Invoice lines
109 109
 	 * @var SupplierInvoiceLine[]
110 110
 	 */
111
-    public $lines = array();
111
+	public $lines = array();
112 112
 	/**
113 113
 	 * @deprecated
114 114
 	 */
115
-    public $fournisseur;
115
+	public $fournisseur;
116 116
 
117 117
 	//Incorterms
118
-    public $fk_incoterms;
119
-    public $location_incoterms;
120
-    public $libelle_incoterms;  //Used into tooltip
118
+	public $fk_incoterms;
119
+	public $location_incoterms;
120
+	public $libelle_incoterms;  //Used into tooltip
121 121
 
122
-    public $extraparams=array();
122
+	public $extraparams=array();
123 123
 
124 124
 	// Multicurrency
125
-    public $fk_multicurrency;
126
-    public $multicurrency_code;
127
-    public $multicurrency_tx;
128
-    public $multicurrency_total_ht;
129
-    public $multicurrency_total_tva;
130
-    public $multicurrency_total_ttc;
131
-    //! id of source invoice if replacement invoice or credit note
132
-    public $fk_facture_source;
133
-
134
-    /**
135
-     * Standard invoice
136
-     */
137
-    const TYPE_STANDARD = 0;
138
-
139
-    /**
140
-     * Replacement invoice
141
-     */
142
-    const TYPE_REPLACEMENT = 1;
143
-
144
-    /**
145
-     * Credit note invoice
146
-     */
147
-    const TYPE_CREDIT_NOTE = 2;
148
-
149
-    /**
150
-     * Deposit invoice
151
-     */
152
-    const TYPE_DEPOSIT = 3;
153
-
154
-    /**
155
-     * Draft
156
-     */
157
-    const STATUS_DRAFT = 0;
158
-
159
-    /**
160
-     * Validated (need to be paid)
161
-     */
162
-    const STATUS_VALIDATED = 1;
163
-
164
-    /**
165
-     * Classified paid.
166
-     * If paid partially, $this->close_code can be:
167
-     * - CLOSECODE_DISCOUNTVAT
168
-     * - CLOSECODE_BADDEBT
169
-     * If paid completelly, this->close_code will be null
170
-     */
171
-    const STATUS_CLOSED = 2;
172
-
173
-    /**
174
-     * Classified abandoned and no payment done.
175
-     * $this->close_code can be:
176
-     * - CLOSECODE_BADDEBT
177
-     * - CLOSECODE_ABANDONED
178
-     * - CLOSECODE_REPLACED
179
-     */
180
-    const STATUS_ABANDONED = 3;
125
+	public $fk_multicurrency;
126
+	public $multicurrency_code;
127
+	public $multicurrency_tx;
128
+	public $multicurrency_total_ht;
129
+	public $multicurrency_total_tva;
130
+	public $multicurrency_total_ttc;
131
+	//! id of source invoice if replacement invoice or credit note
132
+	public $fk_facture_source;
133
+
134
+	/**
135
+	 * Standard invoice
136
+	 */
137
+	const TYPE_STANDARD = 0;
138
+
139
+	/**
140
+	 * Replacement invoice
141
+	 */
142
+	const TYPE_REPLACEMENT = 1;
143
+
144
+	/**
145
+	 * Credit note invoice
146
+	 */
147
+	const TYPE_CREDIT_NOTE = 2;
148
+
149
+	/**
150
+	 * Deposit invoice
151
+	 */
152
+	const TYPE_DEPOSIT = 3;
153
+
154
+	/**
155
+	 * Draft
156
+	 */
157
+	const STATUS_DRAFT = 0;
158
+
159
+	/**
160
+	 * Validated (need to be paid)
161
+	 */
162
+	const STATUS_VALIDATED = 1;
163
+
164
+	/**
165
+	 * Classified paid.
166
+	 * If paid partially, $this->close_code can be:
167
+	 * - CLOSECODE_DISCOUNTVAT
168
+	 * - CLOSECODE_BADDEBT
169
+	 * If paid completelly, this->close_code will be null
170
+	 */
171
+	const STATUS_CLOSED = 2;
172
+
173
+	/**
174
+	 * Classified abandoned and no payment done.
175
+	 * $this->close_code can be:
176
+	 * - CLOSECODE_BADDEBT
177
+	 * - CLOSECODE_ABANDONED
178
+	 * - CLOSECODE_REPLACED
179
+	 */
180
+	const STATUS_ABANDONED = 3;
181 181
 
182 182
 	const CLOSECODE_DISCOUNTVAT = 'discount_vat';
183 183
 	const CLOSECODE_BADCREDIT = 'badsupplier';
184 184
 	const CLOSECODE_ABANDONED = 'abandon';
185 185
 	const CLOSECODE_REPLACED = 'replaced';
186 186
 
187
-    /**
187
+	/**
188 188
 	 *	Constructor
189 189
 	 *
190 190
 	 *  @param		DoliDB		$db      Database handler
191
-     */
192
-    public function __construct($db)
193
-    {
194
-        $this->db = $db;
195
-
196
-        $this->amount = 0;
197
-        $this->remise = 0;
198
-        $this->tva = 0;
199
-        $this->total_localtax1 = 0;
200
-        $this->total_localtax2 = 0;
201
-        $this->total_ht = 0;
202
-        $this->total_tva = 0;
203
-        $this->total_ttc = 0;
204
-        $this->propalid = 0;
205
-
206
-        $this->products = array();
207
-    }
208
-
209
-    /**
210
-     *    Create supplier invoice into database
211
-     *
212
-     *    @param      User		$user       object utilisateur qui cree
213
-     *    @return     int    	     		Id invoice created if OK, < 0 if KO
214
-     */
215
-    public function create($user)
216
-    {
217
-        global $langs,$conf,$hookmanager;
191
+	 */
192
+	public function __construct($db)
193
+	{
194
+		$this->db = $db;
195
+
196
+		$this->amount = 0;
197
+		$this->remise = 0;
198
+		$this->tva = 0;
199
+		$this->total_localtax1 = 0;
200
+		$this->total_localtax2 = 0;
201
+		$this->total_ht = 0;
202
+		$this->total_tva = 0;
203
+		$this->total_ttc = 0;
204
+		$this->propalid = 0;
205
+
206
+		$this->products = array();
207
+	}
208
+
209
+	/**
210
+	 *    Create supplier invoice into database
211
+	 *
212
+	 *    @param      User		$user       object utilisateur qui cree
213
+	 *    @return     int    	     		Id invoice created if OK, < 0 if KO
214
+	 */
215
+	public function create($user)
216
+	{
217
+		global $langs,$conf,$hookmanager;
218 218
 
219 219
 		$error=0;
220
-        $now=dol_now();
220
+		$now=dol_now();
221 221
 
222
-        // Clean parameters
223
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
224
-        if (empty($this->type)) $this->type = self::TYPE_STANDARD;
225
-        if (empty($this->date)) $this->date=$now;
222
+		// Clean parameters
223
+		if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
224
+		if (empty($this->type)) $this->type = self::TYPE_STANDARD;
225
+		if (empty($this->date)) $this->date=$now;
226 226
 
227
-        $socid = $this->socid;
228
-        $ref_supplier = $this->ref_supplier;
229
-        $amount = $this->amount;
230
-        $remise = $this->remise;
227
+		$socid = $this->socid;
228
+		$ref_supplier = $this->ref_supplier;
229
+		$amount = $this->amount;
230
+		$remise = $this->remise;
231 231
 
232 232
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
233 233
 		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
@@ -239,166 +239,166 @@  discard block
 block discarded – undo
239 239
 			$this->multicurrency_tx = 1;
240 240
 		}
241 241
 
242
-        $this->db->begin();
242
+		$this->db->begin();
243 243
 
244
-        if (! $remise) $remise = 0 ;
245
-        $totalht = ($amount - $remise);
244
+		if (! $remise) $remise = 0 ;
245
+		$totalht = ($amount - $remise);
246 246
 
247
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
247
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
248 248
 		$sql.= "ref";
249
-        $sql.= ", ref_supplier";
250
-        $sql.= ", entity";
251
-        $sql.= ", type";
252
-        $sql.= ", libelle";
253
-        $sql.= ", fk_soc";
254
-        $sql.= ", datec";
255
-        $sql.= ", datef";
249
+		$sql.= ", ref_supplier";
250
+		$sql.= ", entity";
251
+		$sql.= ", type";
252
+		$sql.= ", libelle";
253
+		$sql.= ", fk_soc";
254
+		$sql.= ", datec";
255
+		$sql.= ", datef";
256 256
 		$sql.= ", fk_projet";
257 257
 		$sql.= ", fk_cond_reglement";
258 258
 		$sql.= ", fk_mode_reglement";
259
-        $sql.= ", fk_account";
260
-        $sql.= ", note_private";
261
-        $sql.= ", note_public";
262
-        $sql.= ", fk_user_author";
263
-        $sql.= ", date_lim_reglement";
259
+		$sql.= ", fk_account";
260
+		$sql.= ", note_private";
261
+		$sql.= ", note_public";
262
+		$sql.= ", fk_user_author";
263
+		$sql.= ", date_lim_reglement";
264 264
 		$sql.= ", fk_incoterms, location_incoterms";
265
-        $sql.= ", fk_multicurrency";
266
-        $sql.= ", multicurrency_code";
267
-        $sql.= ", multicurrency_tx";
268
-        $sql.= ", fk_facture_source";
269
-        $sql.= ")";
270
-        $sql.= " VALUES (";
265
+		$sql.= ", fk_multicurrency";
266
+		$sql.= ", multicurrency_code";
267
+		$sql.= ", multicurrency_tx";
268
+		$sql.= ", fk_facture_source";
269
+		$sql.= ")";
270
+		$sql.= " VALUES (";
271 271
 		$sql.= "'(PROV)'";
272
-        $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
273
-        $sql.= ", ".$conf->entity;
274
-        $sql.= ", '".$this->db->escape($this->type)."'";
275
-        $sql.= ", '".$this->db->escape($this->libelle)."'";
276
-        $sql.= ", ".$this->socid;
277
-        $sql.= ", '".$this->db->idate($now)."'";
278
-        $sql.= ", '".$this->db->idate($this->date)."'";
272
+		$sql.= ", '".$this->db->escape($this->ref_supplier)."'";
273
+		$sql.= ", ".$conf->entity;
274
+		$sql.= ", '".$this->db->escape($this->type)."'";
275
+		$sql.= ", '".$this->db->escape($this->libelle)."'";
276
+		$sql.= ", ".$this->socid;
277
+		$sql.= ", '".$this->db->idate($now)."'";
278
+		$sql.= ", '".$this->db->idate($this->date)."'";
279 279
 		$sql.= ", ".(isset($this->fk_project)?$this->fk_project:"null");
280 280
 		$sql.= ", ".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null");
281 281
 		$sql.= ", ".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null");
282
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
283
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
284
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
285
-        $sql.= ", ".$user->id.",";
286
-        $sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null";
282
+		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
283
+		$sql.= ", '".$this->db->escape($this->note_private)."'";
284
+		$sql.= ", '".$this->db->escape($this->note_public)."'";
285
+		$sql.= ", ".$user->id.",";
286
+		$sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null";
287 287
 		$sql.= ", ".(int) $this->fk_incoterms;
288
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
288
+		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
289 289
 		$sql.= ", ".(int) $this->fk_multicurrency;
290 290
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
291 291
 		$sql.= ", ".(double) $this->multicurrency_tx;
292
-        $sql.= ", ".(isset($this->fk_facture_source)?$this->fk_facture_source:"NULL");
293
-        $sql.= ")";
294
-
295
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
296
-        $resql=$this->db->query($sql);
297
-        if ($resql)
298
-        {
299
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
300
-
301
-            // Update ref with new one
302
-            $this->ref='(PROV'.$this->id.')';
303
-            $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
304
-
305
-            dol_syslog(get_class($this)."::create", LOG_DEBUG);
306
-            $resql=$this->db->query($sql);
307
-            if (! $resql) $error++;
308
-
309
-            // Add object linked
310
-            if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id))
311
-            {
312
-                $ret = $this->add_object_linked();
313
-                if (! $ret)
314
-                {
315
-                    dol_print_error($this->db);
316
-                    $error++;
317
-                }
318
-            }
292
+		$sql.= ", ".(isset($this->fk_facture_source)?$this->fk_facture_source:"NULL");
293
+		$sql.= ")";
294
+
295
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
296
+		$resql=$this->db->query($sql);
297
+		if ($resql)
298
+		{
299
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
300
+
301
+			// Update ref with new one
302
+			$this->ref='(PROV'.$this->id.')';
303
+			$sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
304
+
305
+			dol_syslog(get_class($this)."::create", LOG_DEBUG);
306
+			$resql=$this->db->query($sql);
307
+			if (! $resql) $error++;
308
+
309
+			// Add object linked
310
+			if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id))
311
+			{
312
+				$ret = $this->add_object_linked();
313
+				if (! $ret)
314
+				{
315
+					dol_print_error($this->db);
316
+					$error++;
317
+				}
318
+			}
319 319
 
320 320
 			if (count($this->lines) && is_object($this->lines[0]))	// If this->lines is array of InvoiceLines (preferred mode)
321 321
 			{
322
-                dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
323
-                foreach ($this->lines as $i => $val)
324
-                {
325
-                    $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
326
-                    $sql .= ' VALUES ('.$this->id.')';
327
-
328
-                    $resql_insert=$this->db->query($sql);
329
-                    if ($resql_insert)
330
-                    {
331
-                        $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
332
-
333
-                        $this->updateline(
334
-                            $idligne,
335
-                            $this->lines[$i]->description,
336
-                            $this->lines[$i]->pu_ht,
337
-                            $this->lines[$i]->tva_tx,
338
-                            $this->lines[$i]->localtax1_tx,
339
-                            $this->lines[$i]->localtax2_tx,
340
-                            $this->lines[$i]->qty,
341
-                            $this->lines[$i]->fk_product,
342
-                            'HT',
343
-                            (! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''),
344
-                            $this->lines[$i]->product_type
345
-                        );
346
-                    }
347
-                    else
348
-                    {
349
-                        $this->error=$this->db->lasterror();
350
-                        $this->db->rollback();
351
-                        return -5;
352
-                    }
353
-                }
322
+				dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
323
+				foreach ($this->lines as $i => $val)
324
+				{
325
+					$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
326
+					$sql .= ' VALUES ('.$this->id.')';
327
+
328
+					$resql_insert=$this->db->query($sql);
329
+					if ($resql_insert)
330
+					{
331
+						$idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
332
+
333
+						$this->updateline(
334
+							$idligne,
335
+							$this->lines[$i]->description,
336
+							$this->lines[$i]->pu_ht,
337
+							$this->lines[$i]->tva_tx,
338
+							$this->lines[$i]->localtax1_tx,
339
+							$this->lines[$i]->localtax2_tx,
340
+							$this->lines[$i]->qty,
341
+							$this->lines[$i]->fk_product,
342
+							'HT',
343
+							(! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''),
344
+							$this->lines[$i]->product_type
345
+						);
346
+					}
347
+					else
348
+					{
349
+						$this->error=$this->db->lasterror();
350
+						$this->db->rollback();
351
+						return -5;
352
+					}
353
+				}
354 354
 			}
355 355
 			else	// If this->lines is an array of invoice line arrays
356 356
 			{
357
-			    dol_syslog("There is ".count($this->lines)." lines that are array lines");
358
-			    foreach ($this->lines as $i => $val)
359
-			    {
360
-                	$line = $this->lines[$i];
361
-
362
-                	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
363
-				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
364
-                	if (! is_object($line)) $line = (object) $line;
365
-
366
-                	$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
367
-			        $sql .= ' VALUES ('.$this->id.')';
368
-
369
-			        $resql_insert=$this->db->query($sql);
370
-			        if ($resql_insert)
371
-			        {
372
-			            $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
373
-
374
-			            $this->updateline(
375
-			                $idligne,
376
-			                $line->description,
377
-			                $line->pu_ht,
378
-			                $line->tva_tx,
379
-			                $line->localtax1_tx,
380
-			                $line->localtax2_tx,
381
-			                $line->qty,
382
-			                $line->fk_product,
383
-			                'HT',
384
-			                (! empty($line->info_bits)?$line->info_bits:''),
385
-			                $line->product_type
386
-			                );
387
-			        }
388
-			        else
389
-			        {
390
-			            $this->error=$this->db->lasterror();
391
-			            $this->db->rollback();
392
-			            return -5;
393
-			        }
394
-			    }
357
+				dol_syslog("There is ".count($this->lines)." lines that are array lines");
358
+				foreach ($this->lines as $i => $val)
359
+				{
360
+					$line = $this->lines[$i];
361
+
362
+					// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
363
+					//if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
364
+					if (! is_object($line)) $line = (object) $line;
365
+
366
+					$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
367
+					$sql .= ' VALUES ('.$this->id.')';
368
+
369
+					$resql_insert=$this->db->query($sql);
370
+					if ($resql_insert)
371
+					{
372
+						$idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
373
+
374
+						$this->updateline(
375
+							$idligne,
376
+							$line->description,
377
+							$line->pu_ht,
378
+							$line->tva_tx,
379
+							$line->localtax1_tx,
380
+							$line->localtax2_tx,
381
+							$line->qty,
382
+							$line->fk_product,
383
+							'HT',
384
+							(! empty($line->info_bits)?$line->info_bits:''),
385
+							$line->product_type
386
+							);
387
+					}
388
+					else
389
+					{
390
+						$this->error=$this->db->lasterror();
391
+						$this->db->rollback();
392
+						return -5;
393
+					}
394
+				}
395 395
 			}
396 396
 
397
-            // Update total price
398
-            $result=$this->update_price();
399
-            if ($result > 0)
400
-            {
401
-            	$action='create';
397
+			// Update total price
398
+			$result=$this->update_price();
399
+			if ($result > 0)
400
+			{
401
+				$action='create';
402 402
 
403 403
 				// Actions on extra fields (by external module or standard code)
404 404
 				// TODO le hook fait double emploi avec le trigger !!
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 				$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
408 408
 				if (empty($reshook))
409 409
 				{
410
-	            	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
410
+					if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
411 411
 					{
412 412
 						$result=$this->insertExtraFields();               // This also set $this->error or $this->errors if errors are found
413 413
 						if ($result < 0)
@@ -420,164 +420,164 @@  discard block
 block discarded – undo
420 420
 
421 421
 				if (! $error)
422 422
 				{
423
-                    // Call trigger
424
-                    $result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user);
425
-                    if ($result < 0) $error++;
426
-                    // End call triggers
423
+					// Call trigger
424
+					$result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user);
425
+					if ($result < 0) $error++;
426
+					// End call triggers
427
+				}
428
+
429
+				if (! $error)
430
+				{
431
+					$this->db->commit();
432
+					return $this->id;
433
+				}
434
+				else
435
+				{
436
+					$this->db->rollback();
437
+					return -4;
427 438
 				}
439
+			}
440
+			else
441
+			{
442
+				$this->error=$langs->trans('FailedToUpdatePrice');
443
+				$this->db->rollback();
444
+				return -3;
445
+			}
446
+		}
447
+		else
448
+		{
449
+			if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
450
+			{
451
+				$this->error=$langs->trans('ErrorRefAlreadyExists');
452
+				$this->db->rollback();
453
+				return -1;
454
+			}
455
+			else
456
+			{
457
+				$this->error=$this->db->lasterror();
458
+				$this->db->rollback();
459
+				return -2;
460
+			}
461
+		}
462
+	}
428 463
 
429
-                if (! $error)
430
-                {
431
-                    $this->db->commit();
432
-                    return $this->id;
433
-                }
434
-                else
435
-                {
436
-                    $this->db->rollback();
437
-                    return -4;
438
-                }
439
-            }
440
-            else
441
-            {
442
-                $this->error=$langs->trans('FailedToUpdatePrice');
443
-                $this->db->rollback();
444
-                return -3;
445
-            }
446
-        }
447
-        else
448
-        {
449
-            if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
450
-            {
451
-                $this->error=$langs->trans('ErrorRefAlreadyExists');
452
-                $this->db->rollback();
453
-                return -1;
454
-            }
455
-            else
456
-            {
457
-                $this->error=$this->db->lasterror();
458
-                $this->db->rollback();
459
-                return -2;
460
-            }
461
-        }
462
-    }
463
-
464
-    /**
465
-     *    Load object in memory from database
466
-     *
467
-     *    @param	int		$id         Id supplier invoice
468
-     *    @param	string	$ref		Ref supplier invoice
469
-     *    @return   int        			<0 if KO, >0 if OK, 0 if not found
470
-     */
471
-    public function fetch($id='',$ref='')
472
-    {
473
-        global $langs;
474
-
475
-        $sql = "SELECT";
476
-        $sql.= " t.rowid,";
464
+	/**
465
+	 *    Load object in memory from database
466
+	 *
467
+	 *    @param	int		$id         Id supplier invoice
468
+	 *    @param	string	$ref		Ref supplier invoice
469
+	 *    @return   int        			<0 if KO, >0 if OK, 0 if not found
470
+	 */
471
+	public function fetch($id='',$ref='')
472
+	{
473
+		global $langs;
474
+
475
+		$sql = "SELECT";
476
+		$sql.= " t.rowid,";
477 477
 		$sql.= " t.ref,";
478
-        $sql.= " t.ref_supplier,";
479
-        $sql.= " t.entity,";
480
-        $sql.= " t.type,";
481
-        $sql.= " t.fk_soc,";
482
-        $sql.= " t.datec,";
483
-        $sql.= " t.datef,";
484
-        $sql.= " t.tms,";
485
-        $sql.= " t.libelle,";
486
-        $sql.= " t.paye,";
487
-        $sql.= " t.amount,";
488
-        $sql.= " t.remise,";
489
-        $sql.= " t.close_code,";
490
-        $sql.= " t.close_note,";
491
-        $sql.= " t.tva,";
492
-        $sql.= " t.localtax1,";
493
-        $sql.= " t.localtax2,";
494
-        //$sql.= " t.total,";
495
-        $sql.= " t.total_ht,";
496
-        $sql.= " t.total_tva,";
497
-        $sql.= " t.total_ttc,";
498
-        $sql.= " t.fk_statut,";
499
-        $sql.= " t.fk_user_author,";
500
-        $sql.= " t.fk_user_valid,";
501
-        $sql.= " t.fk_facture_source,";
502
-        $sql.= " t.fk_projet,";
503
-        $sql.= " t.fk_cond_reglement,";
504
-        $sql.= " t.fk_account,";
505
-        $sql.= " t.fk_mode_reglement,";
506
-        $sql.= " t.date_lim_reglement,";
507
-        $sql.= " t.note_private,";
508
-        $sql.= " t.note_public,";
509
-        $sql.= " t.model_pdf,";
510
-        $sql.= " t.import_key,";
511
-        $sql.= " t.extraparams,";
512
-        $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
513
-        $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
514
-        $sql.= ' s.nom as socnom, s.rowid as socid,';
515
-        $sql.= ' t.fk_incoterms, t.location_incoterms,';
516
-        $sql.= " i.libelle as libelle_incoterms,";
517
-        $sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
518
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
519
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
520
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
521
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
478
+		$sql.= " t.ref_supplier,";
479
+		$sql.= " t.entity,";
480
+		$sql.= " t.type,";
481
+		$sql.= " t.fk_soc,";
482
+		$sql.= " t.datec,";
483
+		$sql.= " t.datef,";
484
+		$sql.= " t.tms,";
485
+		$sql.= " t.libelle,";
486
+		$sql.= " t.paye,";
487
+		$sql.= " t.amount,";
488
+		$sql.= " t.remise,";
489
+		$sql.= " t.close_code,";
490
+		$sql.= " t.close_note,";
491
+		$sql.= " t.tva,";
492
+		$sql.= " t.localtax1,";
493
+		$sql.= " t.localtax2,";
494
+		//$sql.= " t.total,";
495
+		$sql.= " t.total_ht,";
496
+		$sql.= " t.total_tva,";
497
+		$sql.= " t.total_ttc,";
498
+		$sql.= " t.fk_statut,";
499
+		$sql.= " t.fk_user_author,";
500
+		$sql.= " t.fk_user_valid,";
501
+		$sql.= " t.fk_facture_source,";
502
+		$sql.= " t.fk_projet,";
503
+		$sql.= " t.fk_cond_reglement,";
504
+		$sql.= " t.fk_account,";
505
+		$sql.= " t.fk_mode_reglement,";
506
+		$sql.= " t.date_lim_reglement,";
507
+		$sql.= " t.note_private,";
508
+		$sql.= " t.note_public,";
509
+		$sql.= " t.model_pdf,";
510
+		$sql.= " t.import_key,";
511
+		$sql.= " t.extraparams,";
512
+		$sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
513
+		$sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
514
+		$sql.= ' s.nom as socnom, s.rowid as socid,';
515
+		$sql.= ' t.fk_incoterms, t.location_incoterms,';
516
+		$sql.= " i.libelle as libelle_incoterms,";
517
+		$sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
518
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
519
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
520
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
521
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
522 522
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
523
-        if ($id)  $sql.= " WHERE t.rowid=".$id;
524
-        if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
525
-
526
-        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
527
-        $resql=$this->db->query($sql);
528
-        if ($resql)
529
-        {
530
-            if ($this->db->num_rows($resql))
531
-            {
532
-                $obj = $this->db->fetch_object($resql);
533
-
534
-                $this->id					= $obj->rowid;
535
-                $this->ref					= $obj->ref?$obj->ref:$obj->rowid;	// We take rowid if ref is empty for backward compatibility
536
-
537
-                $this->ref_supplier			= $obj->ref_supplier;
538
-                $this->entity				= $obj->entity;
539
-                $this->type					= empty($obj->type)? self::TYPE_STANDARD:$obj->type;
540
-                $this->fk_soc				= $obj->fk_soc;
541
-                $this->datec				= $this->db->jdate($obj->datec);
542
-                $this->date					= $this->db->jdate($obj->datef);
543
-                $this->datep				= $this->db->jdate($obj->datef);
544
-                $this->tms					= $this->db->jdate($obj->tms);
545
-                $this->libelle				= $obj->libelle;
546
-                $this->label				= $obj->libelle;
547
-                $this->paye					= $obj->paye;
548
-                $this->amount				= $obj->amount;
549
-                $this->remise				= $obj->remise;
550
-                $this->close_code			= $obj->close_code;
551
-                $this->close_note			= $obj->close_note;
552
-                $this->tva					= $obj->tva;
553
-                $this->total_localtax1		= $obj->localtax1;
554
-                $this->total_localtax2		= $obj->localtax2;
555
-                //$this->total				= $obj->total;
556
-                $this->total_ht				= $obj->total_ht;
557
-                $this->total_tva			= $obj->total_tva;
558
-                $this->total_ttc			= $obj->total_ttc;
559
-                $this->fk_statut			= $obj->fk_statut;
560
-                $this->statut				= $obj->fk_statut;
561
-                $this->fk_user_author		= $obj->fk_user_author;
562
-                $this->author				= $obj->fk_user_author;
563
-                $this->fk_user_valid		= $obj->fk_user_valid;
564
-                $this->fk_facture_source	= $obj->fk_facture_source;
565
-                $this->fk_project			= $obj->fk_projet;
566
-	            $this->cond_reglement_id	= $obj->fk_cond_reglement;
567
-	            $this->cond_reglement_code	= $obj->cond_reglement_code;
568
-	            $this->cond_reglement		= $obj->cond_reglement_libelle;
569
-	            $this->cond_reglement_doc	= $obj->cond_reglement_libelle;
570
-                $this->fk_account           = $obj->fk_account;
571
-	            $this->mode_reglement_id	= $obj->fk_mode_reglement;
572
-	            $this->mode_reglement_code	= $obj->mode_reglement_code;
573
-	            $this->mode_reglement		= $obj->mode_reglement_libelle;
574
-                $this->date_echeance		= $this->db->jdate($obj->date_lim_reglement);
575
-                $this->note					= $obj->note_private;	// deprecated
576
-                $this->note_private			= $obj->note_private;
577
-                $this->note_public			= $obj->note_public;
578
-                $this->model_pdf			= $obj->model_pdf;
579
-                $this->modelpdf			    = $obj->model_pdf;
580
-                $this->import_key			= $obj->import_key;
523
+		if ($id)  $sql.= " WHERE t.rowid=".$id;
524
+		if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
525
+
526
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
527
+		$resql=$this->db->query($sql);
528
+		if ($resql)
529
+		{
530
+			if ($this->db->num_rows($resql))
531
+			{
532
+				$obj = $this->db->fetch_object($resql);
533
+
534
+				$this->id					= $obj->rowid;
535
+				$this->ref					= $obj->ref?$obj->ref:$obj->rowid;	// We take rowid if ref is empty for backward compatibility
536
+
537
+				$this->ref_supplier			= $obj->ref_supplier;
538
+				$this->entity				= $obj->entity;
539
+				$this->type					= empty($obj->type)? self::TYPE_STANDARD:$obj->type;
540
+				$this->fk_soc				= $obj->fk_soc;
541
+				$this->datec				= $this->db->jdate($obj->datec);
542
+				$this->date					= $this->db->jdate($obj->datef);
543
+				$this->datep				= $this->db->jdate($obj->datef);
544
+				$this->tms					= $this->db->jdate($obj->tms);
545
+				$this->libelle				= $obj->libelle;
546
+				$this->label				= $obj->libelle;
547
+				$this->paye					= $obj->paye;
548
+				$this->amount				= $obj->amount;
549
+				$this->remise				= $obj->remise;
550
+				$this->close_code			= $obj->close_code;
551
+				$this->close_note			= $obj->close_note;
552
+				$this->tva					= $obj->tva;
553
+				$this->total_localtax1		= $obj->localtax1;
554
+				$this->total_localtax2		= $obj->localtax2;
555
+				//$this->total				= $obj->total;
556
+				$this->total_ht				= $obj->total_ht;
557
+				$this->total_tva			= $obj->total_tva;
558
+				$this->total_ttc			= $obj->total_ttc;
559
+				$this->fk_statut			= $obj->fk_statut;
560
+				$this->statut				= $obj->fk_statut;
561
+				$this->fk_user_author		= $obj->fk_user_author;
562
+				$this->author				= $obj->fk_user_author;
563
+				$this->fk_user_valid		= $obj->fk_user_valid;
564
+				$this->fk_facture_source	= $obj->fk_facture_source;
565
+				$this->fk_project			= $obj->fk_projet;
566
+				$this->cond_reglement_id	= $obj->fk_cond_reglement;
567
+				$this->cond_reglement_code	= $obj->cond_reglement_code;
568
+				$this->cond_reglement		= $obj->cond_reglement_libelle;
569
+				$this->cond_reglement_doc	= $obj->cond_reglement_libelle;
570
+				$this->fk_account           = $obj->fk_account;
571
+				$this->mode_reglement_id	= $obj->fk_mode_reglement;
572
+				$this->mode_reglement_code	= $obj->mode_reglement_code;
573
+				$this->mode_reglement		= $obj->mode_reglement_libelle;
574
+				$this->date_echeance		= $this->db->jdate($obj->date_lim_reglement);
575
+				$this->note					= $obj->note_private;	// deprecated
576
+				$this->note_private			= $obj->note_private;
577
+				$this->note_public			= $obj->note_public;
578
+				$this->model_pdf			= $obj->model_pdf;
579
+				$this->modelpdf			    = $obj->model_pdf;
580
+				$this->import_key			= $obj->import_key;
581 581
 
582 582
 				//Incoterms
583 583
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -592,114 +592,114 @@  discard block
 block discarded – undo
592 592
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
593 593
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
594 594
 
595
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
596
-
597
-                $this->socid  = $obj->socid;
598
-                $this->socnom = $obj->socnom;
599
-
600
-                // Retreive all extrafield
601
-                // fetch optionals attributes and labels
602
-                require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
603
-                $extrafields=new ExtraFields($this->db);
604
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
605
-                $this->fetch_optionals($this->id,$extralabels);
606
-
607
-                if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
608
-
609
-                $result=$this->fetch_lines();
610
-                if ($result < 0)
611
-                {
612
-                    $this->error=$this->db->lasterror();
613
-                    return -3;
614
-                }
615
-
616
-            }
617
-            else
618
-            {
619
-                $this->error='Bill with id '.$id.' not found';
620
-                dol_syslog(get_class($this).'::fetch '.$this->error);
621
-                return 0;
622
-            }
623
-
624
-            $this->db->free($resql);
625
-            return 1;
626
-        }
627
-        else
628
-        {
629
-            $this->error="Error ".$this->db->lasterror();
630
-            return -1;
631
-        }
632
-    }
633
-
634
-
635
-    /**
636
-     *	Load this->lines
637
-     *
638
-     *	@return     int         1 si ok, < 0 si erreur
639
-     */
640
-    function fetch_lines()
641
-    {
642
-        $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
643
-        $sql.= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
644
-        $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
645
-        $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
595
+				$this->extraparams			= (array) json_decode($obj->extraparams, true);
596
+
597
+				$this->socid  = $obj->socid;
598
+				$this->socnom = $obj->socnom;
599
+
600
+				// Retreive all extrafield
601
+				// fetch optionals attributes and labels
602
+				require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
603
+				$extrafields=new ExtraFields($this->db);
604
+				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
605
+				$this->fetch_optionals($this->id,$extralabels);
606
+
607
+				if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
608
+
609
+				$result=$this->fetch_lines();
610
+				if ($result < 0)
611
+				{
612
+					$this->error=$this->db->lasterror();
613
+					return -3;
614
+				}
615
+
616
+			}
617
+			else
618
+			{
619
+				$this->error='Bill with id '.$id.' not found';
620
+				dol_syslog(get_class($this).'::fetch '.$this->error);
621
+				return 0;
622
+			}
623
+
624
+			$this->db->free($resql);
625
+			return 1;
626
+		}
627
+		else
628
+		{
629
+			$this->error="Error ".$this->db->lasterror();
630
+			return -1;
631
+		}
632
+	}
633
+
634
+
635
+	/**
636
+	 *	Load this->lines
637
+	 *
638
+	 *	@return     int         1 si ok, < 0 si erreur
639
+	 */
640
+	function fetch_lines()
641
+	{
642
+		$sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
643
+		$sql.= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
644
+		$sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
645
+		$sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
646 646
 		$sql.= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
647
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
648
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
649
-        $sql.= ' WHERE fk_facture_fourn='.$this->id;
650
-        $sql.= ' ORDER BY f.rang, f.rowid';
651
-
652
-
653
-        dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
654
-        $resql_rows = $this->db->query($sql);
655
-        if ($resql_rows)
656
-        {
657
-            $num_rows = $this->db->num_rows($resql_rows);
658
-            if ($num_rows)
659
-            {
660
-                $i = 0;
661
-                while ($i < $num_rows)
662
-                {
663
-                    $obj = $this->db->fetch_object($resql_rows);
664
-
665
-	                $line = new SupplierInvoiceLine($this->db);
666
-
667
-                    $line->id				= $obj->rowid;
668
-                    $line->rowid			= $obj->rowid;
669
-                    $line->description		= $obj->description;
670
-                    $line->product_ref		= $obj->product_ref;
671
-                    $line->ref				= $obj->product_ref;
672
-                    $line->ref_supplier		= $obj->ref_supplier;
673
-                    $line->libelle			= $obj->label;
674
-                    $line->label  			= $obj->label;
675
-                    $line->product_desc		= $obj->product_desc;
676
-                    $line->subprice			= $obj->pu_ht;
677
-                    $line->pu_ht			= $obj->pu_ht;
678
-                    $line->pu_ttc			= $obj->pu_ttc;
679
-
680
-                    $line->vat_src_code     = $obj->vat_src_code;
681
-                    $line->tva_tx			= $obj->tva_tx;
682
-                    $line->localtax1_tx		= $obj->localtax1_tx;
683
-                    $line->localtax2_tx		= $obj->localtax2_tx;
684
-                    $line->localtax1_type	= $obj->localtax1_type;
685
-                    $line->localtax2_type	= $obj->localtax2_type;
686
-                    $line->qty				= $obj->qty;
687
-                    $line->remise_percent   = $obj->remise_percent;
688
-                    $line->tva				= $obj->total_tva;
689
-                    $line->total_ht			= $obj->total_ht;
690
-                    $line->total_tva		= $obj->total_tva;
691
-                    $line->total_localtax1	= $obj->total_localtax1;
692
-                    $line->total_localtax2	= $obj->total_localtax2;
693
-                    $line->fk_facture_fourn     = $obj->fk_facture_fourn;
694
-                    $line->total_ttc		= $obj->total_ttc;
695
-                    $line->fk_product		= $obj->fk_product;
696
-                    $line->product_type		= $obj->product_type;
697
-                    $line->product_label	= $obj->label;
698
-                    $line->info_bits		= $obj->info_bits;
699
-                    $line->fk_parent_line   = $obj->fk_parent_line;
700
-                    $line->special_code		= $obj->special_code;
701
-                    $line->rang       		= $obj->rang;
702
-                    $line->fk_unit          = $obj->fk_unit;
647
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
648
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
649
+		$sql.= ' WHERE fk_facture_fourn='.$this->id;
650
+		$sql.= ' ORDER BY f.rang, f.rowid';
651
+
652
+
653
+		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
654
+		$resql_rows = $this->db->query($sql);
655
+		if ($resql_rows)
656
+		{
657
+			$num_rows = $this->db->num_rows($resql_rows);
658
+			if ($num_rows)
659
+			{
660
+				$i = 0;
661
+				while ($i < $num_rows)
662
+				{
663
+					$obj = $this->db->fetch_object($resql_rows);
664
+
665
+					$line = new SupplierInvoiceLine($this->db);
666
+
667
+					$line->id				= $obj->rowid;
668
+					$line->rowid			= $obj->rowid;
669
+					$line->description		= $obj->description;
670
+					$line->product_ref		= $obj->product_ref;
671
+					$line->ref				= $obj->product_ref;
672
+					$line->ref_supplier		= $obj->ref_supplier;
673
+					$line->libelle			= $obj->label;
674
+					$line->label  			= $obj->label;
675
+					$line->product_desc		= $obj->product_desc;
676
+					$line->subprice			= $obj->pu_ht;
677
+					$line->pu_ht			= $obj->pu_ht;
678
+					$line->pu_ttc			= $obj->pu_ttc;
679
+
680
+					$line->vat_src_code     = $obj->vat_src_code;
681
+					$line->tva_tx			= $obj->tva_tx;
682
+					$line->localtax1_tx		= $obj->localtax1_tx;
683
+					$line->localtax2_tx		= $obj->localtax2_tx;
684
+					$line->localtax1_type	= $obj->localtax1_type;
685
+					$line->localtax2_type	= $obj->localtax2_type;
686
+					$line->qty				= $obj->qty;
687
+					$line->remise_percent   = $obj->remise_percent;
688
+					$line->tva				= $obj->total_tva;
689
+					$line->total_ht			= $obj->total_ht;
690
+					$line->total_tva		= $obj->total_tva;
691
+					$line->total_localtax1	= $obj->total_localtax1;
692
+					$line->total_localtax2	= $obj->total_localtax2;
693
+					$line->fk_facture_fourn     = $obj->fk_facture_fourn;
694
+					$line->total_ttc		= $obj->total_ttc;
695
+					$line->fk_product		= $obj->fk_product;
696
+					$line->product_type		= $obj->product_type;
697
+					$line->product_label	= $obj->label;
698
+					$line->info_bits		= $obj->info_bits;
699
+					$line->fk_parent_line   = $obj->fk_parent_line;
700
+					$line->special_code		= $obj->special_code;
701
+					$line->rang       		= $obj->rang;
702
+					$line->fk_unit          = $obj->fk_unit;
703 703
 
704 704
 					// Multicurrency
705 705
 					$line->fk_multicurrency 		= $obj->fk_multicurrency;
@@ -709,201 +709,201 @@  discard block
 block discarded – undo
709 709
 					$line->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
710 710
 					$line->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
711 711
 
712
-	                $this->lines[$i] = $line;
713
-
714
-                    $i++;
715
-                }
716
-            }
717
-            $this->db->free($resql_rows);
718
-            return 1;
719
-        }
720
-        else
721
-        {
722
-            $this->error=$this->db->error();
723
-            return -3;
724
-        }
725
-    }
726
-
727
-
728
-    /**
729
-     *  Update database
730
-     *
731
-     *  @param	User	$user            User that modify
732
-     *  @param  int		$notrigger       0=launch triggers after, 1=disable triggers
733
-     *  @return int 			         <0 if KO, >0 if OK
734
-     */
735
-    public function update($user=null, $notrigger=0)
736
-    {
737
-        global $conf, $langs;
738
-        $error=0;
739
-
740
-        // Clean parameters
741
-        if (empty($this->type)) $this->type= self::TYPE_STANDARD;
712
+					$this->lines[$i] = $line;
713
+
714
+					$i++;
715
+				}
716
+			}
717
+			$this->db->free($resql_rows);
718
+			return 1;
719
+		}
720
+		else
721
+		{
722
+			$this->error=$this->db->error();
723
+			return -3;
724
+		}
725
+	}
726
+
727
+
728
+	/**
729
+	 *  Update database
730
+	 *
731
+	 *  @param	User	$user            User that modify
732
+	 *  @param  int		$notrigger       0=launch triggers after, 1=disable triggers
733
+	 *  @return int 			         <0 if KO, >0 if OK
734
+	 */
735
+	public function update($user=null, $notrigger=0)
736
+	{
737
+		global $conf, $langs;
738
+		$error=0;
739
+
740
+		// Clean parameters
741
+		if (empty($this->type)) $this->type= self::TYPE_STANDARD;
742 742
 		if (isset($this->ref)) $this->ref=trim($this->ref);
743
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
744
-        if (isset($this->entity)) $this->entity=trim($this->entity);
745
-        if (isset($this->type)) $this->type=trim($this->type);
746
-        if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
747
-        if (isset($this->libelle)) $this->libelle=trim($this->libelle);
748
-        if (isset($this->paye)) $this->paye=trim($this->paye);
749
-        if (isset($this->amount)) $this->amount=trim($this->amount);
750
-        if (isset($this->remise)) $this->remise=trim($this->remise);
751
-        if (isset($this->close_code)) $this->close_code=trim($this->close_code);
752
-        if (isset($this->close_note)) $this->close_note=trim($this->close_note);
753
-        if (isset($this->tva)) $this->tva=trim($this->tva);
754
-        if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1);
755
-        if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2);
756
-        if (empty($this->total_ht)) $this->total_ht=0;
757
-        if (empty($this->total_tva)) $this->total_tva=0;
758
-        //	if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
759
-        //	if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
760
-        if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
761
-        if (isset($this->statut)) $this->statut=(int) $this->statut;
762
-        if (isset($this->author)) $this->author=trim($this->author);
763
-        if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
764
-        if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
765
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
766
-        if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
767
-        if (isset($this->note_private)) $this->note=trim($this->note_private);
768
-        if (isset($this->note_public)) $this->note_public=trim($this->note_public);
769
-        if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
770
-        if (isset($this->import_key)) $this->import_key=trim($this->import_key);
771
-
772
-
773
-        // Check parameters
774
-        // Put here code to add control on parameters values
775
-
776
-        // Update request
777
-        $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
743
+		if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
744
+		if (isset($this->entity)) $this->entity=trim($this->entity);
745
+		if (isset($this->type)) $this->type=trim($this->type);
746
+		if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
747
+		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
748
+		if (isset($this->paye)) $this->paye=trim($this->paye);
749
+		if (isset($this->amount)) $this->amount=trim($this->amount);
750
+		if (isset($this->remise)) $this->remise=trim($this->remise);
751
+		if (isset($this->close_code)) $this->close_code=trim($this->close_code);
752
+		if (isset($this->close_note)) $this->close_note=trim($this->close_note);
753
+		if (isset($this->tva)) $this->tva=trim($this->tva);
754
+		if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1);
755
+		if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2);
756
+		if (empty($this->total_ht)) $this->total_ht=0;
757
+		if (empty($this->total_tva)) $this->total_tva=0;
758
+		//	if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
759
+		//	if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
760
+		if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
761
+		if (isset($this->statut)) $this->statut=(int) $this->statut;
762
+		if (isset($this->author)) $this->author=trim($this->author);
763
+		if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
764
+		if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
765
+		if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
766
+		if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
767
+		if (isset($this->note_private)) $this->note=trim($this->note_private);
768
+		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
769
+		if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
770
+		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
771
+
772
+
773
+		// Check parameters
774
+		// Put here code to add control on parameters values
775
+
776
+		// Update request
777
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
778 778
 		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
779
-        $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
780
-        $sql.= " entity=".(isset($this->entity)?$this->entity:"null").",";
781
-        $sql.= " type=".(isset($this->type)?$this->type:"null").",";
782
-        $sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").",";
783
-        $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
784
-        $sql.= " datef=".(dol_strlen($this->date)!=0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
785
-        if (dol_strlen($this->tms) != 0) $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
786
-        $sql.= " libelle=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
787
-        $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
788
-        $sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
789
-        $sql.= " remise=".(isset($this->remise)?$this->remise:"null").",";
790
-        $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
791
-        $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
792
-        $sql.= " tva=".(isset($this->tva)?$this->tva:"null").",";
793
-        $sql.= " localtax1=".(isset($this->localtax1)?$this->localtax1:"null").",";
794
-        $sql.= " localtax2=".(isset($this->localtax2)?$this->localtax2:"null").",";
795
-        //$sql.= " total=".(isset($this->total)?$this->total:"null").",";
796
-        $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
797
-        $sql.= " total_tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
798
-        $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
799
-        $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
800
-        $sql.= " fk_user_author=".(isset($this->author)?$this->author:"null").",";
801
-        $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
802
-        $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
803
-        $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
804
-        $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
805
-        $sql.= " date_lim_reglement=".(dol_strlen($this->date_echeance)!=0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
806
-        $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
807
-        $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
808
-        $sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
809
-        $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
810
-        $sql.= " WHERE rowid=".$this->id;
811
-
812
-        $this->db->begin();
813
-
814
-        dol_syslog(get_class($this)."::update", LOG_DEBUG);
815
-        $resql = $this->db->query($sql);
816
-
817
-        if (!$resql) {
818
-            $error++;
819
-
820
-            if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
821
-                $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
822
-            } else {
823
-                $this->errors[] = "Error ".$this->db->lasterror();
824
-            }
825
-        }
826
-
827
-        if (! $error)
828
-        {
829
-            if (! $notrigger)
830
-            {
831
-                // Call trigger
832
-                $result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user);
833
-                if ($result < 0) $error++;
834
-                // End call triggers
835
-            }
836
-        }
837
-
838
-        // Commit or rollback
839
-        if ($error)
840
-        {
841
-            foreach($this->errors as $errmsg)
842
-            {
843
-                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
844
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
845
-            }
846
-            $this->db->rollback();
847
-            return -1*$error;
848
-        }
849
-        else
850
-        {
851
-            $this->db->commit();
852
-            return 1;
853
-        }
854
-    }
855
-
856
-
857
-    /**
858
-     *	Delete invoice from database
859
-     *
860
-     *  @param      User	$user		    User object
861
-     *	@param	    int		$notrigger	    1=Does not execute triggers, 0= execute triggers
862
-     *	@return		int						<0 if KO, >0 if OK
863
-     */
864
-    public function delete(User $user, $notrigger=0)
865
-    {
866
-        global $langs,$conf;
867
-
868
-        $rowid=$this->id;
869
-
870
-        dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
871
-
872
-        // TODO Test if there is at least on payment. If yes, refuse to delete.
873
-
874
-        $error=0;
875
-        $this->db->begin();
876
-
877
-        if (! $error && ! $notrigger)
878
-        {
879
-            // Call trigger
880
-            $result=$this->call_trigger('BILL_SUPPLIER_DELETE',$user);
881
-            if ($result < 0)
882
-            {
883
-                $this->db->rollback();
884
-                return -1;
885
-            }
886
-            // Fin appel triggers
887
-        }
888
-
889
-        if (! $error)
890
-        {
891
-            $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
892
-            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
893
-            $resql = $this->db->query($sql);
894
-            if ($resql)
895
-            {
896
-                $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
897
-                dol_syslog(get_class($this)."::delete", LOG_DEBUG);
898
-                $resql2 = $this->db->query($sql);
899
-                if (! $resql2) {
900
-                	$error++;
901
-                }
902
-            }
903
-            else {
904
-            	$error++;
905
-            }
906
-        }
779
+		$sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
780
+		$sql.= " entity=".(isset($this->entity)?$this->entity:"null").",";
781
+		$sql.= " type=".(isset($this->type)?$this->type:"null").",";
782
+		$sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").",";
783
+		$sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
784
+		$sql.= " datef=".(dol_strlen($this->date)!=0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
785
+		if (dol_strlen($this->tms) != 0) $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
786
+		$sql.= " libelle=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
787
+		$sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
788
+		$sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
789
+		$sql.= " remise=".(isset($this->remise)?$this->remise:"null").",";
790
+		$sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
791
+		$sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
792
+		$sql.= " tva=".(isset($this->tva)?$this->tva:"null").",";
793
+		$sql.= " localtax1=".(isset($this->localtax1)?$this->localtax1:"null").",";
794
+		$sql.= " localtax2=".(isset($this->localtax2)?$this->localtax2:"null").",";
795
+		//$sql.= " total=".(isset($this->total)?$this->total:"null").",";
796
+		$sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
797
+		$sql.= " total_tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
798
+		$sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
799
+		$sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
800
+		$sql.= " fk_user_author=".(isset($this->author)?$this->author:"null").",";
801
+		$sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
802
+		$sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
803
+		$sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
804
+		$sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
805
+		$sql.= " date_lim_reglement=".(dol_strlen($this->date_echeance)!=0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
806
+		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
807
+		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
808
+		$sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
809
+		$sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
810
+		$sql.= " WHERE rowid=".$this->id;
811
+
812
+		$this->db->begin();
813
+
814
+		dol_syslog(get_class($this)."::update", LOG_DEBUG);
815
+		$resql = $this->db->query($sql);
816
+
817
+		if (!$resql) {
818
+			$error++;
819
+
820
+			if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
821
+				$this->errors[] = $langs->trans('ErrorRefAlreadyExists');
822
+			} else {
823
+				$this->errors[] = "Error ".$this->db->lasterror();
824
+			}
825
+		}
826
+
827
+		if (! $error)
828
+		{
829
+			if (! $notrigger)
830
+			{
831
+				// Call trigger
832
+				$result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user);
833
+				if ($result < 0) $error++;
834
+				// End call triggers
835
+			}
836
+		}
837
+
838
+		// Commit or rollback
839
+		if ($error)
840
+		{
841
+			foreach($this->errors as $errmsg)
842
+			{
843
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
844
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
845
+			}
846
+			$this->db->rollback();
847
+			return -1*$error;
848
+		}
849
+		else
850
+		{
851
+			$this->db->commit();
852
+			return 1;
853
+		}
854
+	}
855
+
856
+
857
+	/**
858
+	 *	Delete invoice from database
859
+	 *
860
+	 *  @param      User	$user		    User object
861
+	 *	@param	    int		$notrigger	    1=Does not execute triggers, 0= execute triggers
862
+	 *	@return		int						<0 if KO, >0 if OK
863
+	 */
864
+	public function delete(User $user, $notrigger=0)
865
+	{
866
+		global $langs,$conf;
867
+
868
+		$rowid=$this->id;
869
+
870
+		dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
871
+
872
+		// TODO Test if there is at least on payment. If yes, refuse to delete.
873
+
874
+		$error=0;
875
+		$this->db->begin();
876
+
877
+		if (! $error && ! $notrigger)
878
+		{
879
+			// Call trigger
880
+			$result=$this->call_trigger('BILL_SUPPLIER_DELETE',$user);
881
+			if ($result < 0)
882
+			{
883
+				$this->db->rollback();
884
+				return -1;
885
+			}
886
+			// Fin appel triggers
887
+		}
888
+
889
+		if (! $error)
890
+		{
891
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
892
+			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
893
+			$resql = $this->db->query($sql);
894
+			if ($resql)
895
+			{
896
+				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
897
+				dol_syslog(get_class($this)."::delete", LOG_DEBUG);
898
+				$resql2 = $this->db->query($sql);
899
+				if (! $resql2) {
900
+					$error++;
901
+				}
902
+			}
903
+			else {
904
+				$error++;
905
+			}
906
+		}
907 907
 
908 908
 		if (! $error)
909 909
 		{
@@ -912,780 +912,780 @@  discard block
 block discarded – undo
912 912
 			if ($res < 0) $error++;
913 913
 		}
914 914
 
915
-        if (! $error)
916
-        {
917
-        	// Delete linked object
918
-        	$res = $this->deleteObjectLinked();
919
-        	if ($res < 0) $error++;
920
-        }
921
-
922
-        if (! $error)
923
-        {
924
-        	// We remove directory
925
-        	if ($conf->fournisseur->facture->dir_output)
926
-        	{
927
-        		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
928
-
929
-        		$ref = dol_sanitizeFileName($this->ref);
930
-        		$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
931
-        		$file = $dir . "/" . $ref . ".pdf";
932
-        		if (file_exists($file))
933
-        		{
934
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
935
-        			{
936
-        				$this->error='ErrorFailToDeleteFile';
937
-        				$error++;
938
-        			}
939
-        		}
940
-        		if (file_exists($dir))
941
-        		{
942
-        			$res=@dol_delete_dir_recursive($dir);
943
-
944
-        			if (! $res)
945
-        			{
946
-        				$this->error='ErrorFailToDeleteDir';
947
-        				$error++;
948
-        			}
949
-        		}
950
-        	}
951
-        }
952
-
953
-        // Remove extrafields
954
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
955
-        {
956
-        	$result=$this->deleteExtraFields();
957
-        	if ($result < 0)
958
-        	{
959
-        		$error++;
960
-        		dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
961
-        	}
962
-        }
963
-
964
-        if (! $error)
965
-        {
966
-        	dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
967
-        	$this->db->commit();
968
-        	return 1;
969
-        }
970
-        else
971
-        {
972
-        	$this->error=$this->db->lasterror();
973
-        	$this->db->rollback();
974
-        	return -$error;
975
-        }
976
-    }
977
-
978
-
979
-    /**
980
-     *	Tag invoice as a payed invoice
981
-     *
982
-     *	@param  User	$user       Object user
983
-	 *	@param  string	$close_code	Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet.
984
-	 *	@param  string	$close_note	Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet.
985
-     *	@return int         		<0 si ko, >0 si ok
986
-     */
987
-    function set_paid($user, $close_code='', $close_note='')
988
-    {
989
-        global $conf,$langs;
990
-        $error=0;
991
-
992
-        $this->db->begin();
993
-
994
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
995
-        $sql.= ' SET paye = 1, fk_statut=2';
996
-        $sql.= ' WHERE rowid = '.$this->id;
997
-
998
-        dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
999
-        $resql = $this->db->query($sql);
1000
-        if ($resql)
1001
-        {
1002
-            // Call trigger
1003
-            $result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user);
1004
-            if ($result < 0) $error++;
1005
-            // End call triggers
1006
-        }
1007
-        else
1008
-        {
1009
-            $error++;
1010
-            $this->error=$this->db->error();
1011
-            dol_print_error($this->db);
1012
-        }
1013
-
1014
-        if (! $error)
1015
-        {
1016
-            $this->db->commit();
1017
-            return 1;
1018
-        }
1019
-        else
1020
-        {
1021
-            $this->db->rollback();
1022
-            return -1;
1023
-        }
1024
-    }
1025
-
1026
-
1027
-    /**
1028
-     *	Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
1029
-     *	Fonction utilisee quand un paiement prelevement est refuse,
1030
-     *	ou quand une facture annulee et reouverte.
1031
-     *
1032
-     *	@param      User	$user       Object user that change status
1033
-     *	@return     int         		<0 si ok, >0 si ok
1034
-     */
1035
-    function set_unpaid($user)
1036
-    {
1037
-        global $conf,$langs;
1038
-        $error=0;
1039
-
1040
-        $this->db->begin();
1041
-
1042
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
1043
-        $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
1044
-        $sql.= ' WHERE rowid = '.$this->id;
1045
-
1046
-        dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
1047
-        $resql = $this->db->query($sql);
1048
-        if ($resql)
1049
-        {
1050
-            // Call trigger
1051
-            $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user);
1052
-            if ($result < 0) $error++;
1053
-            // End call triggers
1054
-        }
1055
-        else
1056
-        {
1057
-            $error++;
1058
-            $this->error=$this->db->lasterror();
1059
-            dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
1060
-        }
1061
-
1062
-        if (! $error)
1063
-        {
1064
-            $this->db->commit();
1065
-            return 1;
1066
-        }
1067
-        else
1068
-        {
1069
-            $this->db->rollback();
1070
-            return -1;
1071
-        }
1072
-    }
1073
-
1074
-    /**
1075
-     *	Tag invoice as validated + call trigger BILL_VALIDATE
1076
-     *
1077
-     *	@param	User	$user           Object user that validate
1078
-     *	@param  string	$force_number   Reference to force on invoice
1079
-     *	@param	int		$idwarehouse	Id of warehouse for stock change
1080
-     *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1081
-     *	@return int 			        <0 if KO, =0 if nothing to do, >0 if OK
1082
-     */
1083
-    public function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
1084
-    {
1085
-        global $conf,$langs;
1086
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1087
-
1088
-        $now=dol_now();
1089
-
1090
-        $error=0;
1091
-        dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
1092
-
1093
-        // Force to have object complete for checks
1094
-        $this->fetch_thirdparty();
1095
-        $this->fetch_lines();
1096
-
1097
-        // Check parameters
1098
-        if ($this->statut > self::STATUS_DRAFT)	// This is to avoid to validate twice (avoid errors on logs and stock management)
1099
-        {
1100
-            dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
1101
-            return 0;
1102
-        }
1103
-        if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
1104
-        {
1105
-        	$langs->load("errors");
1106
-        	$this->error=$langs->trans("ErrorFieldFormat",$langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString',$langs->transnoentitiesnoconv("CopyOf"));
1107
-            return -1;
1108
-        }
1109
-        if (count($this->lines) <= 0)
1110
-        {
1111
-        	$langs->load("errors");
1112
-            $this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1113
-            return -1;
1114
-        }
1115
-
1116
-        $this->db->begin();
1117
-
1118
-        // Define new ref
1119
-        if ($force_number)
1120
-        {
1121
-            $num = $force_number;
1122
-        }
1123
-        else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
1124
-        {
1125
-            $num = $this->getNextNumRef($this->thirdparty);
1126
-        }
1127
-        else
1128
-		{
1129
-            $num = $this->ref;
1130
-        }
1131
-        $this->newref = $num;
1132
-
1133
-        $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1134
-        $sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
1135
-        $sql.= " WHERE rowid = ".$this->id;
1136
-
1137
-        dol_syslog(get_class($this)."::validate", LOG_DEBUG);
1138
-        $resql = $this->db->query($sql);
1139
-        if ($resql)
1140
-        {
1141
-            // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
1142
-            if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1143
-            {
1144
-                require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1145
-                $langs->load("agenda");
1146
-
1147
-                $cpt=count($this->lines);
1148
-                for ($i = 0; $i < $cpt; $i++)
1149
-                {
1150
-                    if ($this->lines[$i]->fk_product > 0)
1151
-                    {
1152
-                        $this->line = $this->lines[$i];
1153
-                        $mouvP = new MouvementStock($this->db);
1154
-						$mouvP->origin = &$this;
1155
-                        // We increase stock for product
1156
-                        $up_ht_disc=$this->lines[$i]->pu_ht;
1157
-                        if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1158
-                        $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr",$num));
1159
-                        if ($result < 0) { $error++; }
1160
-                        unset($this->line);
1161
-                    }
1162
-                }
1163
-            }
1164
-
1165
-            // Triggers call
1166
-            if (! $error && empty($notrigger))
1167
-            {
1168
-                // Call trigger
1169
-                $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
1170
-                if ($result < 0) $error++;
1171
-                // End call triggers
1172
-            }
1173
-
1174
-            if (! $error)
1175
-            {
1176
-	            $this->oldref = $this->ref;
1177
-
1178
-            	// Rename directory if dir was a temporary ref
1179
-            	if (preg_match('/^[\(]?PROV/i', $this->ref))
1180
-            	{
1181
-            		// On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref)
1182
-            		// in order not to lose the attached files
1183
-            		$oldref = dol_sanitizeFileName($this->ref);
1184
-            		$newref = dol_sanitizeFileName($num);
1185
-
1186
-            		$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$oldref;
1187
-            		$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref;
1188
-            		if (file_exists($dirsource))
1189
-            		{
1190
-            			dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
1191
-
1192
-            			if (@rename($dirsource, $dirdest))
1193
-            			{
1194
-            				dol_syslog("Rename ok");
1195
-                            // Rename docs starting with $oldref with $newref
1196
-	                        $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1197
-	                        foreach($listoffiles as $fileentry)
1198
-	                        {
1199
-	                        	$dirsource=$fileentry['name'];
1200
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1201
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
1202
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
1203
-	                        	@rename($dirsource, $dirdest);
1204
-	                        }
1205
-            			}
1206
-            		}
1207
-            	}
1208
-            }
1209
-
1210
-            // Set new ref and define current statut
1211
-            if (! $error)
1212
-            {
1213
-            	$this->ref = $num;
1214
-            	$this->statut=self::STATUS_VALIDATED;
1215
-            	//$this->date_validation=$now; this is stored into log table
1216
-            }
1217
-
1218
-            if (! $error)
1219
-            {
1220
-                $this->db->commit();
1221
-                return 1;
1222
-            }
1223
-            else
1224
-            {
1225
-                $this->db->rollback();
1226
-                return -1;
1227
-            }
1228
-        }
1229
-        else
1230
-        {
1231
-            $this->error=$this->db->error();
1232
-            $this->db->rollback();
1233
-            return -1;
1234
-        }
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     *	Set draft status
1240
-     *
1241
-     *	@param	User	$user			Object user that modify
1242
-     *	@param	int		$idwarehouse	Id warehouse to use for stock change.
1243
-     *	@return	int						<0 if KO, >0 if OK
1244
-     */
1245
-    function set_draft($user, $idwarehouse=-1)
1246
-    {
1247
-        global $conf,$langs;
1248
-
1249
-        $error=0;
1250
-
1251
-        if ($this->statut == self::STATUS_DRAFT)
1252
-        {
1253
-            dol_syslog(get_class($this)."::set_draft already draft status", LOG_WARNING);
1254
-            return 0;
1255
-        }
1256
-
1257
-        $this->db->begin();
1258
-
1259
-        $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1260
-        $sql.= " SET fk_statut = 0";
1261
-        $sql.= " WHERE rowid = ".$this->id;
1262
-
1263
-        dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
1264
-        $result=$this->db->query($sql);
1265
-        if ($result)
1266
-        {
1267
-            // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
1268
-            if ($result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1269
-            {
1270
-                require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1271
-                $langs->load("agenda");
1272
-
1273
-                $cpt=count($this->lines);
1274
-                for ($i = 0; $i < $cpt; $i++)
1275
-                {
1276
-                    if ($this->lines[$i]->fk_product > 0)
1277
-                    {
1278
-                        $mouvP = new MouvementStock($this->db);
1279
-                        // We increase stock for product
1280
-                        $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
1281
-                    }
1282
-                }
1283
-            }
1284
-            // Triggers call
1285
-            if (! $error && empty($notrigger))
1286
-            {
1287
-                // Call trigger
1288
-                $result=$this->call_trigger('BILL_SUPPLIER_UNVALIDATE',$user);
1289
-                if ($result < 0) $error++;
1290
-                // End call triggers
1291
-            }
1292
-            if ($error == 0)
1293
-            {
1294
-                $this->db->commit();
1295
-                return 1;
1296
-            }
1297
-            else
1298
-            {
1299
-                $this->db->rollback();
1300
-                return -1;
1301
-            }
1302
-        }
1303
-        else
1304
-        {
1305
-            $this->error=$this->db->error();
1306
-            $this->db->rollback();
1307
-            return -1;
1308
-        }
1309
-    }
1310
-
1311
-
1312
-    /**
1313
-     *	Ajoute une ligne de facture (associe a aucun produit/service predefini)
1314
-     *	Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
1315
-     *	de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
1316
-     *	par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod)
1317
-     *	et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue).
1318
-     *
1319
-     *	@param    	string	$desc            	Description de la ligne
1320
-     *	@param    	double	$pu              	Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note)
1321
-     *	@param    	double	$txtva           	Force Vat rate to use, -1 for auto.
1322
-     *	@param		double	$txlocaltax1		LocalTax1 Rate
1323
-     *	@param		double	$txlocaltax2		LocalTax2 Rate
1324
-     *	@param    	double	$qty             	Quantite
1325
-     *	@param    	int		$fk_product      	Id du produit/service predefini
1326
-     *	@param    	double	$remise_percent  	Pourcentage de remise de la ligne
1327
-     *	@param    	date	$date_start      	Date de debut de validite du service
1328
-     * 	@param    	date	$date_end        	Date de fin de validite du service
1329
-     * 	@param    	string	$ventil          	Code de ventilation comptable
1330
-     *	@param    	int		$info_bits			Bits de type de lines
1331
-     *	@param    	string	$price_base_type 	HT ou TTC
1332
-     *	@param		int		$type				Type of line (0=product, 1=service)
1333
-     *  @param      int		$rang            	Position of line
1334
-     *  @param		int		$notrigger			Disable triggers
1335
-	 *  @param		array	$array_options		extrafields array
1336
-     * 	@param 		string	$fk_unit 			Code of the unit to use. Null to use the default one
1337
-     *  @param      int     $origin_id          id origin document
1338
-	 *  @param		double	$pu_ht_devise		Amount in currency
1339
-     *	@return    	int             			>0 if OK, <0 if KO
1340
-     *
1341
-     *  FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order.
1342
-     */
1343
-    public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false, $array_options=0, $fk_unit=null, $origin_id=0, $pu_ht_devise=0)
1344
-    {
1345
-        dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
1346
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1347
-        global $mysoc;
1348
-
1349
-        // Clean parameters
1350
-        if (empty($remise_percent)) $remise_percent=0;
1351
-        if (empty($qty)) $qty=0;
1352
-        if (empty($info_bits)) $info_bits=0;
1353
-        if (empty($rang)) $rang=0;
1354
-        if (empty($ventil)) $ventil=0;
1355
-        if (empty($txtva)) $txtva=0;
1356
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1357
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1358
-
1359
-        $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1360
-
1361
-        // Clean vat code
1362
-        $vat_src_code='';
1363
-        if (preg_match('/\((.*)\)/', $txtva, $reg))
1364
-        {
1365
-            $vat_src_code = $reg[1];
1366
-            $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1367
-        }
1368
-
1369
-        $remise_percent=price2num($remise_percent);
1370
-        $qty=price2num($qty);
1371
-        $pu=price2num($pu);
1372
-        $txtva=price2num($txtva);
1373
-        $txlocaltax1=price2num($txlocaltax1);
1374
-        $txlocaltax2=price2num($txlocaltax2);
1375
-
1376
-        $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1377
-        $total_ht  = $tabprice[0];
1378
-        $total_tva = $tabprice[1];
1379
-        $total_ttc = $tabprice[2];
1380
-        $total_localtax1 = $tabprice[9];
1381
-        $total_localtax2 = $tabprice[10];
1382
-		$pu_ht = $tabprice[3];
915
+		if (! $error)
916
+		{
917
+			// Delete linked object
918
+			$res = $this->deleteObjectLinked();
919
+			if ($res < 0) $error++;
920
+		}
1383 921
 
1384
-        // MultiCurrency
1385
-        $multicurrency_total_ht  = $tabprice[16];
1386
-        $multicurrency_total_tva = $tabprice[17];
1387
-        $multicurrency_total_ttc = $tabprice[18];
1388
-		$pu_ht_devise = $tabprice[19];
922
+		if (! $error)
923
+		{
924
+			// We remove directory
925
+			if ($conf->fournisseur->facture->dir_output)
926
+			{
927
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1389 928
 
1390
-        // Check parameters
1391
-        if ($type < 0) return -1;
1392
-
1393
-        // Insert line
1394
-        $this->line=new SupplierInvoiceLine($this->db);
1395
-
1396
-        $this->line->context = $this->context;
1397
-
1398
-        $this->line->fk_facture_fourn=$this->id;
1399
-        //$this->line->label=$label;	// deprecated
1400
-        $this->line->desc=$desc;
1401
-        $this->line->qty=            ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	// For credit note, quantity is always positive and unit price negative
1402
-
1403
-        $this->line->vat_src_code=$vat_src_code;
1404
-        $this->line->tva_tx=$txtva;
1405
-        $this->line->localtax1_tx=$txlocaltax1;
1406
-        $this->line->localtax2_tx=$txlocaltax2;
1407
-        $this->line->fk_product=$fk_product;
1408
-        $this->line->product_type=$type;
1409
-        $this->line->remise_percent=$remise_percent;
1410
-        $this->line->subprice=       ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
1411
-        $this->line->date_start=$date_start;
1412
-        $this->line->date_end=$date_end;
1413
-        $this->line->ventil=$ventil;
1414
-        $this->line->rang=$rang;
1415
-        $this->line->info_bits=$info_bits;
1416
-        $this->line->total_ht=       (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht);  // For credit note and if qty is negative, total is negative
1417
-        $this->line->total_tva=      $total_tva;
1418
-        $this->line->total_localtax1=$total_localtax1;
1419
-        $this->line->total_localtax2=$total_localtax2;
1420
-        $this->line->localtax1_type = $localtaxes_type[0];
1421
-        $this->line->localtax2_type = $localtaxes_type[2];
1422
-        $this->line->total_ttc=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);
1423
-        $this->line->special_code=$this->special_code;
1424
-        $this->line->fk_parent_line=$this->fk_parent_line;
1425
-        $this->line->origin=$this->origin;
1426
-        $this->line->origin_id=$origin_id;
1427
-        $this->line->fk_unit=$fk_unit;
1428
-
1429
-        // Multicurrency
1430
-        $this->line->fk_multicurrency			= $this->fk_multicurrency;
1431
-        $this->line->multicurrency_code			= $this->multicurrency_code;
1432
-        $this->line->multicurrency_subprice		= $pu_ht_devise;
1433
-        $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1434
-        $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1435
-        $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1436
-
1437
-        if (is_array($array_options) && count($array_options)>0) {
1438
-            $this->line->array_options=$array_options;
1439
-        }
1440
-
1441
-        $result=$this->line->insert($notrigger);
1442
-        if ($result > 0)
1443
-        {
1444
-            // Reorder if child line
1445
-            if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1446
-
1447
-            // Mise a jour informations denormalisees au niveau de la facture meme
1448
-            $result=$this->update_price(1,'auto',0,$this->thirdparty);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
1449
-            if ($result > 0)
1450
-            {
1451
-                $this->db->commit();
1452
-                return $this->line->id;
1453
-            }
1454
-            else
1455
-            {
1456
-                $this->error=$this->db->error();
1457
-                $this->db->rollback();
1458
-                return -1;
1459
-            }
1460
-        }
1461
-        else
1462
-        {
1463
-            $this->error=$this->line->error;
1464
-            $this->db->rollback();
1465
-            return -2;
1466
-        }
1467
-    }
1468
-
1469
-    /**
1470
-     * Update a line detail into database
1471
-     *
1472
-     * @param     	int			$id            		Id of line invoice
1473
-     * @param     	string		$desc         		Description of line
1474
-     * @param     	double		$pu          		Prix unitaire (HT ou TTC selon price_base_type)
1475
-     * @param     	double		$vatrate       		VAT Rate
1476
-     * @param		double		$txlocaltax1		LocalTax1 Rate
1477
-     * @param		double		$txlocaltax2		LocalTax2 Rate
1478
-     * @param     	double		$qty           		Quantity
1479
-     * @param     	int			$idproduct			Id produit
1480
-     * @param	  	double		$price_base_type	HT or TTC
1481
-     * @param	  	int			$info_bits			Miscellaneous informations of line
1482
-     * @param		int			$type				Type of line (0=product, 1=service)
1483
-     * @param     	double		$remise_percent  	Pourcentage de remise de la ligne
1484
-     * @param		int			$notrigger			Disable triggers
1485
-     * @param      	timestamp	$date_start     	Date start of service
1486
-     * @param      	timestamp   $date_end       	Date end of service
1487
-	 * @param		array		$array_options		extrafields array
1488
-     * @param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
929
+				$ref = dol_sanitizeFileName($this->ref);
930
+				$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
931
+				$file = $dir . "/" . $ref . ".pdf";
932
+				if (file_exists($file))
933
+				{
934
+					if (! dol_delete_file($file,0,0,0,$this)) // For triggers
935
+					{
936
+						$this->error='ErrorFailToDeleteFile';
937
+						$error++;
938
+					}
939
+				}
940
+				if (file_exists($dir))
941
+				{
942
+					$res=@dol_delete_dir_recursive($dir);
943
+
944
+					if (! $res)
945
+					{
946
+						$this->error='ErrorFailToDeleteDir';
947
+						$error++;
948
+					}
949
+				}
950
+			}
951
+		}
952
+
953
+		// Remove extrafields
954
+		if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
955
+		{
956
+			$result=$this->deleteExtraFields();
957
+			if ($result < 0)
958
+			{
959
+				$error++;
960
+				dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
961
+			}
962
+		}
963
+
964
+		if (! $error)
965
+		{
966
+			dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
967
+			$this->db->commit();
968
+			return 1;
969
+		}
970
+		else
971
+		{
972
+			$this->error=$this->db->lasterror();
973
+			$this->db->rollback();
974
+			return -$error;
975
+		}
976
+	}
977
+
978
+
979
+	/**
980
+	 *	Tag invoice as a payed invoice
981
+	 *
982
+	 *	@param  User	$user       Object user
983
+	 *	@param  string	$close_code	Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet.
984
+	 *	@param  string	$close_note	Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet.
985
+	 *	@return int         		<0 si ko, >0 si ok
986
+	 */
987
+	function set_paid($user, $close_code='', $close_note='')
988
+	{
989
+		global $conf,$langs;
990
+		$error=0;
991
+
992
+		$this->db->begin();
993
+
994
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
995
+		$sql.= ' SET paye = 1, fk_statut=2';
996
+		$sql.= ' WHERE rowid = '.$this->id;
997
+
998
+		dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
999
+		$resql = $this->db->query($sql);
1000
+		if ($resql)
1001
+		{
1002
+			// Call trigger
1003
+			$result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user);
1004
+			if ($result < 0) $error++;
1005
+			// End call triggers
1006
+		}
1007
+		else
1008
+		{
1009
+			$error++;
1010
+			$this->error=$this->db->error();
1011
+			dol_print_error($this->db);
1012
+		}
1013
+
1014
+		if (! $error)
1015
+		{
1016
+			$this->db->commit();
1017
+			return 1;
1018
+		}
1019
+		else
1020
+		{
1021
+			$this->db->rollback();
1022
+			return -1;
1023
+		}
1024
+	}
1025
+
1026
+
1027
+	/**
1028
+	 *	Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
1029
+	 *	Fonction utilisee quand un paiement prelevement est refuse,
1030
+	 *	ou quand une facture annulee et reouverte.
1031
+	 *
1032
+	 *	@param      User	$user       Object user that change status
1033
+	 *	@return     int         		<0 si ok, >0 si ok
1034
+	 */
1035
+	function set_unpaid($user)
1036
+	{
1037
+		global $conf,$langs;
1038
+		$error=0;
1039
+
1040
+		$this->db->begin();
1041
+
1042
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
1043
+		$sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
1044
+		$sql.= ' WHERE rowid = '.$this->id;
1045
+
1046
+		dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
1047
+		$resql = $this->db->query($sql);
1048
+		if ($resql)
1049
+		{
1050
+			// Call trigger
1051
+			$result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user);
1052
+			if ($result < 0) $error++;
1053
+			// End call triggers
1054
+		}
1055
+		else
1056
+		{
1057
+			$error++;
1058
+			$this->error=$this->db->lasterror();
1059
+			dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
1060
+		}
1061
+
1062
+		if (! $error)
1063
+		{
1064
+			$this->db->commit();
1065
+			return 1;
1066
+		}
1067
+		else
1068
+		{
1069
+			$this->db->rollback();
1070
+			return -1;
1071
+		}
1072
+	}
1073
+
1074
+	/**
1075
+	 *	Tag invoice as validated + call trigger BILL_VALIDATE
1076
+	 *
1077
+	 *	@param	User	$user           Object user that validate
1078
+	 *	@param  string	$force_number   Reference to force on invoice
1079
+	 *	@param	int		$idwarehouse	Id of warehouse for stock change
1080
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1081
+	 *	@return int 			        <0 if KO, =0 if nothing to do, >0 if OK
1082
+	 */
1083
+	public function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
1084
+	{
1085
+		global $conf,$langs;
1086
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1087
+
1088
+		$now=dol_now();
1089
+
1090
+		$error=0;
1091
+		dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
1092
+
1093
+		// Force to have object complete for checks
1094
+		$this->fetch_thirdparty();
1095
+		$this->fetch_lines();
1096
+
1097
+		// Check parameters
1098
+		if ($this->statut > self::STATUS_DRAFT)	// This is to avoid to validate twice (avoid errors on logs and stock management)
1099
+		{
1100
+			dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
1101
+			return 0;
1102
+		}
1103
+		if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
1104
+		{
1105
+			$langs->load("errors");
1106
+			$this->error=$langs->trans("ErrorFieldFormat",$langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString',$langs->transnoentitiesnoconv("CopyOf"));
1107
+			return -1;
1108
+		}
1109
+		if (count($this->lines) <= 0)
1110
+		{
1111
+			$langs->load("errors");
1112
+			$this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1113
+			return -1;
1114
+		}
1115
+
1116
+		$this->db->begin();
1117
+
1118
+		// Define new ref
1119
+		if ($force_number)
1120
+		{
1121
+			$num = $force_number;
1122
+		}
1123
+		else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
1124
+		{
1125
+			$num = $this->getNextNumRef($this->thirdparty);
1126
+		}
1127
+		else
1128
+		{
1129
+			$num = $this->ref;
1130
+		}
1131
+		$this->newref = $num;
1132
+
1133
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1134
+		$sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
1135
+		$sql.= " WHERE rowid = ".$this->id;
1136
+
1137
+		dol_syslog(get_class($this)."::validate", LOG_DEBUG);
1138
+		$resql = $this->db->query($sql);
1139
+		if ($resql)
1140
+		{
1141
+			// Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
1142
+			if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1143
+			{
1144
+				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1145
+				$langs->load("agenda");
1146
+
1147
+				$cpt=count($this->lines);
1148
+				for ($i = 0; $i < $cpt; $i++)
1149
+				{
1150
+					if ($this->lines[$i]->fk_product > 0)
1151
+					{
1152
+						$this->line = $this->lines[$i];
1153
+						$mouvP = new MouvementStock($this->db);
1154
+						$mouvP->origin = &$this;
1155
+						// We increase stock for product
1156
+						$up_ht_disc=$this->lines[$i]->pu_ht;
1157
+						if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1158
+						$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr",$num));
1159
+						if ($result < 0) { $error++; }
1160
+						unset($this->line);
1161
+					}
1162
+				}
1163
+			}
1164
+
1165
+			// Triggers call
1166
+			if (! $error && empty($notrigger))
1167
+			{
1168
+				// Call trigger
1169
+				$result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
1170
+				if ($result < 0) $error++;
1171
+				// End call triggers
1172
+			}
1173
+
1174
+			if (! $error)
1175
+			{
1176
+				$this->oldref = $this->ref;
1177
+
1178
+				// Rename directory if dir was a temporary ref
1179
+				if (preg_match('/^[\(]?PROV/i', $this->ref))
1180
+				{
1181
+					// On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref)
1182
+					// in order not to lose the attached files
1183
+					$oldref = dol_sanitizeFileName($this->ref);
1184
+					$newref = dol_sanitizeFileName($num);
1185
+
1186
+					$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$oldref;
1187
+					$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref;
1188
+					if (file_exists($dirsource))
1189
+					{
1190
+						dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
1191
+
1192
+						if (@rename($dirsource, $dirdest))
1193
+						{
1194
+							dol_syslog("Rename ok");
1195
+							// Rename docs starting with $oldref with $newref
1196
+							$listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1197
+							foreach($listoffiles as $fileentry)
1198
+							{
1199
+								$dirsource=$fileentry['name'];
1200
+								$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1201
+								$dirsource=$fileentry['path'].'/'.$dirsource;
1202
+								$dirdest=$fileentry['path'].'/'.$dirdest;
1203
+								@rename($dirsource, $dirdest);
1204
+							}
1205
+						}
1206
+					}
1207
+				}
1208
+			}
1209
+
1210
+			// Set new ref and define current statut
1211
+			if (! $error)
1212
+			{
1213
+				$this->ref = $num;
1214
+				$this->statut=self::STATUS_VALIDATED;
1215
+				//$this->date_validation=$now; this is stored into log table
1216
+			}
1217
+
1218
+			if (! $error)
1219
+			{
1220
+				$this->db->commit();
1221
+				return 1;
1222
+			}
1223
+			else
1224
+			{
1225
+				$this->db->rollback();
1226
+				return -1;
1227
+			}
1228
+		}
1229
+		else
1230
+		{
1231
+			$this->error=$this->db->error();
1232
+			$this->db->rollback();
1233
+			return -1;
1234
+		}
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 *	Set draft status
1240
+	 *
1241
+	 *	@param	User	$user			Object user that modify
1242
+	 *	@param	int		$idwarehouse	Id warehouse to use for stock change.
1243
+	 *	@return	int						<0 if KO, >0 if OK
1244
+	 */
1245
+	function set_draft($user, $idwarehouse=-1)
1246
+	{
1247
+		global $conf,$langs;
1248
+
1249
+		$error=0;
1250
+
1251
+		if ($this->statut == self::STATUS_DRAFT)
1252
+		{
1253
+			dol_syslog(get_class($this)."::set_draft already draft status", LOG_WARNING);
1254
+			return 0;
1255
+		}
1256
+
1257
+		$this->db->begin();
1258
+
1259
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1260
+		$sql.= " SET fk_statut = 0";
1261
+		$sql.= " WHERE rowid = ".$this->id;
1262
+
1263
+		dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
1264
+		$result=$this->db->query($sql);
1265
+		if ($result)
1266
+		{
1267
+			// Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
1268
+			if ($result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1269
+			{
1270
+				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1271
+				$langs->load("agenda");
1272
+
1273
+				$cpt=count($this->lines);
1274
+				for ($i = 0; $i < $cpt; $i++)
1275
+				{
1276
+					if ($this->lines[$i]->fk_product > 0)
1277
+					{
1278
+						$mouvP = new MouvementStock($this->db);
1279
+						// We increase stock for product
1280
+						$result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
1281
+					}
1282
+				}
1283
+			}
1284
+			// Triggers call
1285
+			if (! $error && empty($notrigger))
1286
+			{
1287
+				// Call trigger
1288
+				$result=$this->call_trigger('BILL_SUPPLIER_UNVALIDATE',$user);
1289
+				if ($result < 0) $error++;
1290
+				// End call triggers
1291
+			}
1292
+			if ($error == 0)
1293
+			{
1294
+				$this->db->commit();
1295
+				return 1;
1296
+			}
1297
+			else
1298
+			{
1299
+				$this->db->rollback();
1300
+				return -1;
1301
+			}
1302
+		}
1303
+		else
1304
+		{
1305
+			$this->error=$this->db->error();
1306
+			$this->db->rollback();
1307
+			return -1;
1308
+		}
1309
+	}
1310
+
1311
+
1312
+	/**
1313
+	 *	Ajoute une ligne de facture (associe a aucun produit/service predefini)
1314
+	 *	Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
1315
+	 *	de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
1316
+	 *	par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod)
1317
+	 *	et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue).
1318
+	 *
1319
+	 *	@param    	string	$desc            	Description de la ligne
1320
+	 *	@param    	double	$pu              	Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note)
1321
+	 *	@param    	double	$txtva           	Force Vat rate to use, -1 for auto.
1322
+	 *	@param		double	$txlocaltax1		LocalTax1 Rate
1323
+	 *	@param		double	$txlocaltax2		LocalTax2 Rate
1324
+	 *	@param    	double	$qty             	Quantite
1325
+	 *	@param    	int		$fk_product      	Id du produit/service predefini
1326
+	 *	@param    	double	$remise_percent  	Pourcentage de remise de la ligne
1327
+	 *	@param    	date	$date_start      	Date de debut de validite du service
1328
+	 * 	@param    	date	$date_end        	Date de fin de validite du service
1329
+	 * 	@param    	string	$ventil          	Code de ventilation comptable
1330
+	 *	@param    	int		$info_bits			Bits de type de lines
1331
+	 *	@param    	string	$price_base_type 	HT ou TTC
1332
+	 *	@param		int		$type				Type of line (0=product, 1=service)
1333
+	 *  @param      int		$rang            	Position of line
1334
+	 *  @param		int		$notrigger			Disable triggers
1335
+	 *  @param		array	$array_options		extrafields array
1336
+	 * 	@param 		string	$fk_unit 			Code of the unit to use. Null to use the default one
1337
+	 *  @param      int     $origin_id          id origin document
1338
+	 *  @param		double	$pu_ht_devise		Amount in currency
1339
+	 *	@return    	int             			>0 if OK, <0 if KO
1340
+	 *
1341
+	 *  FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order.
1342
+	 */
1343
+	public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false, $array_options=0, $fk_unit=null, $origin_id=0, $pu_ht_devise=0)
1344
+	{
1345
+		dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
1346
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1347
+		global $mysoc;
1348
+
1349
+		// Clean parameters
1350
+		if (empty($remise_percent)) $remise_percent=0;
1351
+		if (empty($qty)) $qty=0;
1352
+		if (empty($info_bits)) $info_bits=0;
1353
+		if (empty($rang)) $rang=0;
1354
+		if (empty($ventil)) $ventil=0;
1355
+		if (empty($txtva)) $txtva=0;
1356
+		if (empty($txlocaltax1)) $txlocaltax1=0;
1357
+		if (empty($txlocaltax2)) $txlocaltax2=0;
1358
+
1359
+		$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1360
+
1361
+		// Clean vat code
1362
+		$vat_src_code='';
1363
+		if (preg_match('/\((.*)\)/', $txtva, $reg))
1364
+		{
1365
+			$vat_src_code = $reg[1];
1366
+			$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1367
+		}
1368
+
1369
+		$remise_percent=price2num($remise_percent);
1370
+		$qty=price2num($qty);
1371
+		$pu=price2num($pu);
1372
+		$txtva=price2num($txtva);
1373
+		$txlocaltax1=price2num($txlocaltax1);
1374
+		$txlocaltax2=price2num($txlocaltax2);
1375
+
1376
+		$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1377
+		$total_ht  = $tabprice[0];
1378
+		$total_tva = $tabprice[1];
1379
+		$total_ttc = $tabprice[2];
1380
+		$total_localtax1 = $tabprice[9];
1381
+		$total_localtax2 = $tabprice[10];
1382
+		$pu_ht = $tabprice[3];
1383
+
1384
+		// MultiCurrency
1385
+		$multicurrency_total_ht  = $tabprice[16];
1386
+		$multicurrency_total_tva = $tabprice[17];
1387
+		$multicurrency_total_ttc = $tabprice[18];
1388
+		$pu_ht_devise = $tabprice[19];
1389
+
1390
+		// Check parameters
1391
+		if ($type < 0) return -1;
1392
+
1393
+		// Insert line
1394
+		$this->line=new SupplierInvoiceLine($this->db);
1395
+
1396
+		$this->line->context = $this->context;
1397
+
1398
+		$this->line->fk_facture_fourn=$this->id;
1399
+		//$this->line->label=$label;	// deprecated
1400
+		$this->line->desc=$desc;
1401
+		$this->line->qty=            ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	// For credit note, quantity is always positive and unit price negative
1402
+
1403
+		$this->line->vat_src_code=$vat_src_code;
1404
+		$this->line->tva_tx=$txtva;
1405
+		$this->line->localtax1_tx=$txlocaltax1;
1406
+		$this->line->localtax2_tx=$txlocaltax2;
1407
+		$this->line->fk_product=$fk_product;
1408
+		$this->line->product_type=$type;
1409
+		$this->line->remise_percent=$remise_percent;
1410
+		$this->line->subprice=       ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
1411
+		$this->line->date_start=$date_start;
1412
+		$this->line->date_end=$date_end;
1413
+		$this->line->ventil=$ventil;
1414
+		$this->line->rang=$rang;
1415
+		$this->line->info_bits=$info_bits;
1416
+		$this->line->total_ht=       (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht);  // For credit note and if qty is negative, total is negative
1417
+		$this->line->total_tva=      $total_tva;
1418
+		$this->line->total_localtax1=$total_localtax1;
1419
+		$this->line->total_localtax2=$total_localtax2;
1420
+		$this->line->localtax1_type = $localtaxes_type[0];
1421
+		$this->line->localtax2_type = $localtaxes_type[2];
1422
+		$this->line->total_ttc=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);
1423
+		$this->line->special_code=$this->special_code;
1424
+		$this->line->fk_parent_line=$this->fk_parent_line;
1425
+		$this->line->origin=$this->origin;
1426
+		$this->line->origin_id=$origin_id;
1427
+		$this->line->fk_unit=$fk_unit;
1428
+
1429
+		// Multicurrency
1430
+		$this->line->fk_multicurrency			= $this->fk_multicurrency;
1431
+		$this->line->multicurrency_code			= $this->multicurrency_code;
1432
+		$this->line->multicurrency_subprice		= $pu_ht_devise;
1433
+		$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1434
+		$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1435
+		$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1436
+
1437
+		if (is_array($array_options) && count($array_options)>0) {
1438
+			$this->line->array_options=$array_options;
1439
+		}
1440
+
1441
+		$result=$this->line->insert($notrigger);
1442
+		if ($result > 0)
1443
+		{
1444
+			// Reorder if child line
1445
+			if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1446
+
1447
+			// Mise a jour informations denormalisees au niveau de la facture meme
1448
+			$result=$this->update_price(1,'auto',0,$this->thirdparty);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
1449
+			if ($result > 0)
1450
+			{
1451
+				$this->db->commit();
1452
+				return $this->line->id;
1453
+			}
1454
+			else
1455
+			{
1456
+				$this->error=$this->db->error();
1457
+				$this->db->rollback();
1458
+				return -1;
1459
+			}
1460
+		}
1461
+		else
1462
+		{
1463
+			$this->error=$this->line->error;
1464
+			$this->db->rollback();
1465
+			return -2;
1466
+		}
1467
+	}
1468
+
1469
+	/**
1470
+	 * Update a line detail into database
1471
+	 *
1472
+	 * @param     	int			$id            		Id of line invoice
1473
+	 * @param     	string		$desc         		Description of line
1474
+	 * @param     	double		$pu          		Prix unitaire (HT ou TTC selon price_base_type)
1475
+	 * @param     	double		$vatrate       		VAT Rate
1476
+	 * @param		double		$txlocaltax1		LocalTax1 Rate
1477
+	 * @param		double		$txlocaltax2		LocalTax2 Rate
1478
+	 * @param     	double		$qty           		Quantity
1479
+	 * @param     	int			$idproduct			Id produit
1480
+	 * @param	  	double		$price_base_type	HT or TTC
1481
+	 * @param	  	int			$info_bits			Miscellaneous informations of line
1482
+	 * @param		int			$type				Type of line (0=product, 1=service)
1483
+	 * @param     	double		$remise_percent  	Pourcentage de remise de la ligne
1484
+	 * @param		int			$notrigger			Disable triggers
1485
+	 * @param      	timestamp	$date_start     	Date start of service
1486
+	 * @param      	timestamp   $date_end       	Date end of service
1487
+	 * @param		array		$array_options		extrafields array
1488
+	 * @param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
1489 1489
 	 * @param		double		$pu_ht_devise		Amount in currency
1490
-     * @return    	int           					<0 if KO, >0 if OK
1491
-     */
1492
-    public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit = null, $pu_ht_devise=0)
1493
-    {
1494
-    	global $mysoc;
1495
-        dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$fk_unit", LOG_DEBUG);
1496
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1497
-
1498
-        $pu = price2num($pu);
1499
-        $qty  = price2num($qty);
1490
+	 * @return    	int           					<0 if KO, >0 if OK
1491
+	 */
1492
+	public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit = null, $pu_ht_devise=0)
1493
+	{
1494
+		global $mysoc;
1495
+		dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$fk_unit", LOG_DEBUG);
1496
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1497
+
1498
+		$pu = price2num($pu);
1499
+		$qty  = price2num($qty);
1500 1500
 		$remise_percent=price2num($remise_percent);
1501 1501
 		$pu_ht_devise = price2num($pu_ht_devise);
1502 1502
 
1503
-        // Check parameters
1504
-        //if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
1505
-        if ($type < 0) return -1;
1503
+		// Check parameters
1504
+		//if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
1505
+		if ($type < 0) return -1;
1506 1506
 
1507
-        // Clean parameters
1507
+		// Clean parameters
1508 1508
 		if (empty($vatrate)) $vatrate=0;
1509
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1510
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1511
-
1512
-        $txlocaltax1=price2num($txlocaltax1);
1513
-        $txlocaltax2=price2num($txlocaltax2);
1514
-
1515
-        $localtaxes_type = array($txlocaltax1,$txlocaltax2);
1516
-
1517
-        // Calcul du total TTC et de la TVA pour la ligne a partir de
1518
-        // qty, pu, remise_percent et txtva
1519
-        // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1520
-        // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1521
-
1522
-        $localtaxes_type=getLocalTaxesFromRate($vatrate,0,$mysoc, $this->thirdparty);
1523
-
1524
-        // Clean vat code
1525
-        $vat_src_code='';
1526
-        if (preg_match('/\((.*)\)/', $vatrate, $reg))
1527
-        {
1528
-            $vat_src_code = $reg[1];
1529
-            $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate);    // Remove code into vatrate.
1530
-        }
1531
-
1532
-        $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1533
-        $total_ht  = $tabprice[0];
1534
-        $total_tva = $tabprice[1];
1535
-        $total_ttc = $tabprice[2];
1536
-        $pu_ht  = $tabprice[3];
1537
-        $pu_tva = $tabprice[4];
1538
-        $pu_ttc = $tabprice[5];
1539
-        $total_localtax1 = $tabprice[9];
1540
-        $total_localtax2 = $tabprice[10];
1509
+		if (empty($txlocaltax1)) $txlocaltax1=0;
1510
+		if (empty($txlocaltax2)) $txlocaltax2=0;
1511
+
1512
+		$txlocaltax1=price2num($txlocaltax1);
1513
+		$txlocaltax2=price2num($txlocaltax2);
1514
+
1515
+		$localtaxes_type = array($txlocaltax1,$txlocaltax2);
1516
+
1517
+		// Calcul du total TTC et de la TVA pour la ligne a partir de
1518
+		// qty, pu, remise_percent et txtva
1519
+		// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1520
+		// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1521
+
1522
+		$localtaxes_type=getLocalTaxesFromRate($vatrate,0,$mysoc, $this->thirdparty);
1523
+
1524
+		// Clean vat code
1525
+		$vat_src_code='';
1526
+		if (preg_match('/\((.*)\)/', $vatrate, $reg))
1527
+		{
1528
+			$vat_src_code = $reg[1];
1529
+			$vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate);    // Remove code into vatrate.
1530
+		}
1531
+
1532
+		$tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1533
+		$total_ht  = $tabprice[0];
1534
+		$total_tva = $tabprice[1];
1535
+		$total_ttc = $tabprice[2];
1536
+		$pu_ht  = $tabprice[3];
1537
+		$pu_tva = $tabprice[4];
1538
+		$pu_ttc = $tabprice[5];
1539
+		$total_localtax1 = $tabprice[9];
1540
+		$total_localtax2 = $tabprice[10];
1541 1541
 
1542 1542
 		// MultiCurrency
1543 1543
 		$multicurrency_total_ht  = $tabprice[16];
1544
-        $multicurrency_total_tva = $tabprice[17];
1545
-        $multicurrency_total_ttc = $tabprice[18];
1544
+		$multicurrency_total_tva = $tabprice[17];
1545
+		$multicurrency_total_ttc = $tabprice[18];
1546 1546
 		$pu_ht_devise = $tabprice[19];
1547 1547
 
1548
-        if (empty($info_bits)) $info_bits=0;
1549
-
1550
-        if ($idproduct)
1551
-        {
1552
-            $product=new Product($this->db);
1553
-            $result=$product->fetch($idproduct);
1554
-            $product_type = $product->type;
1555
-        }
1556
-        else
1557
-        {
1558
-            $product_type = $type;
1559
-        }
1560
-
1561
-	    $line = new SupplierInvoiceLine($this->db);
1562
-
1563
-	    if ($line->fetch($id) < 1) {
1564
-		    return -1;
1565
-	    }
1566
-
1567
-	    $line->description = $desc;
1568
-	    $line->subprice = $pu_ht;
1569
-	    $line->pu_ht = $pu_ht;
1570
-	    $line->pu_ttc = $pu_ttc;
1571
-	    $line->qty = $qty;
1572
-	    $line->remise_percent = $remise_percent;
1573
-
1574
-	    $line->vat_src_code=$vat_src_code;
1575
-	    $line->tva_tx = $vatrate;
1576
-	    $line->localtax1_tx = $txlocaltax1;
1577
-	    $line->localtax2_tx = $txlocaltax2;
1548
+		if (empty($info_bits)) $info_bits=0;
1549
+
1550
+		if ($idproduct)
1551
+		{
1552
+			$product=new Product($this->db);
1553
+			$result=$product->fetch($idproduct);
1554
+			$product_type = $product->type;
1555
+		}
1556
+		else
1557
+		{
1558
+			$product_type = $type;
1559
+		}
1560
+
1561
+		$line = new SupplierInvoiceLine($this->db);
1562
+
1563
+		if ($line->fetch($id) < 1) {
1564
+			return -1;
1565
+		}
1566
+
1567
+		$line->description = $desc;
1568
+		$line->subprice = $pu_ht;
1569
+		$line->pu_ht = $pu_ht;
1570
+		$line->pu_ttc = $pu_ttc;
1571
+		$line->qty = $qty;
1572
+		$line->remise_percent = $remise_percent;
1573
+
1574
+		$line->vat_src_code=$vat_src_code;
1575
+		$line->tva_tx = $vatrate;
1576
+		$line->localtax1_tx = $txlocaltax1;
1577
+		$line->localtax2_tx = $txlocaltax2;
1578 1578
 		$line->localtax1_type = $localtaxes_type[0];
1579 1579
 		$line->localtax2_type = $localtaxes_type[2];
1580
-	    $line->total_ht = $total_ht;
1581
-	    $line->total_tva = $total_tva;
1582
-	    $line->total_localtax1 = $total_localtax1;
1583
-	    $line->total_localtax2 = $total_localtax2;
1584
-	    $line->total_ttc = $total_ttc;
1585
-	    $line->fk_product = $idproduct;
1586
-	    $line->product_type = $product_type;
1587
-	    $line->info_bits = $info_bits;
1588
-	    $line->fk_unit = $fk_unit;
1589
-	    $line->array_options = $array_options;
1580
+		$line->total_ht = $total_ht;
1581
+		$line->total_tva = $total_tva;
1582
+		$line->total_localtax1 = $total_localtax1;
1583
+		$line->total_localtax2 = $total_localtax2;
1584
+		$line->total_ttc = $total_ttc;
1585
+		$line->fk_product = $idproduct;
1586
+		$line->product_type = $product_type;
1587
+		$line->info_bits = $info_bits;
1588
+		$line->fk_unit = $fk_unit;
1589
+		$line->array_options = $array_options;
1590 1590
 
1591 1591
 		// Multicurrency
1592 1592
 		$line->multicurrency_subprice	= $pu_ht_devise;
1593 1593
 		$line->multicurrency_total_ht 	= $multicurrency_total_ht;
1594
-        $line->multicurrency_total_tva 	= $multicurrency_total_tva;
1595
-        $line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1596
-
1597
-	    $res = $line->update($notrigger);
1598
-
1599
-	    if ($res < 1) {
1600
-		    $this->errors[] = $line->error;
1601
-	    } else {
1602
-		    // Update total price into invoice record
1603
-		    $res = $this->update_price('','auto');
1604
-	    }
1605
-
1606
-	    return $res;
1607
-    }
1608
-
1609
-    /**
1610
-     * 	Delete a detail line from database
1611
-     *
1612
-     * 	@param  int		$rowid      	Id of line to delete
1613
-     *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1614
-     * 	@return	int						<0 if KO, >0 if OK
1615
-     */
1616
-    public function deleteline($rowid, $notrigger=0)
1617
-    {
1618
-        if (!$rowid) {
1619
-	        $rowid = $this->id;
1620
-        }
1621
-
1622
-	    $line = new SupplierInvoiceLine($this->db);
1623
-
1624
-	    if ($line->fetch($rowid) < 1) {
1625
-		    return -1;
1626
-	    }
1627
-
1628
-	    $res = $line->delete($notrigger);
1629
-
1630
-	    if ($res < 1) {
1631
-		    $this->errors[] = $line->error;
1632
-	    } else {
1633
-		    $res = $this->update_price();
1634
-	    }
1635
-
1636
-    	return $res;
1637
-    }
1638
-
1639
-
1640
-    /**
1641
-     *	Charge les informations d'ordre info dans l'objet facture
1642
-     *
1643
-     *	@param  int		$id       	Id de la facture a charger
1644
-     *	@return	void
1645
-     */
1646
-    public function info($id)
1647
-    {
1648
-        $sql = 'SELECT c.rowid, datec, tms as datem, ';
1649
-        $sql.= ' fk_user_author, fk_user_modif, fk_user_valid';
1650
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
1651
-        $sql.= ' WHERE c.rowid = '.$id;
1652
-
1653
-        $result=$this->db->query($sql);
1654
-        if ($result)
1655
-        {
1656
-            if ($this->db->num_rows($result))
1657
-            {
1658
-                $obj = $this->db->fetch_object($result);
1659
-                $this->id = $obj->rowid;
1660
-                if ($obj->fk_user_author)
1661
-                {
1662
-                    $cuser = new User($this->db);
1663
-                    $cuser->fetch($obj->fk_user_author);
1664
-                    $this->user_creation     = $cuser;
1665
-                }
1666
-                if ($obj->fk_user_valid)
1667
-                {
1668
-                    $vuser = new User($this->db);
1669
-                    $vuser->fetch($obj->fk_user_valid);
1670
-                    $this->user_validation = $vuser;
1671
-                }
1672
-                if ($obj->fk_user_modif)
1673
-                {
1674
-                    $muser = new User($this->db);
1675
-                    $muser->fetch($obj->fk_user_modif);
1676
-                    $this->user_modification = $muser;
1677
-                }
1678
-                $this->date_creation     = $this->db->idate($obj->datec);
1679
-                $this->date_modification = $this->db->idate($obj->datem);
1680
-                //$this->date_validation   = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
1681
-            }
1682
-            $this->db->free($result);
1683
-        }
1684
-        else
1685
-        {
1686
-            dol_print_error($this->db);
1687
-        }
1688
-    }
1594
+		$line->multicurrency_total_tva 	= $multicurrency_total_tva;
1595
+		$line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1596
+
1597
+		$res = $line->update($notrigger);
1598
+
1599
+		if ($res < 1) {
1600
+			$this->errors[] = $line->error;
1601
+		} else {
1602
+			// Update total price into invoice record
1603
+			$res = $this->update_price('','auto');
1604
+		}
1605
+
1606
+		return $res;
1607
+	}
1608
+
1609
+	/**
1610
+	 * 	Delete a detail line from database
1611
+	 *
1612
+	 * 	@param  int		$rowid      	Id of line to delete
1613
+	 *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1614
+	 * 	@return	int						<0 if KO, >0 if OK
1615
+	 */
1616
+	public function deleteline($rowid, $notrigger=0)
1617
+	{
1618
+		if (!$rowid) {
1619
+			$rowid = $this->id;
1620
+		}
1621
+
1622
+		$line = new SupplierInvoiceLine($this->db);
1623
+
1624
+		if ($line->fetch($rowid) < 1) {
1625
+			return -1;
1626
+		}
1627
+
1628
+		$res = $line->delete($notrigger);
1629
+
1630
+		if ($res < 1) {
1631
+			$this->errors[] = $line->error;
1632
+		} else {
1633
+			$res = $this->update_price();
1634
+		}
1635
+
1636
+		return $res;
1637
+	}
1638
+
1639
+
1640
+	/**
1641
+	 *	Charge les informations d'ordre info dans l'objet facture
1642
+	 *
1643
+	 *	@param  int		$id       	Id de la facture a charger
1644
+	 *	@return	void
1645
+	 */
1646
+	public function info($id)
1647
+	{
1648
+		$sql = 'SELECT c.rowid, datec, tms as datem, ';
1649
+		$sql.= ' fk_user_author, fk_user_modif, fk_user_valid';
1650
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
1651
+		$sql.= ' WHERE c.rowid = '.$id;
1652
+
1653
+		$result=$this->db->query($sql);
1654
+		if ($result)
1655
+		{
1656
+			if ($this->db->num_rows($result))
1657
+			{
1658
+				$obj = $this->db->fetch_object($result);
1659
+				$this->id = $obj->rowid;
1660
+				if ($obj->fk_user_author)
1661
+				{
1662
+					$cuser = new User($this->db);
1663
+					$cuser->fetch($obj->fk_user_author);
1664
+					$this->user_creation     = $cuser;
1665
+				}
1666
+				if ($obj->fk_user_valid)
1667
+				{
1668
+					$vuser = new User($this->db);
1669
+					$vuser->fetch($obj->fk_user_valid);
1670
+					$this->user_validation = $vuser;
1671
+				}
1672
+				if ($obj->fk_user_modif)
1673
+				{
1674
+					$muser = new User($this->db);
1675
+					$muser->fetch($obj->fk_user_modif);
1676
+					$this->user_modification = $muser;
1677
+				}
1678
+				$this->date_creation     = $this->db->idate($obj->datec);
1679
+				$this->date_modification = $this->db->idate($obj->datem);
1680
+				//$this->date_validation   = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
1681
+			}
1682
+			$this->db->free($result);
1683
+		}
1684
+		else
1685
+		{
1686
+			dol_print_error($this->db);
1687
+		}
1688
+	}
1689 1689
 
1690 1690
 	/**
1691 1691
 	 *	Renvoi liste des factures remplacables
@@ -1783,296 +1783,296 @@  discard block
 block discarded – undo
1783 1783
 		}
1784 1784
 	}
1785 1785
 
1786
-    /**
1787
-     *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1788
-     *
1789
-     *	@param      User	$user       Object user
1790
-     *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
1791
-     */
1792
-    function load_board($user)
1793
-    {
1794
-        global $conf, $langs;
1795
-
1796
-        $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut';
1797
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
1798
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1799
-        $sql.= ' WHERE ff.paye=0';
1800
-        $sql.= ' AND ff.fk_statut > 0';
1801
-        $sql.= " AND ff.entity = ".$conf->entity;
1802
-        if ($user->societe_id) $sql.=' AND ff.fk_soc = '.$user->societe_id;
1803
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1804
-
1805
-        $resql=$this->db->query($sql);
1806
-        if ($resql)
1807
-        {
1808
-	        $langs->load("bills");
1809
-	        $now=dol_now();
1810
-
1811
-	        $response = new WorkboardResponse();
1812
-	        $response->warning_delay=$conf->facture->fournisseur->warning_delay/60/60/24;
1813
-	        $response->label=$langs->trans("SupplierBillsToPay");
1814
-
1815
-	        $response->url=DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=suppliers_bills';
1816
-	        $response->img=img_object($langs->trans("Bills"),"bill");
1817
-
1818
-            $facturestatic = new FactureFournisseur($this->db);
1819
-
1820
-            while ($obj=$this->db->fetch_object($resql))
1821
-            {
1822
-                $response->nbtodo++;
1823
-
1824
-                $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
1825
-                $facturestatic->statut = $obj->fk_statut;
1826
-
1827
-                if ($facturestatic->hasDelay()) {
1828
-	                $response->nbtodolate++;
1829
-                }
1830
-            }
1831
-            $this->db->free($resql);
1832
-            return $response;
1833
-        }
1834
-        else
1835
-        {
1836
-            dol_print_error($this->db);
1837
-            $this->error=$this->db->error();
1838
-            return -1;
1839
-        }
1840
-    }
1841
-
1842
-
1843
-    /**
1844
-     *	Return clicable name (with picto eventually)
1845
-     *
1846
-     *	@param		int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
1847
-     *	@param		string	$option						Where point the link
1848
-     *	@param		int		$max						Max length of shown ref
1849
-     *	@param		int		$short						1=Return just URL
1850
-     *	@param		string	$moretitle					Add more text to title tooltip
1851
-     *  @param	    int   	$notooltip					1=Disable tooltip
1852
-     *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1853
-     * 	@return		string								String with URL
1854
-     */
1855
-    public function getNomUrl($withpicto=0, $option='',$max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1)
1856
-    {
1857
-        global $langs, $conf;
1858
-
1859
-        $result='';
1860
-
1861
-        if ($option == 'document')	$url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
1862
-        else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
1863
-
1864
-        if ($short) return $url;
1865
-
1866
-        if ($option !== 'nolink')
1867
-        {
1868
-        	// Add param to save lastsearch_values or not
1869
-        	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1870
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1871
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1872
-        }
1873
-
1874
-        $picto='bill';
1875
-        if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice
1876
-        if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note
1877
-        if ($this->type == self::TYPE_DEPOSIT)     $picto.='d'; // Deposit invoice
1878
-
1879
-        $label = '<u>' . $langs->trans("ShowSupplierInvoice") . '</u>';
1880
-        if (! empty($this->ref))
1881
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1882
-        if (! empty($this->ref_supplier))
1883
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
1884
-        if (! empty($this->total_ht))
1885
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1886
-        if (! empty($this->total_tva))
1887
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1888
-        if (! empty($this->total_ttc))
1889
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1890
-        if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1891
-        if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1892
-        if ($this->type == self::TYPE_DEPOSIT)     $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1893
-        if ($moretitle) $label.=' - '.$moretitle;
1894
-
1895
-        $ref=$this->ref;
1896
-        if (empty($ref)) $ref=$this->id;
1897
-
1898
-        $linkclose='';
1899
-        if (empty($notooltip))
1900
-        {
1901
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1902
-            {
1903
-                $label=$langs->trans("ShowSupplierInvoice");
1904
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1905
-            }
1906
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1907
-            $linkclose.=' class="classfortooltip"';
1908
-        }
1909
-
1910
-        $linkstart = '<a href="'.$url.'"';
1911
-        $linkstart.=$linkclose.'>';
1912
-        $linkend='</a>';
1913
-
1914
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
1915
-        $result.=$linkstart.($max?dol_trunc($ref,$max):$ref).$linkend;
1916
-        return $result;
1917
-    }
1786
+	/**
1787
+	 *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1788
+	 *
1789
+	 *	@param      User	$user       Object user
1790
+	 *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
1791
+	 */
1792
+	function load_board($user)
1793
+	{
1794
+		global $conf, $langs;
1795
+
1796
+		$sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut';
1797
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
1798
+		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1799
+		$sql.= ' WHERE ff.paye=0';
1800
+		$sql.= ' AND ff.fk_statut > 0';
1801
+		$sql.= " AND ff.entity = ".$conf->entity;
1802
+		if ($user->societe_id) $sql.=' AND ff.fk_soc = '.$user->societe_id;
1803
+		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1804
+
1805
+		$resql=$this->db->query($sql);
1806
+		if ($resql)
1807
+		{
1808
+			$langs->load("bills");
1809
+			$now=dol_now();
1810
+
1811
+			$response = new WorkboardResponse();
1812
+			$response->warning_delay=$conf->facture->fournisseur->warning_delay/60/60/24;
1813
+			$response->label=$langs->trans("SupplierBillsToPay");
1814
+
1815
+			$response->url=DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=suppliers_bills';
1816
+			$response->img=img_object($langs->trans("Bills"),"bill");
1817
+
1818
+			$facturestatic = new FactureFournisseur($this->db);
1819
+
1820
+			while ($obj=$this->db->fetch_object($resql))
1821
+			{
1822
+				$response->nbtodo++;
1823
+
1824
+				$facturestatic->date_echeance = $this->db->jdate($obj->datefin);
1825
+				$facturestatic->statut = $obj->fk_statut;
1826
+
1827
+				if ($facturestatic->hasDelay()) {
1828
+					$response->nbtodolate++;
1829
+				}
1830
+			}
1831
+			$this->db->free($resql);
1832
+			return $response;
1833
+		}
1834
+		else
1835
+		{
1836
+			dol_print_error($this->db);
1837
+			$this->error=$this->db->error();
1838
+			return -1;
1839
+		}
1840
+	}
1841
+
1842
+
1843
+	/**
1844
+	 *	Return clicable name (with picto eventually)
1845
+	 *
1846
+	 *	@param		int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
1847
+	 *	@param		string	$option						Where point the link
1848
+	 *	@param		int		$max						Max length of shown ref
1849
+	 *	@param		int		$short						1=Return just URL
1850
+	 *	@param		string	$moretitle					Add more text to title tooltip
1851
+	 *  @param	    int   	$notooltip					1=Disable tooltip
1852
+	 *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1853
+	 * 	@return		string								String with URL
1854
+	 */
1855
+	public function getNomUrl($withpicto=0, $option='',$max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1)
1856
+	{
1857
+		global $langs, $conf;
1858
+
1859
+		$result='';
1860
+
1861
+		if ($option == 'document')	$url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
1862
+		else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
1863
+
1864
+		if ($short) return $url;
1865
+
1866
+		if ($option !== 'nolink')
1867
+		{
1868
+			// Add param to save lastsearch_values or not
1869
+			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1870
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1871
+			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1872
+		}
1873
+
1874
+		$picto='bill';
1875
+		if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice
1876
+		if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note
1877
+		if ($this->type == self::TYPE_DEPOSIT)     $picto.='d'; // Deposit invoice
1878
+
1879
+		$label = '<u>' . $langs->trans("ShowSupplierInvoice") . '</u>';
1880
+		if (! empty($this->ref))
1881
+			$label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1882
+		if (! empty($this->ref_supplier))
1883
+			$label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
1884
+		if (! empty($this->total_ht))
1885
+			$label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1886
+		if (! empty($this->total_tva))
1887
+			$label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1888
+		if (! empty($this->total_ttc))
1889
+			$label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1890
+		if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1891
+		if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1892
+		if ($this->type == self::TYPE_DEPOSIT)     $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1893
+		if ($moretitle) $label.=' - '.$moretitle;
1894
+
1895
+		$ref=$this->ref;
1896
+		if (empty($ref)) $ref=$this->id;
1897
+
1898
+		$linkclose='';
1899
+		if (empty($notooltip))
1900
+		{
1901
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1902
+			{
1903
+				$label=$langs->trans("ShowSupplierInvoice");
1904
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1905
+			}
1906
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1907
+			$linkclose.=' class="classfortooltip"';
1908
+		}
1909
+
1910
+		$linkstart = '<a href="'.$url.'"';
1911
+		$linkstart.=$linkclose.'>';
1912
+		$linkend='</a>';
1913
+
1914
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
1915
+		$result.=$linkstart.($max?dol_trunc($ref,$max):$ref).$linkend;
1916
+		return $result;
1917
+	}
1918 1918
 
1919 1919
 	 /**
1920
-      *      Return next reference of supplier invoice not already used (or last reference)
1921
-      *      according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER
1922
-      *
1923
-      *      @param	   Societe		$soc		Thirdparty object
1924
-      *      @param    string		$mode		'next' for next value or 'last' for last value
1925
-      *      @return   string					free ref or last ref
1926
-      */
1927
-    public function getNextNumRef($soc,$mode='next')
1928
-    {
1929
-        global $db, $langs, $conf;
1930
-        $langs->load("orders");
1931
-
1932
-        // Clean parameters (if not defined or using deprecated value)
1933
-        if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
1934
-
1935
-        $mybool=false;
1936
-
1937
-        $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php";
1938
-        $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER;
1939
-
1940
-        // Include file with class
1941
-        $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1942
-
1943
-        foreach ($dirmodels as $reldir) {
1944
-
1945
-            $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
1946
-
1947
-            // Load file with numbering class (if found)
1948
-            $mybool|=@include_once $dir.$file;
1949
-        }
1950
-
1951
-        if (! $mybool)
1952
-        {
1953
-        	dol_print_error('',"Failed to include file ".$file);
1954
-        	return '';
1955
-        }
1956
-
1957
-        $obj = new $classname();
1958
-        $numref = "";
1959
-        $numref = $obj->getNumRef($soc,$this,$mode);
1960
-
1961
-        if ($numref != "")
1962
-        {
1963
-        	return $numref;
1964
-        }
1965
-        else
1966
-       {
1967
-       		$this->error=$obj->error;
1968
-        	//dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error);
1969
-        	return false;
1970
-        }
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     *  Initialise an instance with random values.
1976
-     *  Used to build previews or test instances.
1977
-     *	id must be 0 if object instance is a specimen.
1978
-     *
1920
+	  *      Return next reference of supplier invoice not already used (or last reference)
1921
+	  *      according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER
1922
+	  *
1923
+	  *      @param	   Societe		$soc		Thirdparty object
1924
+	  *      @param    string		$mode		'next' for next value or 'last' for last value
1925
+	  *      @return   string					free ref or last ref
1926
+	  */
1927
+	public function getNextNumRef($soc,$mode='next')
1928
+	{
1929
+		global $db, $langs, $conf;
1930
+		$langs->load("orders");
1931
+
1932
+		// Clean parameters (if not defined or using deprecated value)
1933
+		if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
1934
+
1935
+		$mybool=false;
1936
+
1937
+		$file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php";
1938
+		$classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER;
1939
+
1940
+		// Include file with class
1941
+		$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1942
+
1943
+		foreach ($dirmodels as $reldir) {
1944
+
1945
+			$dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
1946
+
1947
+			// Load file with numbering class (if found)
1948
+			$mybool|=@include_once $dir.$file;
1949
+		}
1950
+
1951
+		if (! $mybool)
1952
+		{
1953
+			dol_print_error('',"Failed to include file ".$file);
1954
+			return '';
1955
+		}
1956
+
1957
+		$obj = new $classname();
1958
+		$numref = "";
1959
+		$numref = $obj->getNumRef($soc,$this,$mode);
1960
+
1961
+		if ($numref != "")
1962
+		{
1963
+			return $numref;
1964
+		}
1965
+		else
1966
+	   {
1967
+	   		$this->error=$obj->error;
1968
+			//dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error);
1969
+			return false;
1970
+		}
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 *  Initialise an instance with random values.
1976
+	 *  Used to build previews or test instances.
1977
+	 *	id must be 0 if object instance is a specimen.
1978
+	 *
1979 1979
 	 *	@param	string		$option		''=Create a specimen invoice with lines, 'nolines'=No lines
1980
-     *  @return	void
1981
-     */
1982
-    public function initAsSpecimen($option='')
1983
-    {
1984
-        global $langs,$conf;
1980
+	 *  @return	void
1981
+	 */
1982
+	public function initAsSpecimen($option='')
1983
+	{
1984
+		global $langs,$conf;
1985 1985
 		include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1986 1986
 
1987
-        $now = dol_now();
1988
-
1989
-        // Load array of products prodids
1990
-        $num_prods = 0;
1991
-        $prodids = array();
1992
-
1993
-        $sql = "SELECT rowid";
1994
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
1995
-        $sql.= " WHERE entity IN (".getEntity('product').")";
1996
-
1997
-        $resql = $this->db->query($sql);
1998
-        if ($resql)
1999
-        {
2000
-            $num_prods = $this->db->num_rows($resql);
2001
-            $i = 0;
2002
-            while ($i < $num_prods)
2003
-            {
2004
-                $i++;
2005
-                $row = $this->db->fetch_row($resql);
2006
-                $prodids[$i] = $row[0];
2007
-            }
2008
-        }
2009
-
2010
-        // Initialise parametres
2011
-        $this->id=0;
2012
-        $this->ref = 'SPECIMEN';
2013
-        $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
2014
-        $this->specimen=1;
2015
-        $this->socid = 1;
2016
-        $this->date = $now;
2017
-        $this->date_lim_reglement=$this->date+3600*24*30;
2018
-        $this->cond_reglement_code = 'RECEP';
2019
-        $this->mode_reglement_code = 'CHQ';
2020
-        $this->note_public='This is a comment (public)';
2021
-        $this->note_private='This is a comment (private)';
1987
+		$now = dol_now();
1988
+
1989
+		// Load array of products prodids
1990
+		$num_prods = 0;
1991
+		$prodids = array();
1992
+
1993
+		$sql = "SELECT rowid";
1994
+		$sql.= " FROM ".MAIN_DB_PREFIX."product";
1995
+		$sql.= " WHERE entity IN (".getEntity('product').")";
1996
+
1997
+		$resql = $this->db->query($sql);
1998
+		if ($resql)
1999
+		{
2000
+			$num_prods = $this->db->num_rows($resql);
2001
+			$i = 0;
2002
+			while ($i < $num_prods)
2003
+			{
2004
+				$i++;
2005
+				$row = $this->db->fetch_row($resql);
2006
+				$prodids[$i] = $row[0];
2007
+			}
2008
+		}
2009
+
2010
+		// Initialise parametres
2011
+		$this->id=0;
2012
+		$this->ref = 'SPECIMEN';
2013
+		$this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
2014
+		$this->specimen=1;
2015
+		$this->socid = 1;
2016
+		$this->date = $now;
2017
+		$this->date_lim_reglement=$this->date+3600*24*30;
2018
+		$this->cond_reglement_code = 'RECEP';
2019
+		$this->mode_reglement_code = 'CHQ';
2020
+		$this->note_public='This is a comment (public)';
2021
+		$this->note_private='This is a comment (private)';
2022 2022
 
2023 2023
 		if (empty($option) || $option != 'nolines')
2024 2024
 		{
2025
-	        // Lines
2026
-	        $nbp = 5;
2027
-	        $xnbp = 0;
2028
-	        while ($xnbp < $nbp)
2029
-	        {
2030
-	            $line=new FactureLigne($this->db);
2031
-	            $line->desc=$langs->trans("Description")." ".$xnbp;
2032
-	            $line->qty=1;
2033
-	            $line->subprice=100;
2034
-	            $line->pu_ht=100;		// the canelle template use pu_ht and not subprice
2035
-	            $line->price=100;
2036
-	            $line->tva_tx=19.6;
2037
-	            $line->localtax1_tx=0;
2038
-	            $line->localtax2_tx=0;
2025
+			// Lines
2026
+			$nbp = 5;
2027
+			$xnbp = 0;
2028
+			while ($xnbp < $nbp)
2029
+			{
2030
+				$line=new FactureLigne($this->db);
2031
+				$line->desc=$langs->trans("Description")." ".$xnbp;
2032
+				$line->qty=1;
2033
+				$line->subprice=100;
2034
+				$line->pu_ht=100;		// the canelle template use pu_ht and not subprice
2035
+				$line->price=100;
2036
+				$line->tva_tx=19.6;
2037
+				$line->localtax1_tx=0;
2038
+				$line->localtax2_tx=0;
2039 2039
 				if ($xnbp == 2)
2040 2040
 				{
2041
-				    $line->total_ht=50;
2042
-				    $line->total_ttc=59.8;
2043
-				    $line->total_tva=9.8;
2044
-	    			$line->remise_percent=50;
2041
+					$line->total_ht=50;
2042
+					$line->total_ttc=59.8;
2043
+					$line->total_tva=9.8;
2044
+					$line->remise_percent=50;
2045 2045
 				}
2046 2046
 				else
2047 2047
 				{
2048
-				    $line->total_ht=100;
2049
-				    $line->total_ttc=119.6;
2050
-				    $line->total_tva=19.6;
2051
-	    			$line->remise_percent=0;
2048
+					$line->total_ht=100;
2049
+					$line->total_ttc=119.6;
2050
+					$line->total_tva=19.6;
2051
+					$line->remise_percent=0;
2052 2052
 				}
2053 2053
 
2054
-	            if ($num_prods > 0)
2055
-	            {
2054
+				if ($num_prods > 0)
2055
+				{
2056 2056
 					$prodid = mt_rand(1, $num_prods);
2057
-	            	$line->fk_product=$prodids[$prodid];
2058
-	            }
2059
-	            $line->product_type=0;
2057
+					$line->fk_product=$prodids[$prodid];
2058
+				}
2059
+				$line->product_type=0;
2060 2060
 
2061
-	            $this->lines[$xnbp]=$line;
2061
+				$this->lines[$xnbp]=$line;
2062 2062
 
2063
-	    		$this->total_ht       += $line->total_ht;
2064
-	    		$this->total_tva      += $line->total_tva;
2065
-	    		$this->total_ttc      += $line->total_ttc;
2063
+				$this->total_ht       += $line->total_ht;
2064
+				$this->total_tva      += $line->total_tva;
2065
+				$this->total_ttc      += $line->total_ttc;
2066 2066
 
2067
-	    		$xnbp++;
2068
-	        }
2067
+				$xnbp++;
2068
+			}
2069 2069
 		}
2070 2070
 
2071
-        $this->amount_ht      = $xnbp*100;
2072
-        $this->total_ht       = $xnbp*100;
2073
-        $this->total_tva      = $xnbp*19.6;
2074
-        $this->total_ttc      = $xnbp*119.6;
2075
-    }
2071
+		$this->amount_ht      = $xnbp*100;
2072
+		$this->total_ht       = $xnbp*100;
2073
+		$this->total_tva      = $xnbp*19.6;
2074
+		$this->total_ttc      = $xnbp*119.6;
2075
+	}
2076 2076
 
2077 2077
 	/**
2078 2078
 	 *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
@@ -2105,7 +2105,7 @@  discard block
 block discarded – undo
2105 2105
 			{
2106 2106
 				$this->nb["supplier_invoices"]=$obj->nb;
2107 2107
 			}
2108
-            $this->db->free($resql);
2108
+			$this->db->free($resql);
2109 2109
 			return 1;
2110 2110
 		}
2111 2111
 		else
@@ -2116,83 +2116,83 @@  discard block
 block discarded – undo
2116 2116
 		}
2117 2117
 	}
2118 2118
 
2119
-    /**
2120
-     *	Load an object from its id and create a new one in database
2121
-     *
2122
-     *	@param      int		$fromid     	Id of object to clone
2123
-     *	@param		int		$invertdetail	Reverse sign of amounts for lines
2124
-     * 	@return		int						New id of clone
2125
-     */
2126
-    public function createFromClone($fromid,$invertdetail=0)
2127
-    {
2128
-        global $user,$langs;
2119
+	/**
2120
+	 *	Load an object from its id and create a new one in database
2121
+	 *
2122
+	 *	@param      int		$fromid     	Id of object to clone
2123
+	 *	@param		int		$invertdetail	Reverse sign of amounts for lines
2124
+	 * 	@return		int						New id of clone
2125
+	 */
2126
+	public function createFromClone($fromid,$invertdetail=0)
2127
+	{
2128
+		global $user,$langs;
2129 2129
 
2130
-        $error=0;
2130
+		$error=0;
2131 2131
 
2132
-        $object=new FactureFournisseur($this->db);
2132
+		$object=new FactureFournisseur($this->db);
2133 2133
 
2134 2134
 		$object->context['createfromclone'] = 'createfromclone';
2135 2135
 
2136 2136
 		$this->db->begin();
2137 2137
 
2138
-        // Load source object
2139
-        $object->fetch($fromid);
2140
-        $object->id=0;
2141
-        $object->statut=self::STATUS_DRAFT;
2142
-
2143
-        // Clear fields
2144
-        $object->ref_supplier=$langs->trans("CopyOf").' '.$object->ref_supplier;
2145
-        $object->author             = $user->id;
2146
-        $object->user_valid         = '';
2147
-        $object->fk_facture_source  = 0;
2148
-        $object->date_creation      = '';
2149
-        $object->date_validation    = '';
2150
-        $object->date               = '';
2151
-        $object->date_echeance      = '';
2152
-        $object->ref_client         = '';
2153
-        $object->close_code         = '';
2154
-        $object->close_note         = '';
2155
-
2156
-        // Loop on each line of new invoice
2157
-        foreach($object->lines as $i => $line)
2158
-        {
2159
-            if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
2160
-            {
2161
-                unset($object->lines[$i]);
2162
-            }
2163
-        }
2164
-
2165
-        // Create clone
2166
-        $result=$object->create($user);
2167
-
2168
-        // Other options
2169
-        if ($result < 0)
2170
-        {
2171
-            $this->error=$object->error;
2172
-            $error++;
2173
-        }
2174
-
2175
-        if (! $error)
2176
-        {
2177
-
2178
-
2179
-
2180
-        }
2181
-
2182
-        unset($object->context['createfromclone']);
2183
-
2184
-        // End
2185
-        if (! $error)
2186
-        {
2187
-            $this->db->commit();
2188
-            return $object->id;
2189
-        }
2190
-        else
2191
-        {
2192
-            $this->db->rollback();
2193
-            return -1;
2194
-        }
2195
-    }
2138
+		// Load source object
2139
+		$object->fetch($fromid);
2140
+		$object->id=0;
2141
+		$object->statut=self::STATUS_DRAFT;
2142
+
2143
+		// Clear fields
2144
+		$object->ref_supplier=$langs->trans("CopyOf").' '.$object->ref_supplier;
2145
+		$object->author             = $user->id;
2146
+		$object->user_valid         = '';
2147
+		$object->fk_facture_source  = 0;
2148
+		$object->date_creation      = '';
2149
+		$object->date_validation    = '';
2150
+		$object->date               = '';
2151
+		$object->date_echeance      = '';
2152
+		$object->ref_client         = '';
2153
+		$object->close_code         = '';
2154
+		$object->close_note         = '';
2155
+
2156
+		// Loop on each line of new invoice
2157
+		foreach($object->lines as $i => $line)
2158
+		{
2159
+			if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
2160
+			{
2161
+				unset($object->lines[$i]);
2162
+			}
2163
+		}
2164
+
2165
+		// Create clone
2166
+		$result=$object->create($user);
2167
+
2168
+		// Other options
2169
+		if ($result < 0)
2170
+		{
2171
+			$this->error=$object->error;
2172
+			$error++;
2173
+		}
2174
+
2175
+		if (! $error)
2176
+		{
2177
+
2178
+
2179
+
2180
+		}
2181
+
2182
+		unset($object->context['createfromclone']);
2183
+
2184
+		// End
2185
+		if (! $error)
2186
+		{
2187
+			$this->db->commit();
2188
+			return $object->id;
2189
+		}
2190
+		else
2191
+		{
2192
+			$this->db->rollback();
2193
+			return -1;
2194
+		}
2195
+	}
2196 2196
 
2197 2197
 	/**
2198 2198
 	 *	Create a document onto disk according to template model.
@@ -2225,13 +2225,13 @@  discard block
 block discarded – undo
2225 2225
 
2226 2226
 		if (empty($modele))
2227 2227
 		{
2228
-		    return 0;
2228
+			return 0;
2229 2229
 		}
2230 2230
 		else
2231 2231
 		{
2232
-            $modelpath = "core/modules/supplier_invoice/pdf/";
2232
+			$modelpath = "core/modules/supplier_invoice/pdf/";
2233 2233
 
2234
-            return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2234
+			return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2235 2235
 		}
2236 2236
 	}
2237 2237
 
@@ -2263,23 +2263,23 @@  discard block
 block discarded – undo
2263 2263
 		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2264 2264
 	}
2265 2265
 
2266
-    /**
2267
-     * Is the payment of the supplier invoice having a delay?
2268
-     *
2269
-     * @return bool
2270
-     */
2271
-    public function hasDelay()
2272
-    {
2273
-        global $conf;
2266
+	/**
2267
+	 * Is the payment of the supplier invoice having a delay?
2268
+	 *
2269
+	 * @return bool
2270
+	 */
2271
+	public function hasDelay()
2272
+	{
2273
+		global $conf;
2274 2274
 
2275
-        $now = dol_now();
2275
+		$now = dol_now();
2276 2276
 
2277
-        if (!$this->date_echeance) {
2278
-            return false;
2279
-        }
2277
+		if (!$this->date_echeance) {
2278
+			return false;
2279
+		}
2280 2280
 
2281
-        return ($this->statut == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
2282
-    }
2281
+		return ($this->statut == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
2282
+	}
2283 2283
 }
2284 2284
 
2285 2285
 
@@ -2406,14 +2406,14 @@  discard block
 block discarded – undo
2406 2406
 	public $multicurrency_total_ttc;
2407 2407
 
2408 2408
 	/**
2409
-     *	Constructor
2410
-     *
2411
-     *  @param		DoliDB		$db      Database handler
2412
-     */
2413
-    public function __construct($db)
2414
-    {
2415
-        $this->db= $db;
2416
-    }
2409
+	 *	Constructor
2410
+	 *
2411
+	 *  @param		DoliDB		$db      Database handler
2412
+	 */
2413
+	public function __construct($db)
2414
+	{
2415
+		$this->db= $db;
2416
+	}
2417 2417
 
2418 2418
 	/**
2419 2419
 	 * Retrieves a supplier invoice line
@@ -2571,7 +2571,7 @@  discard block
 block discarded – undo
2571 2571
 		if (empty($this->fk_unit)) {
2572 2572
 			$fk_unit = "null";
2573 2573
 		} else {
2574
-		    $fk_unit = "'".$this->db->escape($this->fk_unit)."'";
2574
+			$fk_unit = "'".$this->db->escape($this->fk_unit)."'";
2575 2575
 		}
2576 2576
 
2577 2577
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
@@ -2598,9 +2598,9 @@  discard block
 block discarded – undo
2598 2598
 
2599 2599
 		// Multicurrency
2600 2600
 		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
2601
-        $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
2602
-        $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
2603
-        $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
2601
+		$sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
2602
+		$sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
2603
+		$sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
2604 2604
 
2605 2605
 		$sql.= " WHERE rowid = ".$this->id;
2606 2606
 
@@ -2644,179 +2644,179 @@  discard block
 block discarded – undo
2644 2644
 		return 1;
2645 2645
 	}
2646 2646
 
2647
-    /**
2648
-     *	Insert line into database
2649
-     *
2650
-     *	@param      int		$notrigger		1 no triggers
2651
-     *	@return		int						<0 if KO, >0 if OK
2652
-     */
2653
-    public function insert($notrigger=0)
2654
-    {
2655
-        global $user,$conf;
2656
-
2657
-        $error=0;
2658
-
2659
-        dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
2660
-
2661
-        // Clean parameters
2662
-        $this->desc=trim($this->desc);
2663
-        if (empty($this->tva_tx)) $this->tva_tx=0;
2664
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
2665
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
2666
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
2667
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
2668
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
2669
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
2670
-        if (empty($this->rang)) $this->rang=0;
2671
-        if (empty($this->remise_percent)) $this->remise_percent=0;
2672
-        if (empty($this->info_bits)) $this->info_bits=0;
2673
-        if (empty($this->subprice)) $this->subprice=0;
2674
-        if (empty($this->special_code)) $this->special_code=0;
2675
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
2676
-        if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
2677
-
2678
-        if (empty($this->pa_ht)) $this->pa_ht=0;
2679
-        if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
2680
-        if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
2681
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
2682
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
2683
-
2684
-
2685
-        // Check parameters
2686
-        if ($this->product_type < 0)
2687
-        {
2688
-            $this->error='ErrorProductTypeMustBe0orMore';
2689
-            return -1;
2690
-        }
2691
-        if (! empty($this->fk_product))
2692
-        {
2693
-            // Check product exists
2694
-            $result=Product::isExistingObject('product', $this->fk_product);
2695
-            if ($result <= 0)
2696
-            {
2697
-                $this->error='ErrorProductIdDoesNotExists';
2698
-                return -1;
2699
-            }
2700
-        }
2701
-
2702
-        $this->db->begin();
2703
-
2704
-        // Insertion dans base de la ligne
2705
-        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
2706
-        $sql.= ' (fk_facture_fourn, fk_parent_line, label, description, qty,';
2707
-        $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
2708
-        $sql.= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,';
2709
-        $sql.= ' date_start, date_end, fk_code_ventilation, rang, special_code,';
2710
-        $sql.= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit';
2711
-        $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2712
-        $sql.= ')';
2713
-        $sql.= " VALUES (".$this->fk_facture_fourn.",";
2714
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
2715
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
2716
-        $sql.= " '".$this->db->escape($this->desc)."',";
2717
-        $sql.= " ".price2num($this->qty).",";
2718
-
2719
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
2720
-        $sql.= " ".price2num($this->tva_tx).",";
2721
-        $sql.= " ".price2num($this->localtax1_tx).",";
2722
-        $sql.= " ".price2num($this->localtax2_tx).",";
2723
-        $sql.= " '".$this->db->escape($this->localtax1_type)."',";
2724
-        $sql.= " '".$this->db->escape($this->localtax2_type)."',";
2725
-        $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
2726
-        $sql.= " ".$this->product_type.",";
2727
-        $sql.= " ".price2num($this->remise_percent).",";
2728
-        $sql.= " ".price2num($this->subprice).",";
2729
-        $sql.= " ".price2num($this->total_ttc/$this->qty).",";
2730
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").",";
2731
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").",";
2732
-        $sql.= ' '.(!empty($this->fk_code_ventilation)?$this->fk_code_ventilation:0).',';
2733
-        $sql.= ' '.$this->rang.',';
2734
-        $sql.= ' '.$this->special_code.',';
2735
-        $sql.= " '".$this->db->escape($this->info_bits)."',";
2736
-        $sql.= " ".price2num($this->total_ht).",";
2737
-        $sql.= " ".price2num($this->total_tva).",";
2738
-        $sql.= " ".price2num($this->total_ttc).",";
2739
-        $sql.= " ".price2num($this->total_localtax1).",";
2740
-        $sql.= " ".price2num($this->total_localtax2);
2741
-        $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
2742
-        $sql.= ", ".(int) $this->fk_multicurrency;
2743
-        $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
2744
-        $sql.= ", ".price2num($this->multicurrency_subprice);
2745
-        $sql.= ", ".price2num($this->multicurrency_total_ht);
2746
-        $sql.= ", ".price2num($this->multicurrency_total_tva);
2747
-        $sql.= ", ".price2num($this->multicurrency_total_ttc);
2748
-        $sql.= ')';
2749
-
2750
-        dol_syslog(get_class($this)."::insert", LOG_DEBUG);
2751
-        $resql=$this->db->query($sql);
2752
-        if ($resql)
2753
-        {
2754
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
2755
-            $this->rowid=$this->id;
2756
-
2757
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2758
-            {
2759
-                $result=$this->insertExtraFields();
2760
-                if ($result < 0)
2761
-                {
2762
-                    $error++;
2763
-                }
2764
-            }
2765
-
2766
-            if (! $notrigger)
2767
-            {
2768
-                // Call trigger
2769
-                $result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE',$user);
2770
-                if ($result < 0)
2771
-                {
2772
-                    $this->db->rollback();
2773
-                    return -2;
2774
-                }
2775
-                // End call triggers
2776
-            }
2777
-
2778
-            $this->db->commit();
2779
-            return $this->id;
2780
-
2781
-        }
2782
-        else
2783
-        {
2784
-            $this->error=$this->db->error();
2785
-            $this->db->rollback();
2786
-            return -2;
2787
-        }
2788
-    }
2789
-            /**
2790
-     *  Mise a jour de l'objet ligne de commande en base
2791
-     *
2792
-     *  @return		int		<0 si ko, >0 si ok
2793
-     */
2794
-    function update_total()
2795
-    {
2796
-        $this->db->begin();
2797
-
2798
-        // Mise a jour ligne en base
2799
-        $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
2800
-        $sql.= "  total_ht='".price2num($this->total_ht)."'";
2801
-        $sql.= ", tva='".price2num($this->total_tva)."'";
2802
-        $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
2803
-        $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
2804
-        $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
2805
-        $sql.= " WHERE rowid = ".$this->rowid;
2806
-
2807
-        dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG);
2808
-
2809
-        $resql=$this->db->query($sql);
2810
-        if ($resql)
2811
-        {
2812
-            $this->db->commit();
2813
-            return 1;
2814
-        }
2815
-        else
2816
-        {
2817
-            $this->error=$this->db->error();
2818
-            $this->db->rollback();
2819
-            return -2;
2820
-        }
2821
-    }
2647
+	/**
2648
+	 *	Insert line into database
2649
+	 *
2650
+	 *	@param      int		$notrigger		1 no triggers
2651
+	 *	@return		int						<0 if KO, >0 if OK
2652
+	 */
2653
+	public function insert($notrigger=0)
2654
+	{
2655
+		global $user,$conf;
2656
+
2657
+		$error=0;
2658
+
2659
+		dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
2660
+
2661
+		// Clean parameters
2662
+		$this->desc=trim($this->desc);
2663
+		if (empty($this->tva_tx)) $this->tva_tx=0;
2664
+		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
2665
+		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
2666
+		if (empty($this->localtax1_type)) $this->localtax1_type='0';
2667
+		if (empty($this->localtax2_type)) $this->localtax2_type='0';
2668
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
2669
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
2670
+		if (empty($this->rang)) $this->rang=0;
2671
+		if (empty($this->remise_percent)) $this->remise_percent=0;
2672
+		if (empty($this->info_bits)) $this->info_bits=0;
2673
+		if (empty($this->subprice)) $this->subprice=0;
2674
+		if (empty($this->special_code)) $this->special_code=0;
2675
+		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
2676
+		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
2677
+
2678
+		if (empty($this->pa_ht)) $this->pa_ht=0;
2679
+		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
2680
+		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
2681
+		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
2682
+		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
2683
+
2684
+
2685
+		// Check parameters
2686
+		if ($this->product_type < 0)
2687
+		{
2688
+			$this->error='ErrorProductTypeMustBe0orMore';
2689
+			return -1;
2690
+		}
2691
+		if (! empty($this->fk_product))
2692
+		{
2693
+			// Check product exists
2694
+			$result=Product::isExistingObject('product', $this->fk_product);
2695
+			if ($result <= 0)
2696
+			{
2697
+				$this->error='ErrorProductIdDoesNotExists';
2698
+				return -1;
2699
+			}
2700
+		}
2701
+
2702
+		$this->db->begin();
2703
+
2704
+		// Insertion dans base de la ligne
2705
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
2706
+		$sql.= ' (fk_facture_fourn, fk_parent_line, label, description, qty,';
2707
+		$sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
2708
+		$sql.= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,';
2709
+		$sql.= ' date_start, date_end, fk_code_ventilation, rang, special_code,';
2710
+		$sql.= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit';
2711
+		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2712
+		$sql.= ')';
2713
+		$sql.= " VALUES (".$this->fk_facture_fourn.",";
2714
+		$sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
2715
+		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
2716
+		$sql.= " '".$this->db->escape($this->desc)."',";
2717
+		$sql.= " ".price2num($this->qty).",";
2718
+
2719
+		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
2720
+		$sql.= " ".price2num($this->tva_tx).",";
2721
+		$sql.= " ".price2num($this->localtax1_tx).",";
2722
+		$sql.= " ".price2num($this->localtax2_tx).",";
2723
+		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
2724
+		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
2725
+		$sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
2726
+		$sql.= " ".$this->product_type.",";
2727
+		$sql.= " ".price2num($this->remise_percent).",";
2728
+		$sql.= " ".price2num($this->subprice).",";
2729
+		$sql.= " ".price2num($this->total_ttc/$this->qty).",";
2730
+		$sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").",";
2731
+		$sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").",";
2732
+		$sql.= ' '.(!empty($this->fk_code_ventilation)?$this->fk_code_ventilation:0).',';
2733
+		$sql.= ' '.$this->rang.',';
2734
+		$sql.= ' '.$this->special_code.',';
2735
+		$sql.= " '".$this->db->escape($this->info_bits)."',";
2736
+		$sql.= " ".price2num($this->total_ht).",";
2737
+		$sql.= " ".price2num($this->total_tva).",";
2738
+		$sql.= " ".price2num($this->total_ttc).",";
2739
+		$sql.= " ".price2num($this->total_localtax1).",";
2740
+		$sql.= " ".price2num($this->total_localtax2);
2741
+		$sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
2742
+		$sql.= ", ".(int) $this->fk_multicurrency;
2743
+		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
2744
+		$sql.= ", ".price2num($this->multicurrency_subprice);
2745
+		$sql.= ", ".price2num($this->multicurrency_total_ht);
2746
+		$sql.= ", ".price2num($this->multicurrency_total_tva);
2747
+		$sql.= ", ".price2num($this->multicurrency_total_ttc);
2748
+		$sql.= ')';
2749
+
2750
+		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
2751
+		$resql=$this->db->query($sql);
2752
+		if ($resql)
2753
+		{
2754
+			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
2755
+			$this->rowid=$this->id;
2756
+
2757
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2758
+			{
2759
+				$result=$this->insertExtraFields();
2760
+				if ($result < 0)
2761
+				{
2762
+					$error++;
2763
+				}
2764
+			}
2765
+
2766
+			if (! $notrigger)
2767
+			{
2768
+				// Call trigger
2769
+				$result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE',$user);
2770
+				if ($result < 0)
2771
+				{
2772
+					$this->db->rollback();
2773
+					return -2;
2774
+				}
2775
+				// End call triggers
2776
+			}
2777
+
2778
+			$this->db->commit();
2779
+			return $this->id;
2780
+
2781
+		}
2782
+		else
2783
+		{
2784
+			$this->error=$this->db->error();
2785
+			$this->db->rollback();
2786
+			return -2;
2787
+		}
2788
+	}
2789
+			/**
2790
+			 *  Mise a jour de l'objet ligne de commande en base
2791
+			 *
2792
+			 *  @return		int		<0 si ko, >0 si ok
2793
+			 */
2794
+	function update_total()
2795
+	{
2796
+		$this->db->begin();
2797
+
2798
+		// Mise a jour ligne en base
2799
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
2800
+		$sql.= "  total_ht='".price2num($this->total_ht)."'";
2801
+		$sql.= ", tva='".price2num($this->total_tva)."'";
2802
+		$sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
2803
+		$sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
2804
+		$sql.= ", total_ttc='".price2num($this->total_ttc)."'";
2805
+		$sql.= " WHERE rowid = ".$this->rowid;
2806
+
2807
+		dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG);
2808
+
2809
+		$resql=$this->db->query($sql);
2810
+		if ($resql)
2811
+		{
2812
+			$this->db->commit();
2813
+			return 1;
2814
+		}
2815
+		else
2816
+		{
2817
+			$this->error=$this->db->error();
2818
+			$this->db->rollback();
2819
+			return -2;
2820
+		}
2821
+	}
2822 2822
  }
Please login to merge, or discard this patch.
Spacing   +709 added lines, -709 removed lines patch added patch discarded remove patch
@@ -40,12 +40,12 @@  discard block
 block discarded – undo
40 40
  */
41 41
 class FactureFournisseur extends CommonInvoice
42 42
 {
43
-    public $element='invoice_supplier';
44
-    public $table_element='facture_fourn';
45
-    public $table_element_line='facture_fourn_det';
46
-    public $fk_element='fk_facture_fourn';
47
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
-    public $picto='bill';
43
+    public $element = 'invoice_supplier';
44
+    public $table_element = 'facture_fourn';
45
+    public $table_element_line = 'facture_fourn_det';
46
+    public $fk_element = 'fk_facture_fourn';
47
+    protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
+    public $picto = 'bill';
49 49
 
50 50
     /**
51 51
      * {@inheritdoc}
@@ -76,10 +76,10 @@  discard block
 block discarded – undo
76 76
 
77 77
     public $author;
78 78
     public $libelle;
79
-    public $datec;            // Creation date
80
-    public $tms;              // Last update date
81
-    public $date;             // Invoice date
82
-    public $date_echeance;    // Max payment date
79
+    public $datec; // Creation date
80
+    public $tms; // Last update date
81
+    public $date; // Invoice date
82
+    public $date_echeance; // Max payment date
83 83
     public $amount;
84 84
     public $remise;
85 85
     public $tva;
@@ -117,9 +117,9 @@  discard block
 block discarded – undo
117 117
 	//Incorterms
118 118
     public $fk_incoterms;
119 119
     public $location_incoterms;
120
-    public $libelle_incoterms;  //Used into tooltip
120
+    public $libelle_incoterms; //Used into tooltip
121 121
 
122
-    public $extraparams=array();
122
+    public $extraparams = array();
123 123
 
124 124
 	// Multicurrency
125 125
     public $fk_multicurrency;
@@ -214,15 +214,15 @@  discard block
 block discarded – undo
214 214
      */
215 215
     public function create($user)
216 216
     {
217
-        global $langs,$conf,$hookmanager;
217
+        global $langs, $conf, $hookmanager;
218 218
 
219
-		$error=0;
220
-        $now=dol_now();
219
+		$error = 0;
220
+        $now = dol_now();
221 221
 
222 222
         // Clean parameters
223
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
223
+        if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier);
224 224
         if (empty($this->type)) $this->type = self::TYPE_STANDARD;
225
-        if (empty($this->date)) $this->date=$now;
225
+        if (empty($this->date)) $this->date = $now;
226 226
 
227 227
         $socid = $this->socid;
228 228
         $ref_supplier = $this->ref_supplier;
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
         $remise = $this->remise;
231 231
 
232 232
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
233
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
233
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
234 234
 		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
235 235
 		if (empty($this->fk_multicurrency))
236 236
 		{
@@ -241,76 +241,76 @@  discard block
 block discarded – undo
241 241
 
242 242
         $this->db->begin();
243 243
 
244
-        if (! $remise) $remise = 0 ;
244
+        if (!$remise) $remise = 0;
245 245
         $totalht = ($amount - $remise);
246 246
 
247 247
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
248
-		$sql.= "ref";
249
-        $sql.= ", ref_supplier";
250
-        $sql.= ", entity";
251
-        $sql.= ", type";
252
-        $sql.= ", libelle";
253
-        $sql.= ", fk_soc";
254
-        $sql.= ", datec";
255
-        $sql.= ", datef";
256
-		$sql.= ", fk_projet";
257
-		$sql.= ", fk_cond_reglement";
258
-		$sql.= ", fk_mode_reglement";
259
-        $sql.= ", fk_account";
260
-        $sql.= ", note_private";
261
-        $sql.= ", note_public";
262
-        $sql.= ", fk_user_author";
263
-        $sql.= ", date_lim_reglement";
264
-		$sql.= ", fk_incoterms, location_incoterms";
265
-        $sql.= ", fk_multicurrency";
266
-        $sql.= ", multicurrency_code";
267
-        $sql.= ", multicurrency_tx";
268
-        $sql.= ", fk_facture_source";
269
-        $sql.= ")";
270
-        $sql.= " VALUES (";
271
-		$sql.= "'(PROV)'";
272
-        $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
273
-        $sql.= ", ".$conf->entity;
274
-        $sql.= ", '".$this->db->escape($this->type)."'";
275
-        $sql.= ", '".$this->db->escape($this->libelle)."'";
276
-        $sql.= ", ".$this->socid;
277
-        $sql.= ", '".$this->db->idate($now)."'";
278
-        $sql.= ", '".$this->db->idate($this->date)."'";
279
-		$sql.= ", ".(isset($this->fk_project)?$this->fk_project:"null");
280
-		$sql.= ", ".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null");
281
-		$sql.= ", ".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null");
282
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
283
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
284
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
285
-        $sql.= ", ".$user->id.",";
286
-        $sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null";
287
-		$sql.= ", ".(int) $this->fk_incoterms;
288
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
289
-		$sql.= ", ".(int) $this->fk_multicurrency;
290
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
291
-		$sql.= ", ".(double) $this->multicurrency_tx;
292
-        $sql.= ", ".(isset($this->fk_facture_source)?$this->fk_facture_source:"NULL");
293
-        $sql.= ")";
248
+		$sql .= "ref";
249
+        $sql .= ", ref_supplier";
250
+        $sql .= ", entity";
251
+        $sql .= ", type";
252
+        $sql .= ", libelle";
253
+        $sql .= ", fk_soc";
254
+        $sql .= ", datec";
255
+        $sql .= ", datef";
256
+		$sql .= ", fk_projet";
257
+		$sql .= ", fk_cond_reglement";
258
+		$sql .= ", fk_mode_reglement";
259
+        $sql .= ", fk_account";
260
+        $sql .= ", note_private";
261
+        $sql .= ", note_public";
262
+        $sql .= ", fk_user_author";
263
+        $sql .= ", date_lim_reglement";
264
+		$sql .= ", fk_incoterms, location_incoterms";
265
+        $sql .= ", fk_multicurrency";
266
+        $sql .= ", multicurrency_code";
267
+        $sql .= ", multicurrency_tx";
268
+        $sql .= ", fk_facture_source";
269
+        $sql .= ")";
270
+        $sql .= " VALUES (";
271
+		$sql .= "'(PROV)'";
272
+        $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
273
+        $sql .= ", ".$conf->entity;
274
+        $sql .= ", '".$this->db->escape($this->type)."'";
275
+        $sql .= ", '".$this->db->escape($this->libelle)."'";
276
+        $sql .= ", ".$this->socid;
277
+        $sql .= ", '".$this->db->idate($now)."'";
278
+        $sql .= ", '".$this->db->idate($this->date)."'";
279
+		$sql .= ", ".(isset($this->fk_project) ? $this->fk_project : "null");
280
+		$sql .= ", ".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null");
281
+		$sql .= ", ".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null");
282
+        $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
283
+        $sql .= ", '".$this->db->escape($this->note_private)."'";
284
+        $sql .= ", '".$this->db->escape($this->note_public)."'";
285
+        $sql .= ", ".$user->id.",";
286
+        $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
287
+		$sql .= ", ".(int) $this->fk_incoterms;
288
+        $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
289
+		$sql .= ", ".(int) $this->fk_multicurrency;
290
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
291
+		$sql .= ", ".(double) $this->multicurrency_tx;
292
+        $sql .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL");
293
+        $sql .= ")";
294 294
 
295 295
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
296
-        $resql=$this->db->query($sql);
296
+        $resql = $this->db->query($sql);
297 297
         if ($resql)
298 298
         {
299 299
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
300 300
 
301 301
             // Update ref with new one
302
-            $this->ref='(PROV'.$this->id.')';
302
+            $this->ref = '(PROV'.$this->id.')';
303 303
             $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
304 304
 
305 305
             dol_syslog(get_class($this)."::create", LOG_DEBUG);
306
-            $resql=$this->db->query($sql);
307
-            if (! $resql) $error++;
306
+            $resql = $this->db->query($sql);
307
+            if (!$resql) $error++;
308 308
 
309 309
             // Add object linked
310
-            if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id))
310
+            if (!$error && $this->id && !empty($this->origin) && !empty($this->origin_id))
311 311
             {
312 312
                 $ret = $this->add_object_linked();
313
-                if (! $ret)
313
+                if (!$ret)
314 314
                 {
315 315
                     dol_print_error($this->db);
316 316
                     $error++;
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
                     $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
326 326
                     $sql .= ' VALUES ('.$this->id.')';
327 327
 
328
-                    $resql_insert=$this->db->query($sql);
328
+                    $resql_insert = $this->db->query($sql);
329 329
                     if ($resql_insert)
330 330
                     {
331 331
                         $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
@@ -340,13 +340,13 @@  discard block
 block discarded – undo
340 340
                             $this->lines[$i]->qty,
341 341
                             $this->lines[$i]->fk_product,
342 342
                             'HT',
343
-                            (! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''),
343
+                            (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
344 344
                             $this->lines[$i]->product_type
345 345
                         );
346 346
                     }
347 347
                     else
348 348
                     {
349
-                        $this->error=$this->db->lasterror();
349
+                        $this->error = $this->db->lasterror();
350 350
                         $this->db->rollback();
351 351
                         return -5;
352 352
                     }
@@ -361,12 +361,12 @@  discard block
 block discarded – undo
361 361
 
362 362
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
363 363
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
364
-                	if (! is_object($line)) $line = (object) $line;
364
+                	if (!is_object($line)) $line = (object) $line;
365 365
 
366 366
                 	$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
367 367
 			        $sql .= ' VALUES ('.$this->id.')';
368 368
 
369
-			        $resql_insert=$this->db->query($sql);
369
+			        $resql_insert = $this->db->query($sql);
370 370
 			        if ($resql_insert)
371 371
 			        {
372 372
 			            $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
@@ -381,13 +381,13 @@  discard block
 block discarded – undo
381 381
 			                $line->qty,
382 382
 			                $line->fk_product,
383 383
 			                'HT',
384
-			                (! empty($line->info_bits)?$line->info_bits:''),
384
+			                (!empty($line->info_bits) ? $line->info_bits : ''),
385 385
 			                $line->product_type
386 386
 			                );
387 387
 			        }
388 388
 			        else
389 389
 			        {
390
-			            $this->error=$this->db->lasterror();
390
+			            $this->error = $this->db->lasterror();
391 391
 			            $this->db->rollback();
392 392
 			            return -5;
393 393
 			        }
@@ -395,21 +395,21 @@  discard block
 block discarded – undo
395 395
 			}
396 396
 
397 397
             // Update total price
398
-            $result=$this->update_price();
398
+            $result = $this->update_price();
399 399
             if ($result > 0)
400 400
             {
401
-            	$action='create';
401
+            	$action = 'create';
402 402
 
403 403
 				// Actions on extra fields (by external module or standard code)
404 404
 				// TODO le hook fait double emploi avec le trigger !!
405 405
 				$hookmanager->initHooks(array('supplierinvoicedao'));
406
-				$parameters=array('socid'=>$this->id);
407
-				$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
406
+				$parameters = array('socid'=>$this->id);
407
+				$reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
408 408
 				if (empty($reshook))
409 409
 				{
410 410
 	            	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
411 411
 					{
412
-						$result=$this->insertExtraFields();               // This also set $this->error or $this->errors if errors are found
412
+						$result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
413 413
 						if ($result < 0)
414 414
 						{
415 415
 							$error++;
@@ -418,15 +418,15 @@  discard block
 block discarded – undo
418 418
 				}
419 419
 				else if ($reshook < 0) $error++;
420 420
 
421
-				if (! $error)
421
+				if (!$error)
422 422
 				{
423 423
                     // Call trigger
424
-                    $result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user);
424
+                    $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
425 425
                     if ($result < 0) $error++;
426 426
                     // End call triggers
427 427
 				}
428 428
 
429
-                if (! $error)
429
+                if (!$error)
430 430
                 {
431 431
                     $this->db->commit();
432 432
                     return $this->id;
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
             }
440 440
             else
441 441
             {
442
-                $this->error=$langs->trans('FailedToUpdatePrice');
442
+                $this->error = $langs->trans('FailedToUpdatePrice');
443 443
                 $this->db->rollback();
444 444
                 return -3;
445 445
             }
@@ -448,13 +448,13 @@  discard block
 block discarded – undo
448 448
         {
449 449
             if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
450 450
             {
451
-                $this->error=$langs->trans('ErrorRefAlreadyExists');
451
+                $this->error = $langs->trans('ErrorRefAlreadyExists');
452 452
                 $this->db->rollback();
453 453
                 return -1;
454 454
             }
455 455
             else
456 456
             {
457
-                $this->error=$this->db->lasterror();
457
+                $this->error = $this->db->lasterror();
458 458
                 $this->db->rollback();
459 459
                 return -2;
460 460
             }
@@ -468,88 +468,88 @@  discard block
 block discarded – undo
468 468
      *    @param	string	$ref		Ref supplier invoice
469 469
      *    @return   int        			<0 if KO, >0 if OK, 0 if not found
470 470
      */
471
-    public function fetch($id='',$ref='')
471
+    public function fetch($id = '', $ref = '')
472 472
     {
473 473
         global $langs;
474 474
 
475 475
         $sql = "SELECT";
476
-        $sql.= " t.rowid,";
477
-		$sql.= " t.ref,";
478
-        $sql.= " t.ref_supplier,";
479
-        $sql.= " t.entity,";
480
-        $sql.= " t.type,";
481
-        $sql.= " t.fk_soc,";
482
-        $sql.= " t.datec,";
483
-        $sql.= " t.datef,";
484
-        $sql.= " t.tms,";
485
-        $sql.= " t.libelle,";
486
-        $sql.= " t.paye,";
487
-        $sql.= " t.amount,";
488
-        $sql.= " t.remise,";
489
-        $sql.= " t.close_code,";
490
-        $sql.= " t.close_note,";
491
-        $sql.= " t.tva,";
492
-        $sql.= " t.localtax1,";
493
-        $sql.= " t.localtax2,";
476
+        $sql .= " t.rowid,";
477
+		$sql .= " t.ref,";
478
+        $sql .= " t.ref_supplier,";
479
+        $sql .= " t.entity,";
480
+        $sql .= " t.type,";
481
+        $sql .= " t.fk_soc,";
482
+        $sql .= " t.datec,";
483
+        $sql .= " t.datef,";
484
+        $sql .= " t.tms,";
485
+        $sql .= " t.libelle,";
486
+        $sql .= " t.paye,";
487
+        $sql .= " t.amount,";
488
+        $sql .= " t.remise,";
489
+        $sql .= " t.close_code,";
490
+        $sql .= " t.close_note,";
491
+        $sql .= " t.tva,";
492
+        $sql .= " t.localtax1,";
493
+        $sql .= " t.localtax2,";
494 494
         //$sql.= " t.total,";
495
-        $sql.= " t.total_ht,";
496
-        $sql.= " t.total_tva,";
497
-        $sql.= " t.total_ttc,";
498
-        $sql.= " t.fk_statut,";
499
-        $sql.= " t.fk_user_author,";
500
-        $sql.= " t.fk_user_valid,";
501
-        $sql.= " t.fk_facture_source,";
502
-        $sql.= " t.fk_projet,";
503
-        $sql.= " t.fk_cond_reglement,";
504
-        $sql.= " t.fk_account,";
505
-        $sql.= " t.fk_mode_reglement,";
506
-        $sql.= " t.date_lim_reglement,";
507
-        $sql.= " t.note_private,";
508
-        $sql.= " t.note_public,";
509
-        $sql.= " t.model_pdf,";
510
-        $sql.= " t.import_key,";
511
-        $sql.= " t.extraparams,";
512
-        $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
513
-        $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
514
-        $sql.= ' s.nom as socnom, s.rowid as socid,';
515
-        $sql.= ' t.fk_incoterms, t.location_incoterms,';
516
-        $sql.= " i.libelle as libelle_incoterms,";
517
-        $sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
518
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
519
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
520
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
521
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
522
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
523
-        if ($id)  $sql.= " WHERE t.rowid=".$id;
524
-        if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
495
+        $sql .= " t.total_ht,";
496
+        $sql .= " t.total_tva,";
497
+        $sql .= " t.total_ttc,";
498
+        $sql .= " t.fk_statut,";
499
+        $sql .= " t.fk_user_author,";
500
+        $sql .= " t.fk_user_valid,";
501
+        $sql .= " t.fk_facture_source,";
502
+        $sql .= " t.fk_projet,";
503
+        $sql .= " t.fk_cond_reglement,";
504
+        $sql .= " t.fk_account,";
505
+        $sql .= " t.fk_mode_reglement,";
506
+        $sql .= " t.date_lim_reglement,";
507
+        $sql .= " t.note_private,";
508
+        $sql .= " t.note_public,";
509
+        $sql .= " t.model_pdf,";
510
+        $sql .= " t.import_key,";
511
+        $sql .= " t.extraparams,";
512
+        $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
513
+        $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
514
+        $sql .= ' s.nom as socnom, s.rowid as socid,';
515
+        $sql .= ' t.fk_incoterms, t.location_incoterms,';
516
+        $sql .= " i.libelle as libelle_incoterms,";
517
+        $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
518
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
519
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
520
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = ".getEntity('c_payment_term').")";
521
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = ".getEntity('c_paiement').")";
522
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
523
+        if ($id)  $sql .= " WHERE t.rowid=".$id;
524
+        if ($ref) $sql .= " WHERE t.ref='".$this->db->escape($ref)."'";
525 525
 
526 526
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
527
-        $resql=$this->db->query($sql);
527
+        $resql = $this->db->query($sql);
528 528
         if ($resql)
529 529
         {
530 530
             if ($this->db->num_rows($resql))
531 531
             {
532 532
                 $obj = $this->db->fetch_object($resql);
533 533
 
534
-                $this->id					= $obj->rowid;
535
-                $this->ref					= $obj->ref?$obj->ref:$obj->rowid;	// We take rowid if ref is empty for backward compatibility
534
+                $this->id = $obj->rowid;
535
+                $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
536 536
 
537
-                $this->ref_supplier			= $obj->ref_supplier;
537
+                $this->ref_supplier = $obj->ref_supplier;
538 538
                 $this->entity				= $obj->entity;
539
-                $this->type					= empty($obj->type)? self::TYPE_STANDARD:$obj->type;
539
+                $this->type					= empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
540 540
                 $this->fk_soc				= $obj->fk_soc;
541 541
                 $this->datec				= $this->db->jdate($obj->datec);
542 542
                 $this->date					= $this->db->jdate($obj->datef);
543 543
                 $this->datep				= $this->db->jdate($obj->datef);
544
-                $this->tms					= $this->db->jdate($obj->tms);
545
-                $this->libelle				= $obj->libelle;
544
+                $this->tms = $this->db->jdate($obj->tms);
545
+                $this->libelle = $obj->libelle;
546 546
                 $this->label				= $obj->libelle;
547 547
                 $this->paye					= $obj->paye;
548 548
                 $this->amount				= $obj->amount;
549 549
                 $this->remise				= $obj->remise;
550 550
                 $this->close_code			= $obj->close_code;
551 551
                 $this->close_note			= $obj->close_note;
552
-                $this->tva					= $obj->tva;
552
+                $this->tva = $obj->tva;
553 553
                 $this->total_localtax1		= $obj->localtax1;
554 554
                 $this->total_localtax2		= $obj->localtax2;
555 555
                 //$this->total				= $obj->total;
@@ -558,26 +558,26 @@  discard block
 block discarded – undo
558 558
                 $this->total_ttc			= $obj->total_ttc;
559 559
                 $this->fk_statut			= $obj->fk_statut;
560 560
                 $this->statut				= $obj->fk_statut;
561
-                $this->fk_user_author		= $obj->fk_user_author;
561
+                $this->fk_user_author = $obj->fk_user_author;
562 562
                 $this->author				= $obj->fk_user_author;
563 563
                 $this->fk_user_valid		= $obj->fk_user_valid;
564
-                $this->fk_facture_source	= $obj->fk_facture_source;
564
+                $this->fk_facture_source = $obj->fk_facture_source;
565 565
                 $this->fk_project			= $obj->fk_projet;
566 566
 	            $this->cond_reglement_id	= $obj->fk_cond_reglement;
567
-	            $this->cond_reglement_code	= $obj->cond_reglement_code;
567
+	            $this->cond_reglement_code = $obj->cond_reglement_code;
568 568
 	            $this->cond_reglement		= $obj->cond_reglement_libelle;
569
-	            $this->cond_reglement_doc	= $obj->cond_reglement_libelle;
570
-                $this->fk_account           = $obj->fk_account;
569
+	            $this->cond_reglement_doc = $obj->cond_reglement_libelle;
570
+                $this->fk_account = $obj->fk_account;
571 571
 	            $this->mode_reglement_id	= $obj->fk_mode_reglement;
572
-	            $this->mode_reglement_code	= $obj->mode_reglement_code;
573
-	            $this->mode_reglement		= $obj->mode_reglement_libelle;
572
+	            $this->mode_reglement_code = $obj->mode_reglement_code;
573
+	            $this->mode_reglement = $obj->mode_reglement_libelle;
574 574
                 $this->date_echeance		= $this->db->jdate($obj->date_lim_reglement);
575
-                $this->note					= $obj->note_private;	// deprecated
575
+                $this->note = $obj->note_private; // deprecated
576 576
                 $this->note_private			= $obj->note_private;
577
-                $this->note_public			= $obj->note_public;
578
-                $this->model_pdf			= $obj->model_pdf;
577
+                $this->note_public = $obj->note_public;
578
+                $this->model_pdf = $obj->model_pdf;
579 579
                 $this->modelpdf			    = $obj->model_pdf;
580
-                $this->import_key			= $obj->import_key;
580
+                $this->import_key = $obj->import_key;
581 581
 
582 582
 				//Incoterms
583 583
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -586,13 +586,13 @@  discard block
 block discarded – undo
586 586
 
587 587
 				// Multicurrency
588 588
 				$this->fk_multicurrency 		= $obj->fk_multicurrency;
589
-				$this->multicurrency_code 		= $obj->multicurrency_code;
589
+				$this->multicurrency_code = $obj->multicurrency_code;
590 590
 				$this->multicurrency_tx 		= $obj->multicurrency_tx;
591
-				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
591
+				$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
592 592
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
593 593
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
594 594
 
595
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
595
+                $this->extraparams = (array) json_decode($obj->extraparams, true);
596 596
 
597 597
                 $this->socid  = $obj->socid;
598 598
                 $this->socnom = $obj->socnom;
@@ -600,23 +600,23 @@  discard block
 block discarded – undo
600 600
                 // Retreive all extrafield
601 601
                 // fetch optionals attributes and labels
602 602
                 require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
603
-                $extrafields=new ExtraFields($this->db);
604
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
605
-                $this->fetch_optionals($this->id,$extralabels);
603
+                $extrafields = new ExtraFields($this->db);
604
+                $extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true);
605
+                $this->fetch_optionals($this->id, $extralabels);
606 606
 
607 607
                 if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
608 608
 
609
-                $result=$this->fetch_lines();
609
+                $result = $this->fetch_lines();
610 610
                 if ($result < 0)
611 611
                 {
612
-                    $this->error=$this->db->lasterror();
612
+                    $this->error = $this->db->lasterror();
613 613
                     return -3;
614 614
                 }
615 615
 
616 616
             }
617 617
             else
618 618
             {
619
-                $this->error='Bill with id '.$id.' not found';
619
+                $this->error = 'Bill with id '.$id.' not found';
620 620
                 dol_syslog(get_class($this).'::fetch '.$this->error);
621 621
                 return 0;
622 622
             }
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
         }
627 627
         else
628 628
         {
629
-            $this->error="Error ".$this->db->lasterror();
629
+            $this->error = "Error ".$this->db->lasterror();
630 630
             return -1;
631 631
         }
632 632
     }
@@ -640,14 +640,14 @@  discard block
 block discarded – undo
640 640
     function fetch_lines()
641 641
     {
642 642
         $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
643
-        $sql.= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
644
-        $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
645
-        $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
646
-		$sql.= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
647
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
648
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
649
-        $sql.= ' WHERE fk_facture_fourn='.$this->id;
650
-        $sql.= ' ORDER BY f.rang, f.rowid';
643
+        $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
644
+        $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
645
+        $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
646
+		$sql .= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
647
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
648
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
649
+        $sql .= ' WHERE fk_facture_fourn='.$this->id;
650
+        $sql .= ' ORDER BY f.rang, f.rowid';
651 651
 
652 652
 
653 653
         dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
@@ -664,46 +664,46 @@  discard block
 block discarded – undo
664 664
 
665 665
 	                $line = new SupplierInvoiceLine($this->db);
666 666
 
667
-                    $line->id				= $obj->rowid;
668
-                    $line->rowid			= $obj->rowid;
667
+                    $line->id = $obj->rowid;
668
+                    $line->rowid = $obj->rowid;
669 669
                     $line->description		= $obj->description;
670 670
                     $line->product_ref		= $obj->product_ref;
671
-                    $line->ref				= $obj->product_ref;
671
+                    $line->ref = $obj->product_ref;
672 672
                     $line->ref_supplier		= $obj->ref_supplier;
673 673
                     $line->libelle			= $obj->label;
674 674
                     $line->label  			= $obj->label;
675 675
                     $line->product_desc		= $obj->product_desc;
676
-                    $line->subprice			= $obj->pu_ht;
677
-                    $line->pu_ht			= $obj->pu_ht;
676
+                    $line->subprice = $obj->pu_ht;
677
+                    $line->pu_ht = $obj->pu_ht;
678 678
                     $line->pu_ttc			= $obj->pu_ttc;
679 679
 
680
-                    $line->vat_src_code     = $obj->vat_src_code;
680
+                    $line->vat_src_code = $obj->vat_src_code;
681 681
                     $line->tva_tx			= $obj->tva_tx;
682 682
                     $line->localtax1_tx		= $obj->localtax1_tx;
683 683
                     $line->localtax2_tx		= $obj->localtax2_tx;
684 684
                     $line->localtax1_type	= $obj->localtax1_type;
685 685
                     $line->localtax2_type	= $obj->localtax2_type;
686 686
                     $line->qty				= $obj->qty;
687
-                    $line->remise_percent   = $obj->remise_percent;
687
+                    $line->remise_percent = $obj->remise_percent;
688 688
                     $line->tva				= $obj->total_tva;
689 689
                     $line->total_ht			= $obj->total_ht;
690 690
                     $line->total_tva		= $obj->total_tva;
691 691
                     $line->total_localtax1	= $obj->total_localtax1;
692 692
                     $line->total_localtax2	= $obj->total_localtax2;
693
-                    $line->fk_facture_fourn     = $obj->fk_facture_fourn;
694
-                    $line->total_ttc		= $obj->total_ttc;
695
-                    $line->fk_product		= $obj->fk_product;
693
+                    $line->fk_facture_fourn = $obj->fk_facture_fourn;
694
+                    $line->total_ttc = $obj->total_ttc;
695
+                    $line->fk_product = $obj->fk_product;
696 696
                     $line->product_type		= $obj->product_type;
697 697
                     $line->product_label	= $obj->label;
698
-                    $line->info_bits		= $obj->info_bits;
698
+                    $line->info_bits = $obj->info_bits;
699 699
                     $line->fk_parent_line   = $obj->fk_parent_line;
700 700
                     $line->special_code		= $obj->special_code;
701
-                    $line->rang       		= $obj->rang;
701
+                    $line->rang = $obj->rang;
702 702
                     $line->fk_unit          = $obj->fk_unit;
703 703
 
704 704
 					// Multicurrency
705
-					$line->fk_multicurrency 		= $obj->fk_multicurrency;
706
-					$line->multicurrency_code 		= $obj->multicurrency_code;
705
+					$line->fk_multicurrency = $obj->fk_multicurrency;
706
+					$line->multicurrency_code = $obj->multicurrency_code;
707 707
 					$line->multicurrency_subprice 	= $obj->multicurrency_subprice;
708 708
 					$line->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
709 709
 					$line->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
         }
720 720
         else
721 721
         {
722
-            $this->error=$this->db->error();
722
+            $this->error = $this->db->error();
723 723
             return -3;
724 724
         }
725 725
     }
@@ -732,42 +732,42 @@  discard block
 block discarded – undo
732 732
      *  @param  int		$notrigger       0=launch triggers after, 1=disable triggers
733 733
      *  @return int 			         <0 if KO, >0 if OK
734 734
      */
735
-    public function update($user=null, $notrigger=0)
735
+    public function update($user = null, $notrigger = 0)
736 736
     {
737 737
         global $conf, $langs;
738
-        $error=0;
738
+        $error = 0;
739 739
 
740 740
         // Clean parameters
741
-        if (empty($this->type)) $this->type= self::TYPE_STANDARD;
742
-		if (isset($this->ref)) $this->ref=trim($this->ref);
743
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
744
-        if (isset($this->entity)) $this->entity=trim($this->entity);
745
-        if (isset($this->type)) $this->type=trim($this->type);
746
-        if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
747
-        if (isset($this->libelle)) $this->libelle=trim($this->libelle);
748
-        if (isset($this->paye)) $this->paye=trim($this->paye);
749
-        if (isset($this->amount)) $this->amount=trim($this->amount);
750
-        if (isset($this->remise)) $this->remise=trim($this->remise);
751
-        if (isset($this->close_code)) $this->close_code=trim($this->close_code);
752
-        if (isset($this->close_note)) $this->close_note=trim($this->close_note);
753
-        if (isset($this->tva)) $this->tva=trim($this->tva);
754
-        if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1);
755
-        if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2);
756
-        if (empty($this->total_ht)) $this->total_ht=0;
757
-        if (empty($this->total_tva)) $this->total_tva=0;
741
+        if (empty($this->type)) $this->type = self::TYPE_STANDARD;
742
+		if (isset($this->ref)) $this->ref = trim($this->ref);
743
+        if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier);
744
+        if (isset($this->entity)) $this->entity = trim($this->entity);
745
+        if (isset($this->type)) $this->type = trim($this->type);
746
+        if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc);
747
+        if (isset($this->libelle)) $this->libelle = trim($this->libelle);
748
+        if (isset($this->paye)) $this->paye = trim($this->paye);
749
+        if (isset($this->amount)) $this->amount = trim($this->amount);
750
+        if (isset($this->remise)) $this->remise = trim($this->remise);
751
+        if (isset($this->close_code)) $this->close_code = trim($this->close_code);
752
+        if (isset($this->close_note)) $this->close_note = trim($this->close_note);
753
+        if (isset($this->tva)) $this->tva = trim($this->tva);
754
+        if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1);
755
+        if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2);
756
+        if (empty($this->total_ht)) $this->total_ht = 0;
757
+        if (empty($this->total_tva)) $this->total_tva = 0;
758 758
         //	if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
759 759
         //	if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
760
-        if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
761
-        if (isset($this->statut)) $this->statut=(int) $this->statut;
762
-        if (isset($this->author)) $this->author=trim($this->author);
763
-        if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
764
-        if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
765
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
766
-        if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
767
-        if (isset($this->note_private)) $this->note=trim($this->note_private);
768
-        if (isset($this->note_public)) $this->note_public=trim($this->note_public);
769
-        if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
770
-        if (isset($this->import_key)) $this->import_key=trim($this->import_key);
760
+        if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc);
761
+        if (isset($this->statut)) $this->statut = (int) $this->statut;
762
+        if (isset($this->author)) $this->author = trim($this->author);
763
+        if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid);
764
+        if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source);
765
+        if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project);
766
+        if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id);
767
+        if (isset($this->note_private)) $this->note = trim($this->note_private);
768
+        if (isset($this->note_public)) $this->note_public = trim($this->note_public);
769
+        if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
770
+        if (isset($this->import_key)) $this->import_key = trim($this->import_key);
771 771
 
772 772
 
773 773
         // Check parameters
@@ -775,39 +775,39 @@  discard block
 block discarded – undo
775 775
 
776 776
         // Update request
777 777
         $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
778
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
779
-        $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
780
-        $sql.= " entity=".(isset($this->entity)?$this->entity:"null").",";
781
-        $sql.= " type=".(isset($this->type)?$this->type:"null").",";
782
-        $sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").",";
783
-        $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
784
-        $sql.= " datef=".(dol_strlen($this->date)!=0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
785
-        if (dol_strlen($this->tms) != 0) $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
786
-        $sql.= " libelle=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
787
-        $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
788
-        $sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
789
-        $sql.= " remise=".(isset($this->remise)?$this->remise:"null").",";
790
-        $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
791
-        $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
792
-        $sql.= " tva=".(isset($this->tva)?$this->tva:"null").",";
793
-        $sql.= " localtax1=".(isset($this->localtax1)?$this->localtax1:"null").",";
794
-        $sql.= " localtax2=".(isset($this->localtax2)?$this->localtax2:"null").",";
778
+		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
779
+        $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
780
+        $sql .= " entity=".(isset($this->entity) ? $this->entity : "null").",";
781
+        $sql .= " type=".(isset($this->type) ? $this->type : "null").",";
782
+        $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").",";
783
+        $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
784
+        $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
785
+        if (dol_strlen($this->tms) != 0) $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
786
+        $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
787
+        $sql .= " paye=".(isset($this->paye) ? $this->paye : "null").",";
788
+        $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").",";
789
+        $sql .= " remise=".(isset($this->remise) ? $this->remise : "null").",";
790
+        $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
791
+        $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
792
+        $sql .= " tva=".(isset($this->tva) ? $this->tva : "null").",";
793
+        $sql .= " localtax1=".(isset($this->localtax1) ? $this->localtax1 : "null").",";
794
+        $sql .= " localtax2=".(isset($this->localtax2) ? $this->localtax2 : "null").",";
795 795
         //$sql.= " total=".(isset($this->total)?$this->total:"null").",";
796
-        $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
797
-        $sql.= " total_tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
798
-        $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
799
-        $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
800
-        $sql.= " fk_user_author=".(isset($this->author)?$this->author:"null").",";
801
-        $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
802
-        $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
803
-        $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
804
-        $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
805
-        $sql.= " date_lim_reglement=".(dol_strlen($this->date_echeance)!=0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
806
-        $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
807
-        $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
808
-        $sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
809
-        $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
810
-        $sql.= " WHERE rowid=".$this->id;
796
+        $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
797
+        $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
798
+        $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
799
+        $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
800
+        $sql .= " fk_user_author=".(isset($this->author) ? $this->author : "null").",";
801
+        $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
802
+        $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "null").",";
803
+        $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
804
+        $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
805
+        $sql .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
806
+        $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
807
+        $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
808
+        $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
809
+        $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
810
+        $sql .= " WHERE rowid=".$this->id;
811 811
 
812 812
         $this->db->begin();
813 813
 
@@ -824,12 +824,12 @@  discard block
 block discarded – undo
824 824
             }
825 825
         }
826 826
 
827
-        if (! $error)
827
+        if (!$error)
828 828
         {
829
-            if (! $notrigger)
829
+            if (!$notrigger)
830 830
             {
831 831
                 // Call trigger
832
-                $result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user);
832
+                $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user);
833 833
                 if ($result < 0) $error++;
834 834
                 // End call triggers
835 835
             }
@@ -838,13 +838,13 @@  discard block
 block discarded – undo
838 838
         // Commit or rollback
839 839
         if ($error)
840 840
         {
841
-            foreach($this->errors as $errmsg)
841
+            foreach ($this->errors as $errmsg)
842 842
             {
843 843
                 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
844
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
844
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
845 845
             }
846 846
             $this->db->rollback();
847
-            return -1*$error;
847
+            return -1 * $error;
848 848
         }
849 849
         else
850 850
         {
@@ -861,23 +861,23 @@  discard block
 block discarded – undo
861 861
      *	@param	    int		$notrigger	    1=Does not execute triggers, 0= execute triggers
862 862
      *	@return		int						<0 if KO, >0 if OK
863 863
      */
864
-    public function delete(User $user, $notrigger=0)
864
+    public function delete(User $user, $notrigger = 0)
865 865
     {
866
-        global $langs,$conf;
866
+        global $langs, $conf;
867 867
 
868
-        $rowid=$this->id;
868
+        $rowid = $this->id;
869 869
 
870 870
         dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
871 871
 
872 872
         // TODO Test if there is at least on payment. If yes, refuse to delete.
873 873
 
874
-        $error=0;
874
+        $error = 0;
875 875
         $this->db->begin();
876 876
 
877
-        if (! $error && ! $notrigger)
877
+        if (!$error && !$notrigger)
878 878
         {
879 879
             // Call trigger
880
-            $result=$this->call_trigger('BILL_SUPPLIER_DELETE',$user);
880
+            $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
881 881
             if ($result < 0)
882 882
             {
883 883
                 $this->db->rollback();
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
             // Fin appel triggers
887 887
         }
888 888
 
889
-        if (! $error)
889
+        if (!$error)
890 890
         {
891 891
             $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
892 892
             dol_syslog(get_class($this)."::delete", LOG_DEBUG);
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
                 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
897 897
                 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
898 898
                 $resql2 = $this->db->query($sql);
899
-                if (! $resql2) {
899
+                if (!$resql2) {
900 900
                 	$error++;
901 901
                 }
902 902
             }
@@ -905,21 +905,21 @@  discard block
 block discarded – undo
905 905
             }
906 906
         }
907 907
 
908
-		if (! $error)
908
+		if (!$error)
909 909
 		{
910 910
 			// Delete linked object
911 911
 			$res = $this->deleteObjectLinked();
912 912
 			if ($res < 0) $error++;
913 913
 		}
914 914
 
915
-        if (! $error)
915
+        if (!$error)
916 916
         {
917 917
         	// Delete linked object
918 918
         	$res = $this->deleteObjectLinked();
919 919
         	if ($res < 0) $error++;
920 920
         }
921 921
 
922
-        if (! $error)
922
+        if (!$error)
923 923
         {
924 924
         	// We remove directory
925 925
         	if ($conf->fournisseur->facture->dir_output)
@@ -928,22 +928,22 @@  discard block
 block discarded – undo
928 928
 
929 929
         		$ref = dol_sanitizeFileName($this->ref);
930 930
         		$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
931
-        		$file = $dir . "/" . $ref . ".pdf";
931
+        		$file = $dir."/".$ref.".pdf";
932 932
         		if (file_exists($file))
933 933
         		{
934
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
934
+        			if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
935 935
         			{
936
-        				$this->error='ErrorFailToDeleteFile';
936
+        				$this->error = 'ErrorFailToDeleteFile';
937 937
         				$error++;
938 938
         			}
939 939
         		}
940 940
         		if (file_exists($dir))
941 941
         		{
942
-        			$res=@dol_delete_dir_recursive($dir);
942
+        			$res = @dol_delete_dir_recursive($dir);
943 943
 
944
-        			if (! $res)
944
+        			if (!$res)
945 945
         			{
946
-        				$this->error='ErrorFailToDeleteDir';
946
+        				$this->error = 'ErrorFailToDeleteDir';
947 947
         				$error++;
948 948
         			}
949 949
         		}
@@ -951,9 +951,9 @@  discard block
 block discarded – undo
951 951
         }
952 952
 
953 953
         // Remove extrafields
954
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
954
+        if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
955 955
         {
956
-        	$result=$this->deleteExtraFields();
956
+        	$result = $this->deleteExtraFields();
957 957
         	if ($result < 0)
958 958
         	{
959 959
         		$error++;
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
         	}
962 962
         }
963 963
 
964
-        if (! $error)
964
+        if (!$error)
965 965
         {
966 966
         	dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
967 967
         	$this->db->commit();
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
         }
970 970
         else
971 971
         {
972
-        	$this->error=$this->db->lasterror();
972
+        	$this->error = $this->db->lasterror();
973 973
         	$this->db->rollback();
974 974
         	return -$error;
975 975
         }
@@ -984,34 +984,34 @@  discard block
 block discarded – undo
984 984
 	 *	@param  string	$close_note	Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet.
985 985
      *	@return int         		<0 si ko, >0 si ok
986 986
      */
987
-    function set_paid($user, $close_code='', $close_note='')
987
+    function set_paid($user, $close_code = '', $close_note = '')
988 988
     {
989
-        global $conf,$langs;
990
-        $error=0;
989
+        global $conf, $langs;
990
+        $error = 0;
991 991
 
992 992
         $this->db->begin();
993 993
 
994 994
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
995
-        $sql.= ' SET paye = 1, fk_statut=2';
996
-        $sql.= ' WHERE rowid = '.$this->id;
995
+        $sql .= ' SET paye = 1, fk_statut=2';
996
+        $sql .= ' WHERE rowid = '.$this->id;
997 997
 
998 998
         dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
999 999
         $resql = $this->db->query($sql);
1000 1000
         if ($resql)
1001 1001
         {
1002 1002
             // Call trigger
1003
-            $result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user);
1003
+            $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
1004 1004
             if ($result < 0) $error++;
1005 1005
             // End call triggers
1006 1006
         }
1007 1007
         else
1008 1008
         {
1009 1009
             $error++;
1010
-            $this->error=$this->db->error();
1010
+            $this->error = $this->db->error();
1011 1011
             dol_print_error($this->db);
1012 1012
         }
1013 1013
 
1014
-        if (! $error)
1014
+        if (!$error)
1015 1015
         {
1016 1016
             $this->db->commit();
1017 1017
             return 1;
@@ -1034,32 +1034,32 @@  discard block
 block discarded – undo
1034 1034
      */
1035 1035
     function set_unpaid($user)
1036 1036
     {
1037
-        global $conf,$langs;
1038
-        $error=0;
1037
+        global $conf, $langs;
1038
+        $error = 0;
1039 1039
 
1040 1040
         $this->db->begin();
1041 1041
 
1042 1042
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
1043
-        $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
1044
-        $sql.= ' WHERE rowid = '.$this->id;
1043
+        $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
1044
+        $sql .= ' WHERE rowid = '.$this->id;
1045 1045
 
1046 1046
         dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
1047 1047
         $resql = $this->db->query($sql);
1048 1048
         if ($resql)
1049 1049
         {
1050 1050
             // Call trigger
1051
-            $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user);
1051
+            $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
1052 1052
             if ($result < 0) $error++;
1053 1053
             // End call triggers
1054 1054
         }
1055 1055
         else
1056 1056
         {
1057 1057
             $error++;
1058
-            $this->error=$this->db->lasterror();
1058
+            $this->error = $this->db->lasterror();
1059 1059
             dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
1060 1060
         }
1061 1061
 
1062
-        if (! $error)
1062
+        if (!$error)
1063 1063
         {
1064 1064
             $this->db->commit();
1065 1065
             return 1;
@@ -1080,14 +1080,14 @@  discard block
 block discarded – undo
1080 1080
      *  @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1081 1081
      *	@return int 			        <0 if KO, =0 if nothing to do, >0 if OK
1082 1082
      */
1083
-    public function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
1083
+    public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1084 1084
     {
1085
-        global $conf,$langs;
1085
+        global $conf, $langs;
1086 1086
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1087 1087
 
1088
-        $now=dol_now();
1088
+        $now = dol_now();
1089 1089
 
1090
-        $error=0;
1090
+        $error = 0;
1091 1091
         dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
1092 1092
 
1093 1093
         // Force to have object complete for checks
@@ -1103,13 +1103,13 @@  discard block
 block discarded – undo
1103 1103
         if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
1104 1104
         {
1105 1105
         	$langs->load("errors");
1106
-        	$this->error=$langs->trans("ErrorFieldFormat",$langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString',$langs->transnoentitiesnoconv("CopyOf"));
1106
+        	$this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1107 1107
             return -1;
1108 1108
         }
1109 1109
         if (count($this->lines) <= 0)
1110 1110
         {
1111 1111
         	$langs->load("errors");
1112
-            $this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1112
+            $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1113 1113
             return -1;
1114 1114
         }
1115 1115
 
@@ -1131,20 +1131,20 @@  discard block
 block discarded – undo
1131 1131
         $this->newref = $num;
1132 1132
 
1133 1133
         $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1134
-        $sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
1135
-        $sql.= " WHERE rowid = ".$this->id;
1134
+        $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
1135
+        $sql .= " WHERE rowid = ".$this->id;
1136 1136
 
1137 1137
         dol_syslog(get_class($this)."::validate", LOG_DEBUG);
1138 1138
         $resql = $this->db->query($sql);
1139 1139
         if ($resql)
1140 1140
         {
1141 1141
             // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
1142
-            if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1142
+            if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1143 1143
             {
1144 1144
                 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1145 1145
                 $langs->load("agenda");
1146 1146
 
1147
-                $cpt=count($this->lines);
1147
+                $cpt = count($this->lines);
1148 1148
                 for ($i = 0; $i < $cpt; $i++)
1149 1149
                 {
1150 1150
                     if ($this->lines[$i]->fk_product > 0)
@@ -1153,9 +1153,9 @@  discard block
 block discarded – undo
1153 1153
                         $mouvP = new MouvementStock($this->db);
1154 1154
 						$mouvP->origin = &$this;
1155 1155
                         // We increase stock for product
1156
-                        $up_ht_disc=$this->lines[$i]->pu_ht;
1157
-                        if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1158
-                        $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr",$num));
1156
+                        $up_ht_disc = $this->lines[$i]->pu_ht;
1157
+                        if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1158
+                        $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
1159 1159
                         if ($result < 0) { $error++; }
1160 1160
                         unset($this->line);
1161 1161
                     }
@@ -1163,15 +1163,15 @@  discard block
 block discarded – undo
1163 1163
             }
1164 1164
 
1165 1165
             // Triggers call
1166
-            if (! $error && empty($notrigger))
1166
+            if (!$error && empty($notrigger))
1167 1167
             {
1168 1168
                 // Call trigger
1169
-                $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
1169
+                $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
1170 1170
                 if ($result < 0) $error++;
1171 1171
                 // End call triggers
1172 1172
             }
1173 1173
 
1174
-            if (! $error)
1174
+            if (!$error)
1175 1175
             {
1176 1176
 	            $this->oldref = $this->ref;
1177 1177
 
@@ -1183,8 +1183,8 @@  discard block
 block discarded – undo
1183 1183
             		$oldref = dol_sanitizeFileName($this->ref);
1184 1184
             		$newref = dol_sanitizeFileName($num);
1185 1185
 
1186
-            		$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$oldref;
1187
-            		$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref;
1186
+            		$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
1187
+            		$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref;
1188 1188
             		if (file_exists($dirsource))
1189 1189
             		{
1190 1190
             			dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
@@ -1193,13 +1193,13 @@  discard block
 block discarded – undo
1193 1193
             			{
1194 1194
             				dol_syslog("Rename ok");
1195 1195
                             // Rename docs starting with $oldref with $newref
1196
-	                        $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1197
-	                        foreach($listoffiles as $fileentry)
1196
+	                        $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1197
+	                        foreach ($listoffiles as $fileentry)
1198 1198
 	                        {
1199
-	                        	$dirsource=$fileentry['name'];
1200
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1201
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
1202
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
1199
+	                        	$dirsource = $fileentry['name'];
1200
+	                        	$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1201
+	                        	$dirsource = $fileentry['path'].'/'.$dirsource;
1202
+	                        	$dirdest = $fileentry['path'].'/'.$dirdest;
1203 1203
 	                        	@rename($dirsource, $dirdest);
1204 1204
 	                        }
1205 1205
             			}
@@ -1208,14 +1208,14 @@  discard block
 block discarded – undo
1208 1208
             }
1209 1209
 
1210 1210
             // Set new ref and define current statut
1211
-            if (! $error)
1211
+            if (!$error)
1212 1212
             {
1213 1213
             	$this->ref = $num;
1214
-            	$this->statut=self::STATUS_VALIDATED;
1214
+            	$this->statut = self::STATUS_VALIDATED;
1215 1215
             	//$this->date_validation=$now; this is stored into log table
1216 1216
             }
1217 1217
 
1218
-            if (! $error)
1218
+            if (!$error)
1219 1219
             {
1220 1220
                 $this->db->commit();
1221 1221
                 return 1;
@@ -1228,7 +1228,7 @@  discard block
 block discarded – undo
1228 1228
         }
1229 1229
         else
1230 1230
         {
1231
-            $this->error=$this->db->error();
1231
+            $this->error = $this->db->error();
1232 1232
             $this->db->rollback();
1233 1233
             return -1;
1234 1234
         }
@@ -1242,11 +1242,11 @@  discard block
 block discarded – undo
1242 1242
      *	@param	int		$idwarehouse	Id warehouse to use for stock change.
1243 1243
      *	@return	int						<0 if KO, >0 if OK
1244 1244
      */
1245
-    function set_draft($user, $idwarehouse=-1)
1245
+    function set_draft($user, $idwarehouse = -1)
1246 1246
     {
1247
-        global $conf,$langs;
1247
+        global $conf, $langs;
1248 1248
 
1249
-        $error=0;
1249
+        $error = 0;
1250 1250
 
1251 1251
         if ($this->statut == self::STATUS_DRAFT)
1252 1252
         {
@@ -1257,35 +1257,35 @@  discard block
 block discarded – undo
1257 1257
         $this->db->begin();
1258 1258
 
1259 1259
         $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1260
-        $sql.= " SET fk_statut = 0";
1261
-        $sql.= " WHERE rowid = ".$this->id;
1260
+        $sql .= " SET fk_statut = 0";
1261
+        $sql .= " WHERE rowid = ".$this->id;
1262 1262
 
1263 1263
         dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
1264
-        $result=$this->db->query($sql);
1264
+        $result = $this->db->query($sql);
1265 1265
         if ($result)
1266 1266
         {
1267 1267
             // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
1268
-            if ($result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1268
+            if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1269 1269
             {
1270 1270
                 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1271 1271
                 $langs->load("agenda");
1272 1272
 
1273
-                $cpt=count($this->lines);
1273
+                $cpt = count($this->lines);
1274 1274
                 for ($i = 0; $i < $cpt; $i++)
1275 1275
                 {
1276 1276
                     if ($this->lines[$i]->fk_product > 0)
1277 1277
                     {
1278 1278
                         $mouvP = new MouvementStock($this->db);
1279 1279
                         // We increase stock for product
1280
-                        $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
1280
+                        $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
1281 1281
                     }
1282 1282
                 }
1283 1283
             }
1284 1284
             // Triggers call
1285
-            if (! $error && empty($notrigger))
1285
+            if (!$error && empty($notrigger))
1286 1286
             {
1287 1287
                 // Call trigger
1288
-                $result=$this->call_trigger('BILL_SUPPLIER_UNVALIDATE',$user);
1288
+                $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
1289 1289
                 if ($result < 0) $error++;
1290 1290
                 // End call triggers
1291 1291
             }
@@ -1302,7 +1302,7 @@  discard block
 block discarded – undo
1302 1302
         }
1303 1303
         else
1304 1304
         {
1305
-            $this->error=$this->db->error();
1305
+            $this->error = $this->db->error();
1306 1306
             $this->db->rollback();
1307 1307
             return -1;
1308 1308
         }
@@ -1340,38 +1340,38 @@  discard block
 block discarded – undo
1340 1340
      *
1341 1341
      *  FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order.
1342 1342
      */
1343
-    public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false, $array_options=0, $fk_unit=null, $origin_id=0, $pu_ht_devise=0)
1343
+    public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_ht_devise = 0)
1344 1344
     {
1345 1345
         dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
1346 1346
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1347 1347
         global $mysoc;
1348 1348
 
1349 1349
         // Clean parameters
1350
-        if (empty($remise_percent)) $remise_percent=0;
1351
-        if (empty($qty)) $qty=0;
1352
-        if (empty($info_bits)) $info_bits=0;
1353
-        if (empty($rang)) $rang=0;
1354
-        if (empty($ventil)) $ventil=0;
1355
-        if (empty($txtva)) $txtva=0;
1356
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1357
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1350
+        if (empty($remise_percent)) $remise_percent = 0;
1351
+        if (empty($qty)) $qty = 0;
1352
+        if (empty($info_bits)) $info_bits = 0;
1353
+        if (empty($rang)) $rang = 0;
1354
+        if (empty($ventil)) $ventil = 0;
1355
+        if (empty($txtva)) $txtva = 0;
1356
+        if (empty($txlocaltax1)) $txlocaltax1 = 0;
1357
+        if (empty($txlocaltax2)) $txlocaltax2 = 0;
1358 1358
 
1359
-        $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1359
+        $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1360 1360
 
1361 1361
         // Clean vat code
1362
-        $vat_src_code='';
1362
+        $vat_src_code = '';
1363 1363
         if (preg_match('/\((.*)\)/', $txtva, $reg))
1364 1364
         {
1365 1365
             $vat_src_code = $reg[1];
1366
-            $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1366
+            $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1367 1367
         }
1368 1368
 
1369
-        $remise_percent=price2num($remise_percent);
1370
-        $qty=price2num($qty);
1371
-        $pu=price2num($pu);
1372
-        $txtva=price2num($txtva);
1373
-        $txlocaltax1=price2num($txlocaltax1);
1374
-        $txlocaltax2=price2num($txlocaltax2);
1369
+        $remise_percent = price2num($remise_percent);
1370
+        $qty = price2num($qty);
1371
+        $pu = price2num($pu);
1372
+        $txtva = price2num($txtva);
1373
+        $txlocaltax1 = price2num($txlocaltax1);
1374
+        $txlocaltax2 = price2num($txlocaltax2);
1375 1375
 
1376 1376
         $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1377 1377
         $total_ht  = $tabprice[0];
@@ -1391,61 +1391,61 @@  discard block
 block discarded – undo
1391 1391
         if ($type < 0) return -1;
1392 1392
 
1393 1393
         // Insert line
1394
-        $this->line=new SupplierInvoiceLine($this->db);
1394
+        $this->line = new SupplierInvoiceLine($this->db);
1395 1395
 
1396 1396
         $this->line->context = $this->context;
1397 1397
 
1398
-        $this->line->fk_facture_fourn=$this->id;
1398
+        $this->line->fk_facture_fourn = $this->id;
1399 1399
         //$this->line->label=$label;	// deprecated
1400
-        $this->line->desc=$desc;
1401
-        $this->line->qty=            ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	// For credit note, quantity is always positive and unit price negative
1402
-
1403
-        $this->line->vat_src_code=$vat_src_code;
1404
-        $this->line->tva_tx=$txtva;
1405
-        $this->line->localtax1_tx=$txlocaltax1;
1406
-        $this->line->localtax2_tx=$txlocaltax2;
1407
-        $this->line->fk_product=$fk_product;
1408
-        $this->line->product_type=$type;
1409
-        $this->line->remise_percent=$remise_percent;
1410
-        $this->line->subprice=       ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
1411
-        $this->line->date_start=$date_start;
1412
-        $this->line->date_end=$date_end;
1413
-        $this->line->ventil=$ventil;
1414
-        $this->line->rang=$rang;
1415
-        $this->line->info_bits=$info_bits;
1416
-        $this->line->total_ht=       (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht);  // For credit note and if qty is negative, total is negative
1417
-        $this->line->total_tva=      $total_tva;
1418
-        $this->line->total_localtax1=$total_localtax1;
1419
-        $this->line->total_localtax2=$total_localtax2;
1400
+        $this->line->desc = $desc;
1401
+        $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
1402
+
1403
+        $this->line->vat_src_code = $vat_src_code;
1404
+        $this->line->tva_tx = $txtva;
1405
+        $this->line->localtax1_tx = $txlocaltax1;
1406
+        $this->line->localtax2_tx = $txlocaltax2;
1407
+        $this->line->fk_product = $fk_product;
1408
+        $this->line->product_type = $type;
1409
+        $this->line->remise_percent = $remise_percent;
1410
+        $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
1411
+        $this->line->date_start = $date_start;
1412
+        $this->line->date_end = $date_end;
1413
+        $this->line->ventil = $ventil;
1414
+        $this->line->rang = $rang;
1415
+        $this->line->info_bits = $info_bits;
1416
+        $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
1417
+        $this->line->total_tva = $total_tva;
1418
+        $this->line->total_localtax1 = $total_localtax1;
1419
+        $this->line->total_localtax2 = $total_localtax2;
1420 1420
         $this->line->localtax1_type = $localtaxes_type[0];
1421 1421
         $this->line->localtax2_type = $localtaxes_type[2];
1422
-        $this->line->total_ttc=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);
1423
-        $this->line->special_code=$this->special_code;
1424
-        $this->line->fk_parent_line=$this->fk_parent_line;
1425
-        $this->line->origin=$this->origin;
1426
-        $this->line->origin_id=$origin_id;
1427
-        $this->line->fk_unit=$fk_unit;
1422
+        $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
1423
+        $this->line->special_code = $this->special_code;
1424
+        $this->line->fk_parent_line = $this->fk_parent_line;
1425
+        $this->line->origin = $this->origin;
1426
+        $this->line->origin_id = $origin_id;
1427
+        $this->line->fk_unit = $fk_unit;
1428 1428
 
1429 1429
         // Multicurrency
1430
-        $this->line->fk_multicurrency			= $this->fk_multicurrency;
1431
-        $this->line->multicurrency_code			= $this->multicurrency_code;
1430
+        $this->line->fk_multicurrency = $this->fk_multicurrency;
1431
+        $this->line->multicurrency_code = $this->multicurrency_code;
1432 1432
         $this->line->multicurrency_subprice		= $pu_ht_devise;
1433 1433
         $this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1434 1434
         $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1435 1435
         $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1436 1436
 
1437
-        if (is_array($array_options) && count($array_options)>0) {
1438
-            $this->line->array_options=$array_options;
1437
+        if (is_array($array_options) && count($array_options) > 0) {
1438
+            $this->line->array_options = $array_options;
1439 1439
         }
1440 1440
 
1441
-        $result=$this->line->insert($notrigger);
1441
+        $result = $this->line->insert($notrigger);
1442 1442
         if ($result > 0)
1443 1443
         {
1444 1444
             // Reorder if child line
1445
-            if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1445
+            if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
1446 1446
 
1447 1447
             // Mise a jour informations denormalisees au niveau de la facture meme
1448
-            $result=$this->update_price(1,'auto',0,$this->thirdparty);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
1448
+            $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
1449 1449
             if ($result > 0)
1450 1450
             {
1451 1451
                 $this->db->commit();
@@ -1453,14 +1453,14 @@  discard block
 block discarded – undo
1453 1453
             }
1454 1454
             else
1455 1455
             {
1456
-                $this->error=$this->db->error();
1456
+                $this->error = $this->db->error();
1457 1457
                 $this->db->rollback();
1458 1458
                 return -1;
1459 1459
             }
1460 1460
         }
1461 1461
         else
1462 1462
         {
1463
-            $this->error=$this->line->error;
1463
+            $this->error = $this->line->error;
1464 1464
             $this->db->rollback();
1465 1465
             return -2;
1466 1466
         }
@@ -1489,15 +1489,15 @@  discard block
 block discarded – undo
1489 1489
 	 * @param		double		$pu_ht_devise		Amount in currency
1490 1490
      * @return    	int           					<0 if KO, >0 if OK
1491 1491
      */
1492
-    public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit = null, $pu_ht_devise=0)
1492
+    public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1 = 0, $txlocaltax2 = 0, $qty = 1, $idproduct = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $remise_percent = 0, $notrigger = false, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0)
1493 1493
     {
1494 1494
     	global $mysoc;
1495 1495
         dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$fk_unit", LOG_DEBUG);
1496 1496
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1497 1497
 
1498 1498
         $pu = price2num($pu);
1499
-        $qty  = price2num($qty);
1500
-		$remise_percent=price2num($remise_percent);
1499
+        $qty = price2num($qty);
1500
+		$remise_percent = price2num($remise_percent);
1501 1501
 		$pu_ht_devise = price2num($pu_ht_devise);
1502 1502
 
1503 1503
         // Check parameters
@@ -1505,28 +1505,28 @@  discard block
 block discarded – undo
1505 1505
         if ($type < 0) return -1;
1506 1506
 
1507 1507
         // Clean parameters
1508
-		if (empty($vatrate)) $vatrate=0;
1509
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1510
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1508
+		if (empty($vatrate)) $vatrate = 0;
1509
+        if (empty($txlocaltax1)) $txlocaltax1 = 0;
1510
+        if (empty($txlocaltax2)) $txlocaltax2 = 0;
1511 1511
 
1512
-        $txlocaltax1=price2num($txlocaltax1);
1513
-        $txlocaltax2=price2num($txlocaltax2);
1512
+        $txlocaltax1 = price2num($txlocaltax1);
1513
+        $txlocaltax2 = price2num($txlocaltax2);
1514 1514
 
1515
-        $localtaxes_type = array($txlocaltax1,$txlocaltax2);
1515
+        $localtaxes_type = array($txlocaltax1, $txlocaltax2);
1516 1516
 
1517 1517
         // Calcul du total TTC et de la TVA pour la ligne a partir de
1518 1518
         // qty, pu, remise_percent et txtva
1519 1519
         // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1520 1520
         // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1521 1521
 
1522
-        $localtaxes_type=getLocalTaxesFromRate($vatrate,0,$mysoc, $this->thirdparty);
1522
+        $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
1523 1523
 
1524 1524
         // Clean vat code
1525
-        $vat_src_code='';
1525
+        $vat_src_code = '';
1526 1526
         if (preg_match('/\((.*)\)/', $vatrate, $reg))
1527 1527
         {
1528 1528
             $vat_src_code = $reg[1];
1529
-            $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate);    // Remove code into vatrate.
1529
+            $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
1530 1530
         }
1531 1531
 
1532 1532
         $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
@@ -1540,17 +1540,17 @@  discard block
 block discarded – undo
1540 1540
         $total_localtax2 = $tabprice[10];
1541 1541
 
1542 1542
 		// MultiCurrency
1543
-		$multicurrency_total_ht  = $tabprice[16];
1543
+		$multicurrency_total_ht = $tabprice[16];
1544 1544
         $multicurrency_total_tva = $tabprice[17];
1545 1545
         $multicurrency_total_ttc = $tabprice[18];
1546 1546
 		$pu_ht_devise = $tabprice[19];
1547 1547
 
1548
-        if (empty($info_bits)) $info_bits=0;
1548
+        if (empty($info_bits)) $info_bits = 0;
1549 1549
 
1550 1550
         if ($idproduct)
1551 1551
         {
1552
-            $product=new Product($this->db);
1553
-            $result=$product->fetch($idproduct);
1552
+            $product = new Product($this->db);
1553
+            $result = $product->fetch($idproduct);
1554 1554
             $product_type = $product->type;
1555 1555
         }
1556 1556
         else
@@ -1571,7 +1571,7 @@  discard block
 block discarded – undo
1571 1571
 	    $line->qty = $qty;
1572 1572
 	    $line->remise_percent = $remise_percent;
1573 1573
 
1574
-	    $line->vat_src_code=$vat_src_code;
1574
+	    $line->vat_src_code = $vat_src_code;
1575 1575
 	    $line->tva_tx = $vatrate;
1576 1576
 	    $line->localtax1_tx = $txlocaltax1;
1577 1577
 	    $line->localtax2_tx = $txlocaltax2;
@@ -1589,8 +1589,8 @@  discard block
 block discarded – undo
1589 1589
 	    $line->array_options = $array_options;
1590 1590
 
1591 1591
 		// Multicurrency
1592
-		$line->multicurrency_subprice	= $pu_ht_devise;
1593
-		$line->multicurrency_total_ht 	= $multicurrency_total_ht;
1592
+		$line->multicurrency_subprice = $pu_ht_devise;
1593
+		$line->multicurrency_total_ht = $multicurrency_total_ht;
1594 1594
         $line->multicurrency_total_tva 	= $multicurrency_total_tva;
1595 1595
         $line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1596 1596
 
@@ -1600,7 +1600,7 @@  discard block
 block discarded – undo
1600 1600
 		    $this->errors[] = $line->error;
1601 1601
 	    } else {
1602 1602
 		    // Update total price into invoice record
1603
-		    $res = $this->update_price('','auto');
1603
+		    $res = $this->update_price('', 'auto');
1604 1604
 	    }
1605 1605
 
1606 1606
 	    return $res;
@@ -1613,7 +1613,7 @@  discard block
 block discarded – undo
1613 1613
      *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1614 1614
      * 	@return	int						<0 if KO, >0 if OK
1615 1615
      */
1616
-    public function deleteline($rowid, $notrigger=0)
1616
+    public function deleteline($rowid, $notrigger = 0)
1617 1617
     {
1618 1618
         if (!$rowid) {
1619 1619
 	        $rowid = $this->id;
@@ -1646,11 +1646,11 @@  discard block
 block discarded – undo
1646 1646
     public function info($id)
1647 1647
     {
1648 1648
         $sql = 'SELECT c.rowid, datec, tms as datem, ';
1649
-        $sql.= ' fk_user_author, fk_user_modif, fk_user_valid';
1650
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
1651
-        $sql.= ' WHERE c.rowid = '.$id;
1649
+        $sql .= ' fk_user_author, fk_user_modif, fk_user_valid';
1650
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
1651
+        $sql .= ' WHERE c.rowid = '.$id;
1652 1652
 
1653
-        $result=$this->db->query($sql);
1653
+        $result = $this->db->query($sql);
1654 1654
         if ($result)
1655 1655
         {
1656 1656
             if ($this->db->num_rows($result))
@@ -1661,7 +1661,7 @@  discard block
 block discarded – undo
1661 1661
                 {
1662 1662
                     $cuser = new User($this->db);
1663 1663
                     $cuser->fetch($obj->fk_user_author);
1664
-                    $this->user_creation     = $cuser;
1664
+                    $this->user_creation = $cuser;
1665 1665
                 }
1666 1666
                 if ($obj->fk_user_valid)
1667 1667
                 {
@@ -1694,32 +1694,32 @@  discard block
 block discarded – undo
1694 1694
 	 *	@param		int		$socid		Id societe
1695 1695
 	 *	@return    	array				Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
1696 1696
 	 */
1697
-	function list_replacable_supplier_invoices($socid=0)
1697
+	function list_replacable_supplier_invoices($socid = 0)
1698 1698
 	{
1699 1699
 		global $conf;
1700 1700
 
1701 1701
 		$return = array();
1702 1702
 
1703 1703
 		$sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,";
1704
-		$sql.= " ff.rowid as rowidnext";
1705
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
1706
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
1707
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source";
1708
-		$sql.= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
1709
-		$sql.= " AND f.entity = ".$conf->entity;
1710
-		$sql.= " AND f.paye = 0";					// Pas classee payee completement
1711
-		$sql.= " AND pf.fk_paiementfourn IS NULL";	// Aucun paiement deja fait
1712
-		$sql.= " AND ff.fk_statut IS NULL";			// Renvoi vrai si pas facture de remplacement
1713
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
1714
-		$sql.= " ORDER BY f.ref";
1704
+		$sql .= " ff.rowid as rowidnext";
1705
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
1706
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
1707
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source";
1708
+		$sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
1709
+		$sql .= " AND f.entity = ".$conf->entity;
1710
+		$sql .= " AND f.paye = 0"; // Pas classee payee completement
1711
+		$sql .= " AND pf.fk_paiementfourn IS NULL"; // Aucun paiement deja fait
1712
+		$sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
1713
+		if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
1714
+		$sql .= " ORDER BY f.ref";
1715 1715
 
1716 1716
 		dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG);
1717
-		$resql=$this->db->query($sql);
1717
+		$resql = $this->db->query($sql);
1718 1718
 		if ($resql)
1719 1719
 		{
1720
-			while ($obj=$this->db->fetch_object($resql))
1720
+			while ($obj = $this->db->fetch_object($resql))
1721 1721
 			{
1722
-				$return[$obj->rowid]=array(	'id' => $obj->rowid,
1722
+				$return[$obj->rowid] = array('id' => $obj->rowid,
1723 1723
 				'ref' => $obj->ref,
1724 1724
 				'status' => $obj->fk_statut);
1725 1725
 			}
@@ -1728,7 +1728,7 @@  discard block
 block discarded – undo
1728 1728
 		}
1729 1729
 		else
1730 1730
 		{
1731
-			$this->error=$this->db->error();
1731
+			$this->error = $this->db->error();
1732 1732
 			return -1;
1733 1733
 		}
1734 1734
 	}
@@ -1741,36 +1741,36 @@  discard block
 block discarded – undo
1741 1741
 	 *	@param		int		$socid		Id societe
1742 1742
 	 *	@return    	array				Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
1743 1743
 	 */
1744
-	function list_qualified_avoir_supplier_invoices($socid=0)
1744
+	function list_qualified_avoir_supplier_invoices($socid = 0)
1745 1745
 	{
1746 1746
 		global $conf;
1747 1747
 
1748 1748
 		$return = array();
1749 1749
 
1750 1750
 		$sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiementfourn";
1751
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
1752
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
1753
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
1754
-		$sql.= " WHERE f.entity = ".$conf->entity;
1755
-		$sql.= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
1756
-		$sql.= " AND ff.type IS NULL";									// Renvoi vrai si pas facture de remplacement
1757
-		$sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE;				// Type non 2 si facture non avoir
1758
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
1759
-		$sql.= " ORDER BY f.ref";
1751
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
1752
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
1753
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
1754
+		$sql .= " WHERE f.entity = ".$conf->entity;
1755
+		$sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
1756
+		$sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
1757
+		$sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
1758
+		if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
1759
+		$sql .= " ORDER BY f.ref";
1760 1760
 
1761 1761
 		dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG);
1762
-		$resql=$this->db->query($sql);
1762
+		$resql = $this->db->query($sql);
1763 1763
 		if ($resql)
1764 1764
 		{
1765
-			while ($obj=$this->db->fetch_object($resql))
1765
+			while ($obj = $this->db->fetch_object($resql))
1766 1766
 			{
1767
-				$qualified=0;
1768
-				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified=1;
1769
-				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified=1;
1767
+				$qualified = 0;
1768
+				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1;
1769
+				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1;
1770 1770
 				if ($qualified)
1771 1771
 				{
1772
-					$paymentornot=($obj->fk_paiementfourn?1:0);
1773
-					$return[$obj->rowid]=array('ref'=>$obj->ref,'status'=>$obj->fk_statut,'type'=>$obj->type,'paye'=>$obj->paye,'paymentornot'=>$paymentornot);
1772
+					$paymentornot = ($obj->fk_paiementfourn ? 1 : 0);
1773
+					$return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
1774 1774
 				}
1775 1775
 			}
1776 1776
 
@@ -1778,7 +1778,7 @@  discard block
 block discarded – undo
1778 1778
 		}
1779 1779
 		else
1780 1780
 		{
1781
-			$this->error=$this->db->error();
1781
+			$this->error = $this->db->error();
1782 1782
 			return -1;
1783 1783
 		}
1784 1784
 	}
@@ -1794,30 +1794,30 @@  discard block
 block discarded – undo
1794 1794
         global $conf, $langs;
1795 1795
 
1796 1796
         $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut';
1797
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
1798
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1799
-        $sql.= ' WHERE ff.paye=0';
1800
-        $sql.= ' AND ff.fk_statut > 0';
1801
-        $sql.= " AND ff.entity = ".$conf->entity;
1802
-        if ($user->societe_id) $sql.=' AND ff.fk_soc = '.$user->societe_id;
1803
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1804
-
1805
-        $resql=$this->db->query($sql);
1797
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
1798
+        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1799
+        $sql .= ' WHERE ff.paye=0';
1800
+        $sql .= ' AND ff.fk_statut > 0';
1801
+        $sql .= " AND ff.entity = ".$conf->entity;
1802
+        if ($user->societe_id) $sql .= ' AND ff.fk_soc = '.$user->societe_id;
1803
+        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1804
+
1805
+        $resql = $this->db->query($sql);
1806 1806
         if ($resql)
1807 1807
         {
1808 1808
 	        $langs->load("bills");
1809
-	        $now=dol_now();
1809
+	        $now = dol_now();
1810 1810
 
1811 1811
 	        $response = new WorkboardResponse();
1812
-	        $response->warning_delay=$conf->facture->fournisseur->warning_delay/60/60/24;
1813
-	        $response->label=$langs->trans("SupplierBillsToPay");
1812
+	        $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24;
1813
+	        $response->label = $langs->trans("SupplierBillsToPay");
1814 1814
 
1815
-	        $response->url=DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=suppliers_bills';
1816
-	        $response->img=img_object($langs->trans("Bills"),"bill");
1815
+	        $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=suppliers_bills';
1816
+	        $response->img = img_object($langs->trans("Bills"), "bill");
1817 1817
 
1818 1818
             $facturestatic = new FactureFournisseur($this->db);
1819 1819
 
1820
-            while ($obj=$this->db->fetch_object($resql))
1820
+            while ($obj = $this->db->fetch_object($resql))
1821 1821
             {
1822 1822
                 $response->nbtodo++;
1823 1823
 
@@ -1834,7 +1834,7 @@  discard block
 block discarded – undo
1834 1834
         else
1835 1835
         {
1836 1836
             dol_print_error($this->db);
1837
-            $this->error=$this->db->error();
1837
+            $this->error = $this->db->error();
1838 1838
             return -1;
1839 1839
         }
1840 1840
     }
@@ -1852,11 +1852,11 @@  discard block
 block discarded – undo
1852 1852
      *  @param      int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1853 1853
      * 	@return		string								String with URL
1854 1854
      */
1855
-    public function getNomUrl($withpicto=0, $option='',$max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1)
1855
+    public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1856 1856
     {
1857 1857
         global $langs, $conf;
1858 1858
 
1859
-        $result='';
1859
+        $result = '';
1860 1860
 
1861 1861
         if ($option == 'document')	$url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
1862 1862
         else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
@@ -1866,53 +1866,53 @@  discard block
 block discarded – undo
1866 1866
         if ($option !== 'nolink')
1867 1867
         {
1868 1868
         	// Add param to save lastsearch_values or not
1869
-        	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1870
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1871
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1872
-        }
1873
-
1874
-        $picto='bill';
1875
-        if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice
1876
-        if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note
1877
-        if ($this->type == self::TYPE_DEPOSIT)     $picto.='d'; // Deposit invoice
1878
-
1879
-        $label = '<u>' . $langs->trans("ShowSupplierInvoice") . '</u>';
1880
-        if (! empty($this->ref))
1881
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1882
-        if (! empty($this->ref_supplier))
1883
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
1884
-        if (! empty($this->total_ht))
1885
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1886
-        if (! empty($this->total_tva))
1887
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1888
-        if (! empty($this->total_ttc))
1889
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1890
-        if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1891
-        if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1892
-        if ($this->type == self::TYPE_DEPOSIT)     $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1893
-        if ($moretitle) $label.=' - '.$moretitle;
1894
-
1895
-        $ref=$this->ref;
1896
-        if (empty($ref)) $ref=$this->id;
1897
-
1898
-        $linkclose='';
1869
+        	$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1870
+        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1871
+        	if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1872
+        }
1873
+
1874
+        $picto = 'bill';
1875
+        if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice
1876
+        if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note
1877
+        if ($this->type == self::TYPE_DEPOSIT)     $picto .= 'd'; // Deposit invoice
1878
+
1879
+        $label = '<u>'.$langs->trans("ShowSupplierInvoice").'</u>';
1880
+        if (!empty($this->ref))
1881
+            $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1882
+        if (!empty($this->ref_supplier))
1883
+            $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
1884
+        if (!empty($this->total_ht))
1885
+            $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1886
+        if (!empty($this->total_tva))
1887
+            $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1888
+        if (!empty($this->total_ttc))
1889
+            $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1890
+        if ($this->type == self::TYPE_REPLACEMENT) $label = $langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1891
+        if ($this->type == self::TYPE_CREDIT_NOTE) $label = $langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1892
+        if ($this->type == self::TYPE_DEPOSIT)     $label = $langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1893
+        if ($moretitle) $label .= ' - '.$moretitle;
1894
+
1895
+        $ref = $this->ref;
1896
+        if (empty($ref)) $ref = $this->id;
1897
+
1898
+        $linkclose = '';
1899 1899
         if (empty($notooltip))
1900 1900
         {
1901
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1901
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1902 1902
             {
1903
-                $label=$langs->trans("ShowSupplierInvoice");
1904
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1903
+                $label = $langs->trans("ShowSupplierInvoice");
1904
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1905 1905
             }
1906
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1907
-            $linkclose.=' class="classfortooltip"';
1906
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1907
+            $linkclose .= ' class="classfortooltip"';
1908 1908
         }
1909 1909
 
1910 1910
         $linkstart = '<a href="'.$url.'"';
1911
-        $linkstart.=$linkclose.'>';
1912
-        $linkend='</a>';
1911
+        $linkstart .= $linkclose.'>';
1912
+        $linkend = '</a>';
1913 1913
 
1914
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
1915
-        $result.=$linkstart.($max?dol_trunc($ref,$max):$ref).$linkend;
1914
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend.' ');
1915
+        $result .= $linkstart.($max ?dol_trunc($ref, $max) : $ref).$linkend;
1916 1916
         return $result;
1917 1917
     }
1918 1918
 
@@ -1924,15 +1924,15 @@  discard block
 block discarded – undo
1924 1924
       *      @param    string		$mode		'next' for next value or 'last' for last value
1925 1925
       *      @return   string					free ref or last ref
1926 1926
       */
1927
-    public function getNextNumRef($soc,$mode='next')
1927
+    public function getNextNumRef($soc, $mode = 'next')
1928 1928
     {
1929 1929
         global $db, $langs, $conf;
1930 1930
         $langs->load("orders");
1931 1931
 
1932 1932
         // Clean parameters (if not defined or using deprecated value)
1933
-        if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
1933
+        if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus';
1934 1934
 
1935
-        $mybool=false;
1935
+        $mybool = false;
1936 1936
 
1937 1937
         $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php";
1938 1938
         $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER;
@@ -1945,18 +1945,18 @@  discard block
 block discarded – undo
1945 1945
             $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
1946 1946
 
1947 1947
             // Load file with numbering class (if found)
1948
-            $mybool|=@include_once $dir.$file;
1948
+            $mybool |= @include_once $dir.$file;
1949 1949
         }
1950 1950
 
1951
-        if (! $mybool)
1951
+        if (!$mybool)
1952 1952
         {
1953
-        	dol_print_error('',"Failed to include file ".$file);
1953
+        	dol_print_error('', "Failed to include file ".$file);
1954 1954
         	return '';
1955 1955
         }
1956 1956
 
1957 1957
         $obj = new $classname();
1958 1958
         $numref = "";
1959
-        $numref = $obj->getNumRef($soc,$this,$mode);
1959
+        $numref = $obj->getNumRef($soc, $this, $mode);
1960 1960
 
1961 1961
         if ($numref != "")
1962 1962
         {
@@ -1964,7 +1964,7 @@  discard block
 block discarded – undo
1964 1964
         }
1965 1965
         else
1966 1966
        {
1967
-       		$this->error=$obj->error;
1967
+       		$this->error = $obj->error;
1968 1968
         	//dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error);
1969 1969
         	return false;
1970 1970
         }
@@ -1979,9 +1979,9 @@  discard block
 block discarded – undo
1979 1979
 	 *	@param	string		$option		''=Create a specimen invoice with lines, 'nolines'=No lines
1980 1980
      *  @return	void
1981 1981
      */
1982
-    public function initAsSpecimen($option='')
1982
+    public function initAsSpecimen($option = '')
1983 1983
     {
1984
-        global $langs,$conf;
1984
+        global $langs, $conf;
1985 1985
 		include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1986 1986
 
1987 1987
         $now = dol_now();
@@ -1991,8 +1991,8 @@  discard block
 block discarded – undo
1991 1991
         $prodids = array();
1992 1992
 
1993 1993
         $sql = "SELECT rowid";
1994
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
1995
-        $sql.= " WHERE entity IN (".getEntity('product').")";
1994
+        $sql .= " FROM ".MAIN_DB_PREFIX."product";
1995
+        $sql .= " WHERE entity IN (".getEntity('product').")";
1996 1996
 
1997 1997
         $resql = $this->db->query($sql);
1998 1998
         if ($resql)
@@ -2008,17 +2008,17 @@  discard block
 block discarded – undo
2008 2008
         }
2009 2009
 
2010 2010
         // Initialise parametres
2011
-        $this->id=0;
2011
+        $this->id = 0;
2012 2012
         $this->ref = 'SPECIMEN';
2013 2013
         $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
2014
-        $this->specimen=1;
2014
+        $this->specimen = 1;
2015 2015
         $this->socid = 1;
2016 2016
         $this->date = $now;
2017
-        $this->date_lim_reglement=$this->date+3600*24*30;
2017
+        $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
2018 2018
         $this->cond_reglement_code = 'RECEP';
2019 2019
         $this->mode_reglement_code = 'CHQ';
2020
-        $this->note_public='This is a comment (public)';
2021
-        $this->note_private='This is a comment (private)';
2020
+        $this->note_public = 'This is a comment (public)';
2021
+        $this->note_private = 'This is a comment (private)';
2022 2022
 
2023 2023
 		if (empty($option) || $option != 'nolines')
2024 2024
 		{
@@ -2027,38 +2027,38 @@  discard block
 block discarded – undo
2027 2027
 	        $xnbp = 0;
2028 2028
 	        while ($xnbp < $nbp)
2029 2029
 	        {
2030
-	            $line=new FactureLigne($this->db);
2031
-	            $line->desc=$langs->trans("Description")." ".$xnbp;
2032
-	            $line->qty=1;
2033
-	            $line->subprice=100;
2034
-	            $line->pu_ht=100;		// the canelle template use pu_ht and not subprice
2035
-	            $line->price=100;
2036
-	            $line->tva_tx=19.6;
2037
-	            $line->localtax1_tx=0;
2038
-	            $line->localtax2_tx=0;
2030
+	            $line = new FactureLigne($this->db);
2031
+	            $line->desc = $langs->trans("Description")." ".$xnbp;
2032
+	            $line->qty = 1;
2033
+	            $line->subprice = 100;
2034
+	            $line->pu_ht = 100; // the canelle template use pu_ht and not subprice
2035
+	            $line->price = 100;
2036
+	            $line->tva_tx = 19.6;
2037
+	            $line->localtax1_tx = 0;
2038
+	            $line->localtax2_tx = 0;
2039 2039
 				if ($xnbp == 2)
2040 2040
 				{
2041
-				    $line->total_ht=50;
2042
-				    $line->total_ttc=59.8;
2043
-				    $line->total_tva=9.8;
2044
-	    			$line->remise_percent=50;
2041
+				    $line->total_ht = 50;
2042
+				    $line->total_ttc = 59.8;
2043
+				    $line->total_tva = 9.8;
2044
+	    			$line->remise_percent = 50;
2045 2045
 				}
2046 2046
 				else
2047 2047
 				{
2048
-				    $line->total_ht=100;
2049
-				    $line->total_ttc=119.6;
2050
-				    $line->total_tva=19.6;
2051
-	    			$line->remise_percent=0;
2048
+				    $line->total_ht = 100;
2049
+				    $line->total_ttc = 119.6;
2050
+				    $line->total_tva = 19.6;
2051
+	    			$line->remise_percent = 0;
2052 2052
 				}
2053 2053
 
2054 2054
 	            if ($num_prods > 0)
2055 2055
 	            {
2056 2056
 					$prodid = mt_rand(1, $num_prods);
2057
-	            	$line->fk_product=$prodids[$prodid];
2057
+	            	$line->fk_product = $prodids[$prodid];
2058 2058
 	            }
2059
-	            $line->product_type=0;
2059
+	            $line->product_type = 0;
2060 2060
 
2061
-	            $this->lines[$xnbp]=$line;
2061
+	            $this->lines[$xnbp] = $line;
2062 2062
 
2063 2063
 	    		$this->total_ht       += $line->total_ht;
2064 2064
 	    		$this->total_tva      += $line->total_tva;
@@ -2068,10 +2068,10 @@  discard block
 block discarded – undo
2068 2068
 	        }
2069 2069
 		}
2070 2070
 
2071
-        $this->amount_ht      = $xnbp*100;
2072
-        $this->total_ht       = $xnbp*100;
2073
-        $this->total_tva      = $xnbp*19.6;
2074
-        $this->total_ttc      = $xnbp*119.6;
2071
+        $this->amount_ht      = $xnbp * 100;
2072
+        $this->total_ht       = $xnbp * 100;
2073
+        $this->total_tva      = $xnbp * 19.6;
2074
+        $this->total_ttc      = $xnbp * 119.6;
2075 2075
     }
2076 2076
 
2077 2077
 	/**
@@ -2083,27 +2083,27 @@  discard block
 block discarded – undo
2083 2083
 	{
2084 2084
 		global $conf, $user;
2085 2085
 
2086
-		$this->nb=array();
2086
+		$this->nb = array();
2087 2087
 
2088 2088
 		$clause = "WHERE";
2089 2089
 
2090 2090
 		$sql = "SELECT count(f.rowid) as nb";
2091
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2092
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
2091
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2092
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
2093 2093
 		if (!$user->rights->societe->client->voir && !$user->societe_id)
2094 2094
 		{
2095
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2096
-			$sql.= " WHERE sc.fk_user = " .$user->id;
2095
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2096
+			$sql .= " WHERE sc.fk_user = ".$user->id;
2097 2097
 			$clause = "AND";
2098 2098
 		}
2099
-		$sql.= " ".$clause." f.entity = ".$conf->entity;
2099
+		$sql .= " ".$clause." f.entity = ".$conf->entity;
2100 2100
 
2101
-		$resql=$this->db->query($sql);
2101
+		$resql = $this->db->query($sql);
2102 2102
 		if ($resql)
2103 2103
 		{
2104
-			while ($obj=$this->db->fetch_object($resql))
2104
+			while ($obj = $this->db->fetch_object($resql))
2105 2105
 			{
2106
-				$this->nb["supplier_invoices"]=$obj->nb;
2106
+				$this->nb["supplier_invoices"] = $obj->nb;
2107 2107
 			}
2108 2108
             $this->db->free($resql);
2109 2109
 			return 1;
@@ -2111,7 +2111,7 @@  discard block
 block discarded – undo
2111 2111
 		else
2112 2112
 		{
2113 2113
 			dol_print_error($this->db);
2114
-			$this->error=$this->db->error();
2114
+			$this->error = $this->db->error();
2115 2115
 			return -1;
2116 2116
 		}
2117 2117
 	}
@@ -2123,13 +2123,13 @@  discard block
 block discarded – undo
2123 2123
      *	@param		int		$invertdetail	Reverse sign of amounts for lines
2124 2124
      * 	@return		int						New id of clone
2125 2125
      */
2126
-    public function createFromClone($fromid,$invertdetail=0)
2126
+    public function createFromClone($fromid, $invertdetail = 0)
2127 2127
     {
2128
-        global $user,$langs;
2128
+        global $user, $langs;
2129 2129
 
2130
-        $error=0;
2130
+        $error = 0;
2131 2131
 
2132
-        $object=new FactureFournisseur($this->db);
2132
+        $object = new FactureFournisseur($this->db);
2133 2133
 
2134 2134
 		$object->context['createfromclone'] = 'createfromclone';
2135 2135
 
@@ -2137,11 +2137,11 @@  discard block
 block discarded – undo
2137 2137
 
2138 2138
         // Load source object
2139 2139
         $object->fetch($fromid);
2140
-        $object->id=0;
2141
-        $object->statut=self::STATUS_DRAFT;
2140
+        $object->id = 0;
2141
+        $object->statut = self::STATUS_DRAFT;
2142 2142
 
2143 2143
         // Clear fields
2144
-        $object->ref_supplier=$langs->trans("CopyOf").' '.$object->ref_supplier;
2144
+        $object->ref_supplier = $langs->trans("CopyOf").' '.$object->ref_supplier;
2145 2145
         $object->author             = $user->id;
2146 2146
         $object->user_valid         = '';
2147 2147
         $object->fk_facture_source  = 0;
@@ -2154,7 +2154,7 @@  discard block
 block discarded – undo
2154 2154
         $object->close_note         = '';
2155 2155
 
2156 2156
         // Loop on each line of new invoice
2157
-        foreach($object->lines as $i => $line)
2157
+        foreach ($object->lines as $i => $line)
2158 2158
         {
2159 2159
             if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
2160 2160
             {
@@ -2163,16 +2163,16 @@  discard block
 block discarded – undo
2163 2163
         }
2164 2164
 
2165 2165
         // Create clone
2166
-        $result=$object->create($user);
2166
+        $result = $object->create($user);
2167 2167
 
2168 2168
         // Other options
2169 2169
         if ($result < 0)
2170 2170
         {
2171
-            $this->error=$object->error;
2171
+            $this->error = $object->error;
2172 2172
             $error++;
2173 2173
         }
2174 2174
 
2175
-        if (! $error)
2175
+        if (!$error)
2176 2176
         {
2177 2177
 
2178 2178
 
@@ -2182,7 +2182,7 @@  discard block
 block discarded – undo
2182 2182
         unset($object->context['createfromclone']);
2183 2183
 
2184 2184
         // End
2185
-        if (! $error)
2185
+        if (!$error)
2186 2186
         {
2187 2187
             $this->db->commit();
2188 2188
             return $object->id;
@@ -2204,7 +2204,7 @@  discard block
 block discarded – undo
2204 2204
 	 *  @param      int			$hideref        Hide ref
2205 2205
 	 *  @return     int         				<0 if KO, 0 if nothing done, >0 if OK
2206 2206
 	 */
2207
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
2207
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2208 2208
 	{
2209 2209
 		global $conf, $user, $langs;
2210 2210
 
@@ -2213,13 +2213,13 @@  discard block
 block discarded – undo
2213 2213
 		// Set the model on the model name to use
2214 2214
 		if (empty($modele))
2215 2215
 		{
2216
-			if (! empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF))
2216
+			if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF))
2217 2217
 			{
2218 2218
 				$modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF;
2219 2219
 			}
2220 2220
 			else
2221 2221
 			{
2222
-				$modele = '';       // No default value. For supplier invoice, we allow to disable all PDF generation
2222
+				$modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation
2223 2223
 			}
2224 2224
 		}
2225 2225
 
@@ -2289,8 +2289,8 @@  discard block
 block discarded – undo
2289 2289
  */
2290 2290
 class SupplierInvoiceLine extends CommonObjectLine
2291 2291
 {
2292
-	public $element='facture_fourn_det';
2293
-	public $table_element='facture_fourn_det';
2292
+	public $element = 'facture_fourn_det';
2293
+	public $table_element = 'facture_fourn_det';
2294 2294
 
2295 2295
 	public $oldline;
2296 2296
 
@@ -2412,7 +2412,7 @@  discard block
 block discarded – undo
2412 2412
      */
2413 2413
     public function __construct($db)
2414 2414
     {
2415
-        $this->db= $db;
2415
+        $this->db = $db;
2416 2416
     }
2417 2417
 
2418 2418
 	/**
@@ -2424,14 +2424,14 @@  discard block
 block discarded – undo
2424 2424
 	public function fetch($rowid)
2425 2425
 	{
2426 2426
 		$sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.tva_tx';
2427
-		$sql.= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 ';
2428
-		$sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_facture_fourn, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
2429
-		$sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
2430
-		$sql.= ', f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, multicurrency_total_ttc';
2431
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
2432
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
2433
-		$sql.= ' WHERE f.rowid = '.$rowid;
2434
-		$sql.= ' ORDER BY f.rang, f.rowid';
2427
+		$sql .= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 ';
2428
+		$sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_facture_fourn, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
2429
+		$sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
2430
+		$sql .= ', f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, multicurrency_total_ttc';
2431
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
2432
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
2433
+		$sql .= ' WHERE f.rowid = '.$rowid;
2434
+		$sql .= ' ORDER BY f.rang, f.rowid';
2435 2435
 
2436 2436
 		$query = $this->db->query($sql);
2437 2437
 
@@ -2446,17 +2446,17 @@  discard block
 block discarded – undo
2446 2446
 
2447 2447
 		$obj = $this->db->fetch_object($query);
2448 2448
 
2449
-		$this->id				= $obj->rowid;
2450
-		$this->rowid				= $obj->rowid;
2451
-		$this->fk_facture_fourn			= $obj->fk_facture_fourn;
2449
+		$this->id = $obj->rowid;
2450
+		$this->rowid = $obj->rowid;
2451
+		$this->fk_facture_fourn = $obj->fk_facture_fourn;
2452 2452
 		$this->description		= $obj->description;
2453 2453
 		$this->product_ref		= $obj->product_ref;
2454
-		$this->ref				= $obj->product_ref;
2454
+		$this->ref = $obj->product_ref;
2455 2455
 		$this->ref_supplier		= $obj->ref_supplier;
2456 2456
 		$this->libelle			= $obj->label;
2457 2457
 		$this->label  			= $obj->label;
2458 2458
 		$this->product_desc		= $obj->product_desc;
2459
-		$this->subprice			= $obj->pu_ht;
2459
+		$this->subprice = $obj->pu_ht;
2460 2460
 		$this->pu_ht				= $obj->pu_ht;
2461 2461
 		$this->pu_ttc			= $obj->pu_ttc;
2462 2462
 		$this->tva_tx			= $obj->tva_tx;
@@ -2465,20 +2465,20 @@  discard block
 block discarded – undo
2465 2465
 		$this->localtax1_type		= $obj->localtax1_type;
2466 2466
 		$this->localtax2_type		= $obj->localtax2_type;
2467 2467
 		$this->qty				= $obj->qty;
2468
-		$this->remise_percent    = $obj->remise_percent;
2468
+		$this->remise_percent = $obj->remise_percent;
2469 2469
 		$this->tva				= $obj->total_tva;
2470
-		$this->total_ht			= $obj->total_ht;
2470
+		$this->total_ht = $obj->total_ht;
2471 2471
 		$this->total_tva			= $obj->total_tva;
2472 2472
 		$this->total_localtax1	= $obj->total_localtax1;
2473 2473
 		$this->total_localtax2	= $obj->total_localtax2;
2474 2474
 		$this->total_ttc			= $obj->total_ttc;
2475 2475
 		$this->fk_product		= $obj->fk_product;
2476
-		$this->product_type		= $obj->product_type;
2476
+		$this->product_type = $obj->product_type;
2477 2477
 		$this->product_label		= $obj->label;
2478 2478
 		$this->info_bits		    = $obj->info_bits;
2479 2479
 		$this->fk_parent_line    = $obj->fk_parent_line;
2480
-		$this->special_code		= $obj->special_code;
2481
-		$this->rang       		= $obj->rang;
2480
+		$this->special_code = $obj->special_code;
2481
+		$this->rang = $obj->rang;
2482 2482
 		$this->fk_unit           = $obj->fk_unit;
2483 2483
 
2484 2484
 		$this->multicurrency_subprice	= $obj->multicurrency_subprice;
@@ -2504,7 +2504,7 @@  discard block
 block discarded – undo
2504 2504
 		$this->db->begin();
2505 2505
 
2506 2506
 		if (!$notrigger) {
2507
-			if ($this->call_trigger('LINEBILL_SUPPLIER_DELETE',$user) < 0) {
2507
+			if ($this->call_trigger('LINEBILL_SUPPLIER_DELETE', $user) < 0) {
2508 2508
 				$error++;
2509 2509
 			}
2510 2510
 		}
@@ -2521,7 +2521,7 @@  discard block
 block discarded – undo
2521 2521
 			}
2522 2522
 		}
2523 2523
 
2524
-		if (! $error)
2524
+		if (!$error)
2525 2525
 		{
2526 2526
 			$this->db->commit();
2527 2527
 			return 1;
@@ -2544,10 +2544,10 @@  discard block
 block discarded – undo
2544 2544
 		global $conf;
2545 2545
 
2546 2546
 		$pu = price2num($this->pu_ht);
2547
-		$qty  = price2num($this->qty);
2547
+		$qty = price2num($this->qty);
2548 2548
 
2549 2549
 		// Check parameters
2550
-		if (empty($this->qty)) $this->qty=0;
2550
+		if (empty($this->qty)) $this->qty = 0;
2551 2551
 
2552 2552
 		if ($this->product_type < 0) {
2553 2553
 			return -1;
@@ -2575,34 +2575,34 @@  discard block
 block discarded – undo
2575 2575
 		}
2576 2576
 
2577 2577
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
2578
-		$sql.= " description ='".$this->db->escape($this->description)."'";
2579
-		$sql.= ", pu_ht = ".price2num($this->pu_ht);
2580
-		$sql.= ", pu_ttc = ".price2num($this->pu_ttc);
2581
-		$sql.= ", qty = ".price2num($this->qty);
2582
-		$sql.= ", remise_percent = ".price2num($this->remise_percent);
2583
-		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
2584
-		$sql.= ", tva_tx = ".price2num($this->tva_tx);
2585
-		$sql.= ", localtax1_tx = ".price2num($this->localtax1_tx);
2586
-		$sql.= ", localtax2_tx = ".price2num($this->localtax2_tx);
2587
-		$sql.= ", localtax1_type = '".$this->db->escape($this->localtax1_type)."'";
2588
-		$sql.= ", localtax2_type = '".$this->db->escape($this->localtax2_type)."'";
2589
-		$sql.= ", total_ht = ".price2num($this->total_ht);
2590
-		$sql.= ", tva= ".price2num($this->total_tva);
2591
-		$sql.= ", total_localtax1= ".price2num($this->total_localtax1);
2592
-		$sql.= ", total_localtax2= ".price2num($this->total_localtax2);
2593
-		$sql.= ", total_ttc = ".price2num($this->total_ttc);
2594
-		$sql.= ", fk_product = ".$fk_product;
2595
-		$sql.= ", product_type = ".$this->product_type;
2596
-		$sql.= ", info_bits = ".$this->info_bits;
2597
-		$sql.= ", fk_unit = ".$fk_unit;
2578
+		$sql .= " description ='".$this->db->escape($this->description)."'";
2579
+		$sql .= ", pu_ht = ".price2num($this->pu_ht);
2580
+		$sql .= ", pu_ttc = ".price2num($this->pu_ttc);
2581
+		$sql .= ", qty = ".price2num($this->qty);
2582
+		$sql .= ", remise_percent = ".price2num($this->remise_percent);
2583
+		$sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
2584
+		$sql .= ", tva_tx = ".price2num($this->tva_tx);
2585
+		$sql .= ", localtax1_tx = ".price2num($this->localtax1_tx);
2586
+		$sql .= ", localtax2_tx = ".price2num($this->localtax2_tx);
2587
+		$sql .= ", localtax1_type = '".$this->db->escape($this->localtax1_type)."'";
2588
+		$sql .= ", localtax2_type = '".$this->db->escape($this->localtax2_type)."'";
2589
+		$sql .= ", total_ht = ".price2num($this->total_ht);
2590
+		$sql .= ", tva= ".price2num($this->total_tva);
2591
+		$sql .= ", total_localtax1= ".price2num($this->total_localtax1);
2592
+		$sql .= ", total_localtax2= ".price2num($this->total_localtax2);
2593
+		$sql .= ", total_ttc = ".price2num($this->total_ttc);
2594
+		$sql .= ", fk_product = ".$fk_product;
2595
+		$sql .= ", product_type = ".$this->product_type;
2596
+		$sql .= ", info_bits = ".$this->info_bits;
2597
+		$sql .= ", fk_unit = ".$fk_unit;
2598 2598
 
2599 2599
 		// Multicurrency
2600
-		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
2601
-        $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
2602
-        $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
2603
-        $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
2600
+		$sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
2601
+        $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
2602
+        $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
2603
+        $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
2604 2604
 
2605
-		$sql.= " WHERE rowid = ".$this->id;
2605
+		$sql .= " WHERE rowid = ".$this->id;
2606 2606
 
2607 2607
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
2608 2608
 		$resql = $this->db->query($sql);
@@ -2623,12 +2623,12 @@  discard block
 block discarded – undo
2623 2623
 			}
2624 2624
 		}
2625 2625
 
2626
-		if (! $error && ! $notrigger)
2626
+		if (!$error && !$notrigger)
2627 2627
 		{
2628 2628
 			global $langs, $user;
2629 2629
 
2630 2630
 			// Call trigger
2631
-			if ($this->call_trigger('LINEBILL_SUPPLIER_UPDATE',$user) < 0) {
2631
+			if ($this->call_trigger('LINEBILL_SUPPLIER_UPDATE', $user) < 0) {
2632 2632
 				$this->db->rollback();
2633 2633
 				return -1;
2634 2634
 			}
@@ -2650,51 +2650,51 @@  discard block
 block discarded – undo
2650 2650
      *	@param      int		$notrigger		1 no triggers
2651 2651
      *	@return		int						<0 if KO, >0 if OK
2652 2652
      */
2653
-    public function insert($notrigger=0)
2653
+    public function insert($notrigger = 0)
2654 2654
     {
2655
-        global $user,$conf;
2655
+        global $user, $conf;
2656 2656
 
2657
-        $error=0;
2657
+        $error = 0;
2658 2658
 
2659 2659
         dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
2660 2660
 
2661 2661
         // Clean parameters
2662
-        $this->desc=trim($this->desc);
2663
-        if (empty($this->tva_tx)) $this->tva_tx=0;
2664
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
2665
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
2666
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
2667
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
2668
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
2669
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
2670
-        if (empty($this->rang)) $this->rang=0;
2671
-        if (empty($this->remise_percent)) $this->remise_percent=0;
2672
-        if (empty($this->info_bits)) $this->info_bits=0;
2673
-        if (empty($this->subprice)) $this->subprice=0;
2674
-        if (empty($this->special_code)) $this->special_code=0;
2675
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
2676
-        if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
2677
-
2678
-        if (empty($this->pa_ht)) $this->pa_ht=0;
2679
-        if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
2680
-        if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
2681
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
2682
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
2662
+        $this->desc = trim($this->desc);
2663
+        if (empty($this->tva_tx)) $this->tva_tx = 0;
2664
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
2665
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
2666
+        if (empty($this->localtax1_type)) $this->localtax1_type = '0';
2667
+        if (empty($this->localtax2_type)) $this->localtax2_type = '0';
2668
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
2669
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
2670
+        if (empty($this->rang)) $this->rang = 0;
2671
+        if (empty($this->remise_percent)) $this->remise_percent = 0;
2672
+        if (empty($this->info_bits)) $this->info_bits = 0;
2673
+        if (empty($this->subprice)) $this->subprice = 0;
2674
+        if (empty($this->special_code)) $this->special_code = 0;
2675
+        if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
2676
+        if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
2677
+
2678
+        if (empty($this->pa_ht)) $this->pa_ht = 0;
2679
+        if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0;
2680
+        if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0;
2681
+        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
2682
+        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
2683 2683
 
2684 2684
 
2685 2685
         // Check parameters
2686 2686
         if ($this->product_type < 0)
2687 2687
         {
2688
-            $this->error='ErrorProductTypeMustBe0orMore';
2688
+            $this->error = 'ErrorProductTypeMustBe0orMore';
2689 2689
             return -1;
2690 2690
         }
2691
-        if (! empty($this->fk_product))
2691
+        if (!empty($this->fk_product))
2692 2692
         {
2693 2693
             // Check product exists
2694
-            $result=Product::isExistingObject('product', $this->fk_product);
2694
+            $result = Product::isExistingObject('product', $this->fk_product);
2695 2695
             if ($result <= 0)
2696 2696
             {
2697
-                $this->error='ErrorProductIdDoesNotExists';
2697
+                $this->error = 'ErrorProductIdDoesNotExists';
2698 2698
                 return -1;
2699 2699
             }
2700 2700
         }
@@ -2703,70 +2703,70 @@  discard block
 block discarded – undo
2703 2703
 
2704 2704
         // Insertion dans base de la ligne
2705 2705
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
2706
-        $sql.= ' (fk_facture_fourn, fk_parent_line, label, description, qty,';
2707
-        $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
2708
-        $sql.= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,';
2709
-        $sql.= ' date_start, date_end, fk_code_ventilation, rang, special_code,';
2710
-        $sql.= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit';
2711
-        $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2712
-        $sql.= ')';
2713
-        $sql.= " VALUES (".$this->fk_facture_fourn.",";
2714
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
2715
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
2716
-        $sql.= " '".$this->db->escape($this->desc)."',";
2717
-        $sql.= " ".price2num($this->qty).",";
2718
-
2719
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
2720
-        $sql.= " ".price2num($this->tva_tx).",";
2721
-        $sql.= " ".price2num($this->localtax1_tx).",";
2722
-        $sql.= " ".price2num($this->localtax2_tx).",";
2723
-        $sql.= " '".$this->db->escape($this->localtax1_type)."',";
2724
-        $sql.= " '".$this->db->escape($this->localtax2_type)."',";
2725
-        $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
2726
-        $sql.= " ".$this->product_type.",";
2727
-        $sql.= " ".price2num($this->remise_percent).",";
2728
-        $sql.= " ".price2num($this->subprice).",";
2729
-        $sql.= " ".price2num($this->total_ttc/$this->qty).",";
2730
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").",";
2731
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").",";
2732
-        $sql.= ' '.(!empty($this->fk_code_ventilation)?$this->fk_code_ventilation:0).',';
2733
-        $sql.= ' '.$this->rang.',';
2734
-        $sql.= ' '.$this->special_code.',';
2735
-        $sql.= " '".$this->db->escape($this->info_bits)."',";
2736
-        $sql.= " ".price2num($this->total_ht).",";
2737
-        $sql.= " ".price2num($this->total_tva).",";
2738
-        $sql.= " ".price2num($this->total_ttc).",";
2739
-        $sql.= " ".price2num($this->total_localtax1).",";
2740
-        $sql.= " ".price2num($this->total_localtax2);
2706
+        $sql .= ' (fk_facture_fourn, fk_parent_line, label, description, qty,';
2707
+        $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
2708
+        $sql .= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,';
2709
+        $sql .= ' date_start, date_end, fk_code_ventilation, rang, special_code,';
2710
+        $sql .= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit';
2711
+        $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2712
+        $sql .= ')';
2713
+        $sql .= " VALUES (".$this->fk_facture_fourn.",";
2714
+        $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
2715
+        $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
2716
+        $sql .= " '".$this->db->escape($this->desc)."',";
2717
+        $sql .= " ".price2num($this->qty).",";
2718
+
2719
+        $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
2720
+        $sql .= " ".price2num($this->tva_tx).",";
2721
+        $sql .= " ".price2num($this->localtax1_tx).",";
2722
+        $sql .= " ".price2num($this->localtax2_tx).",";
2723
+        $sql .= " '".$this->db->escape($this->localtax1_type)."',";
2724
+        $sql .= " '".$this->db->escape($this->localtax2_type)."',";
2725
+        $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").',';
2726
+        $sql .= " ".$this->product_type.",";
2727
+        $sql .= " ".price2num($this->remise_percent).",";
2728
+        $sql .= " ".price2num($this->subprice).",";
2729
+        $sql .= " ".price2num($this->total_ttc / $this->qty).",";
2730
+        $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
2731
+        $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
2732
+        $sql .= ' '.(!empty($this->fk_code_ventilation) ? $this->fk_code_ventilation : 0).',';
2733
+        $sql .= ' '.$this->rang.',';
2734
+        $sql .= ' '.$this->special_code.',';
2735
+        $sql .= " '".$this->db->escape($this->info_bits)."',";
2736
+        $sql .= " ".price2num($this->total_ht).",";
2737
+        $sql .= " ".price2num($this->total_tva).",";
2738
+        $sql .= " ".price2num($this->total_ttc).",";
2739
+        $sql .= " ".price2num($this->total_localtax1).",";
2740
+        $sql .= " ".price2num($this->total_localtax2);
2741 2741
         $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
2742
-        $sql.= ", ".(int) $this->fk_multicurrency;
2743
-        $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
2744
-        $sql.= ", ".price2num($this->multicurrency_subprice);
2745
-        $sql.= ", ".price2num($this->multicurrency_total_ht);
2746
-        $sql.= ", ".price2num($this->multicurrency_total_tva);
2747
-        $sql.= ", ".price2num($this->multicurrency_total_ttc);
2748
-        $sql.= ')';
2742
+        $sql .= ", ".(int) $this->fk_multicurrency;
2743
+        $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
2744
+        $sql .= ", ".price2num($this->multicurrency_subprice);
2745
+        $sql .= ", ".price2num($this->multicurrency_total_ht);
2746
+        $sql .= ", ".price2num($this->multicurrency_total_tva);
2747
+        $sql .= ", ".price2num($this->multicurrency_total_ttc);
2748
+        $sql .= ')';
2749 2749
 
2750 2750
         dol_syslog(get_class($this)."::insert", LOG_DEBUG);
2751
-        $resql=$this->db->query($sql);
2751
+        $resql = $this->db->query($sql);
2752 2752
         if ($resql)
2753 2753
         {
2754
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
2755
-            $this->rowid=$this->id;
2754
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
2755
+            $this->rowid = $this->id;
2756 2756
 
2757 2757
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2758 2758
             {
2759
-                $result=$this->insertExtraFields();
2759
+                $result = $this->insertExtraFields();
2760 2760
                 if ($result < 0)
2761 2761
                 {
2762 2762
                     $error++;
2763 2763
                 }
2764 2764
             }
2765 2765
 
2766
-            if (! $notrigger)
2766
+            if (!$notrigger)
2767 2767
             {
2768 2768
                 // Call trigger
2769
-                $result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE',$user);
2769
+                $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user);
2770 2770
                 if ($result < 0)
2771 2771
                 {
2772 2772
                     $this->db->rollback();
@@ -2781,7 +2781,7 @@  discard block
 block discarded – undo
2781 2781
         }
2782 2782
         else
2783 2783
         {
2784
-            $this->error=$this->db->error();
2784
+            $this->error = $this->db->error();
2785 2785
             $this->db->rollback();
2786 2786
             return -2;
2787 2787
         }
@@ -2797,16 +2797,16 @@  discard block
 block discarded – undo
2797 2797
 
2798 2798
         // Mise a jour ligne en base
2799 2799
         $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
2800
-        $sql.= "  total_ht='".price2num($this->total_ht)."'";
2801
-        $sql.= ", tva='".price2num($this->total_tva)."'";
2802
-        $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
2803
-        $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
2804
-        $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
2805
-        $sql.= " WHERE rowid = ".$this->rowid;
2800
+        $sql .= "  total_ht='".price2num($this->total_ht)."'";
2801
+        $sql .= ", tva='".price2num($this->total_tva)."'";
2802
+        $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'";
2803
+        $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'";
2804
+        $sql .= ", total_ttc='".price2num($this->total_ttc)."'";
2805
+        $sql .= " WHERE rowid = ".$this->rowid;
2806 2806
 
2807 2807
         dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG);
2808 2808
 
2809
-        $resql=$this->db->query($sql);
2809
+        $resql = $this->db->query($sql);
2810 2810
         if ($resql)
2811 2811
         {
2812 2812
             $this->db->commit();
@@ -2814,7 +2814,7 @@  discard block
 block discarded – undo
2814 2814
         }
2815 2815
         else
2816 2816
         {
2817
-            $this->error=$this->db->error();
2817
+            $this->error = $this->db->error();
2818 2818
             $this->db->rollback();
2819 2819
             return -2;
2820 2820
         }
Please login to merge, or discard this patch.
Braces   +415 added lines, -208 removed lines patch added patch discarded remove patch
@@ -220,9 +220,15 @@  discard block
 block discarded – undo
220 220
         $now=dol_now();
221 221
 
222 222
         // Clean parameters
223
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
224
-        if (empty($this->type)) $this->type = self::TYPE_STANDARD;
225
-        if (empty($this->date)) $this->date=$now;
223
+        if (isset($this->ref_supplier)) {
224
+        	$this->ref_supplier=trim($this->ref_supplier);
225
+        }
226
+        if (empty($this->type)) {
227
+        	$this->type = self::TYPE_STANDARD;
228
+        }
229
+        if (empty($this->date)) {
230
+        	$this->date=$now;
231
+        }
226 232
 
227 233
         $socid = $this->socid;
228 234
         $ref_supplier = $this->ref_supplier;
@@ -230,8 +236,11 @@  discard block
 block discarded – undo
230 236
         $remise = $this->remise;
231 237
 
232 238
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
233
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
234
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
239
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
240
+			list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
241
+		} else {
242
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
243
+		}
235 244
 		if (empty($this->fk_multicurrency))
236 245
 		{
237 246
 			$this->multicurrency_code = $conf->currency;
@@ -241,7 +250,9 @@  discard block
 block discarded – undo
241 250
 
242 251
         $this->db->begin();
243 252
 
244
-        if (! $remise) $remise = 0 ;
253
+        if (! $remise) {
254
+        	$remise = 0 ;
255
+        }
245 256
         $totalht = ($amount - $remise);
246 257
 
247 258
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
@@ -304,7 +315,9 @@  discard block
 block discarded – undo
304 315
 
305 316
             dol_syslog(get_class($this)."::create", LOG_DEBUG);
306 317
             $resql=$this->db->query($sql);
307
-            if (! $resql) $error++;
318
+            if (! $resql) {
319
+            	$error++;
320
+            }
308 321
 
309 322
             // Add object linked
310 323
             if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id))
@@ -317,9 +330,11 @@  discard block
 block discarded – undo
317 330
                 }
318 331
             }
319 332
 
320
-			if (count($this->lines) && is_object($this->lines[0]))	// If this->lines is array of InvoiceLines (preferred mode)
333
+			if (count($this->lines) && is_object($this->lines[0])) {
334
+				// If this->lines is array of InvoiceLines (preferred mode)
321 335
 			{
322 336
                 dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
337
+			}
323 338
                 foreach ($this->lines as $i => $val)
324 339
                 {
325 340
                     $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
@@ -343,16 +358,14 @@  discard block
 block discarded – undo
343 358
                             (! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''),
344 359
                             $this->lines[$i]->product_type
345 360
                         );
346
-                    }
347
-                    else
361
+                    } else
348 362
                     {
349 363
                         $this->error=$this->db->lasterror();
350 364
                         $this->db->rollback();
351 365
                         return -5;
352 366
                     }
353 367
                 }
354
-			}
355
-			else	// If this->lines is an array of invoice line arrays
368
+			} else	// If this->lines is an array of invoice line arrays
356 369
 			{
357 370
 			    dol_syslog("There is ".count($this->lines)." lines that are array lines");
358 371
 			    foreach ($this->lines as $i => $val)
@@ -361,7 +374,9 @@  discard block
 block discarded – undo
361 374
 
362 375
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
363 376
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
364
-                	if (! is_object($line)) $line = (object) $line;
377
+                	if (! is_object($line)) {
378
+                		$line = (object) $line;
379
+                	}
365 380
 
366 381
                 	$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
367 382
 			        $sql .= ' VALUES ('.$this->id.')';
@@ -384,8 +399,7 @@  discard block
 block discarded – undo
384 399
 			                (! empty($line->info_bits)?$line->info_bits:''),
385 400
 			                $line->product_type
386 401
 			                );
387
-			        }
388
-			        else
402
+			        } else
389 403
 			        {
390 404
 			            $this->error=$this->db->lasterror();
391 405
 			            $this->db->rollback();
@@ -407,22 +421,28 @@  discard block
 block discarded – undo
407 421
 				$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
408 422
 				if (empty($reshook))
409 423
 				{
410
-	            	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
424
+	            	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
425
+	            		// For avoid conflicts if trigger used
411 426
 					{
412
-						$result=$this->insertExtraFields();               // This also set $this->error or $this->errors if errors are found
427
+						$result=$this->insertExtraFields();
428
+	            	}
429
+	            	// This also set $this->error or $this->errors if errors are found
413 430
 						if ($result < 0)
414 431
 						{
415 432
 							$error++;
416 433
 						}
417 434
 					}
435
+				} else if ($reshook < 0) {
436
+					$error++;
418 437
 				}
419
-				else if ($reshook < 0) $error++;
420 438
 
421 439
 				if (! $error)
422 440
 				{
423 441
                     // Call trigger
424 442
                     $result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user);
425
-                    if ($result < 0) $error++;
443
+                    if ($result < 0) {
444
+                    	$error++;
445
+                    }
426 446
                     // End call triggers
427 447
 				}
428 448
 
@@ -430,29 +450,25 @@  discard block
 block discarded – undo
430 450
                 {
431 451
                     $this->db->commit();
432 452
                     return $this->id;
433
-                }
434
-                else
453
+                } else
435 454
                 {
436 455
                     $this->db->rollback();
437 456
                     return -4;
438 457
                 }
439
-            }
440
-            else
458
+            } else
441 459
             {
442 460
                 $this->error=$langs->trans('FailedToUpdatePrice');
443 461
                 $this->db->rollback();
444 462
                 return -3;
445 463
             }
446
-        }
447
-        else
464
+        } else
448 465
         {
449 466
             if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
450 467
             {
451 468
                 $this->error=$langs->trans('ErrorRefAlreadyExists');
452 469
                 $this->db->rollback();
453 470
                 return -1;
454
-            }
455
-            else
471
+            } else
456 472
             {
457 473
                 $this->error=$this->db->lasterror();
458 474
                 $this->db->rollback();
@@ -520,8 +536,12 @@  discard block
 block discarded – undo
520 536
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")";
521 537
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")";
522 538
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
523
-        if ($id)  $sql.= " WHERE t.rowid=".$id;
524
-        if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
539
+        if ($id) {
540
+        	$sql.= " WHERE t.rowid=".$id;
541
+        }
542
+        if ($ref) {
543
+        	$sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
544
+        }
525 545
 
526 546
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
527 547
         $resql=$this->db->query($sql);
@@ -604,7 +624,9 @@  discard block
 block discarded – undo
604 624
                 $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
605 625
                 $this->fetch_optionals($this->id,$extralabels);
606 626
 
607
-                if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
627
+                if ($this->statut == self::STATUS_DRAFT) {
628
+                	$this->brouillon = 1;
629
+                }
608 630
 
609 631
                 $result=$this->fetch_lines();
610 632
                 if ($result < 0)
@@ -613,8 +635,7 @@  discard block
 block discarded – undo
613 635
                     return -3;
614 636
                 }
615 637
 
616
-            }
617
-            else
638
+            } else
618 639
             {
619 640
                 $this->error='Bill with id '.$id.' not found';
620 641
                 dol_syslog(get_class($this).'::fetch '.$this->error);
@@ -623,8 +644,7 @@  discard block
 block discarded – undo
623 644
 
624 645
             $this->db->free($resql);
625 646
             return 1;
626
-        }
627
-        else
647
+        } else
628 648
         {
629 649
             $this->error="Error ".$this->db->lasterror();
630 650
             return -1;
@@ -716,8 +736,7 @@  discard block
 block discarded – undo
716 736
             }
717 737
             $this->db->free($resql_rows);
718 738
             return 1;
719
-        }
720
-        else
739
+        } else
721 740
         {
722 741
             $this->error=$this->db->error();
723 742
             return -3;
@@ -738,36 +757,92 @@  discard block
 block discarded – undo
738 757
         $error=0;
739 758
 
740 759
         // Clean parameters
741
-        if (empty($this->type)) $this->type= self::TYPE_STANDARD;
742
-		if (isset($this->ref)) $this->ref=trim($this->ref);
743
-        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
744
-        if (isset($this->entity)) $this->entity=trim($this->entity);
745
-        if (isset($this->type)) $this->type=trim($this->type);
746
-        if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
747
-        if (isset($this->libelle)) $this->libelle=trim($this->libelle);
748
-        if (isset($this->paye)) $this->paye=trim($this->paye);
749
-        if (isset($this->amount)) $this->amount=trim($this->amount);
750
-        if (isset($this->remise)) $this->remise=trim($this->remise);
751
-        if (isset($this->close_code)) $this->close_code=trim($this->close_code);
752
-        if (isset($this->close_note)) $this->close_note=trim($this->close_note);
753
-        if (isset($this->tva)) $this->tva=trim($this->tva);
754
-        if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1);
755
-        if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2);
756
-        if (empty($this->total_ht)) $this->total_ht=0;
757
-        if (empty($this->total_tva)) $this->total_tva=0;
760
+        if (empty($this->type)) {
761
+        	$this->type= self::TYPE_STANDARD;
762
+        }
763
+		if (isset($this->ref)) {
764
+			$this->ref=trim($this->ref);
765
+		}
766
+        if (isset($this->ref_supplier)) {
767
+        	$this->ref_supplier=trim($this->ref_supplier);
768
+        }
769
+        if (isset($this->entity)) {
770
+        	$this->entity=trim($this->entity);
771
+        }
772
+        if (isset($this->type)) {
773
+        	$this->type=trim($this->type);
774
+        }
775
+        if (isset($this->fk_soc)) {
776
+        	$this->fk_soc=trim($this->fk_soc);
777
+        }
778
+        if (isset($this->libelle)) {
779
+        	$this->libelle=trim($this->libelle);
780
+        }
781
+        if (isset($this->paye)) {
782
+        	$this->paye=trim($this->paye);
783
+        }
784
+        if (isset($this->amount)) {
785
+        	$this->amount=trim($this->amount);
786
+        }
787
+        if (isset($this->remise)) {
788
+        	$this->remise=trim($this->remise);
789
+        }
790
+        if (isset($this->close_code)) {
791
+        	$this->close_code=trim($this->close_code);
792
+        }
793
+        if (isset($this->close_note)) {
794
+        	$this->close_note=trim($this->close_note);
795
+        }
796
+        if (isset($this->tva)) {
797
+        	$this->tva=trim($this->tva);
798
+        }
799
+        if (isset($this->localtax1)) {
800
+        	$this->localtax1=trim($this->localtax1);
801
+        }
802
+        if (isset($this->localtax2)) {
803
+        	$this->localtax2=trim($this->localtax2);
804
+        }
805
+        if (empty($this->total_ht)) {
806
+        	$this->total_ht=0;
807
+        }
808
+        if (empty($this->total_tva)) {
809
+        	$this->total_tva=0;
810
+        }
758 811
         //	if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
759 812
         //	if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
760
-        if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
761
-        if (isset($this->statut)) $this->statut=(int) $this->statut;
762
-        if (isset($this->author)) $this->author=trim($this->author);
763
-        if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
764
-        if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
765
-        if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
766
-        if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
767
-        if (isset($this->note_private)) $this->note=trim($this->note_private);
768
-        if (isset($this->note_public)) $this->note_public=trim($this->note_public);
769
-        if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
770
-        if (isset($this->import_key)) $this->import_key=trim($this->import_key);
813
+        if (isset($this->total_ttc)) {
814
+        	$this->total_ttc=trim($this->total_ttc);
815
+        }
816
+        if (isset($this->statut)) {
817
+        	$this->statut=(int) $this->statut;
818
+        }
819
+        if (isset($this->author)) {
820
+        	$this->author=trim($this->author);
821
+        }
822
+        if (isset($this->fk_user_valid)) {
823
+        	$this->fk_user_valid=trim($this->fk_user_valid);
824
+        }
825
+        if (isset($this->fk_facture_source)) {
826
+        	$this->fk_facture_source=trim($this->fk_facture_source);
827
+        }
828
+        if (isset($this->fk_project)) {
829
+        	$this->fk_project=trim($this->fk_project);
830
+        }
831
+        if (isset($this->cond_reglement_id)) {
832
+        	$this->cond_reglement_id=trim($this->cond_reglement_id);
833
+        }
834
+        if (isset($this->note_private)) {
835
+        	$this->note=trim($this->note_private);
836
+        }
837
+        if (isset($this->note_public)) {
838
+        	$this->note_public=trim($this->note_public);
839
+        }
840
+        if (isset($this->model_pdf)) {
841
+        	$this->model_pdf=trim($this->model_pdf);
842
+        }
843
+        if (isset($this->import_key)) {
844
+        	$this->import_key=trim($this->import_key);
845
+        }
771 846
 
772 847
 
773 848
         // Check parameters
@@ -782,7 +857,9 @@  discard block
 block discarded – undo
782 857
         $sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").",";
783 858
         $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
784 859
         $sql.= " datef=".(dol_strlen($this->date)!=0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
785
-        if (dol_strlen($this->tms) != 0) $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
860
+        if (dol_strlen($this->tms) != 0) {
861
+        	$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
862
+        }
786 863
         $sql.= " libelle=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
787 864
         $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
788 865
         $sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
@@ -830,7 +907,9 @@  discard block
 block discarded – undo
830 907
             {
831 908
                 // Call trigger
832 909
                 $result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user);
833
-                if ($result < 0) $error++;
910
+                if ($result < 0) {
911
+                	$error++;
912
+                }
834 913
                 // End call triggers
835 914
             }
836 915
         }
@@ -845,8 +924,7 @@  discard block
 block discarded – undo
845 924
             }
846 925
             $this->db->rollback();
847 926
             return -1*$error;
848
-        }
849
-        else
927
+        } else
850 928
         {
851 929
             $this->db->commit();
852 930
             return 1;
@@ -899,8 +977,7 @@  discard block
 block discarded – undo
899 977
                 if (! $resql2) {
900 978
                 	$error++;
901 979
                 }
902
-            }
903
-            else {
980
+            } else {
904 981
             	$error++;
905 982
             }
906 983
         }
@@ -909,14 +986,18 @@  discard block
 block discarded – undo
909 986
 		{
910 987
 			// Delete linked object
911 988
 			$res = $this->deleteObjectLinked();
912
-			if ($res < 0) $error++;
989
+			if ($res < 0) {
990
+				$error++;
991
+			}
913 992
 		}
914 993
 
915 994
         if (! $error)
916 995
         {
917 996
         	// Delete linked object
918 997
         	$res = $this->deleteObjectLinked();
919
-        	if ($res < 0) $error++;
998
+        	if ($res < 0) {
999
+        		$error++;
1000
+        	}
920 1001
         }
921 1002
 
922 1003
         if (! $error)
@@ -931,9 +1012,11 @@  discard block
 block discarded – undo
931 1012
         		$file = $dir . "/" . $ref . ".pdf";
932 1013
         		if (file_exists($file))
933 1014
         		{
934
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1015
+        			if (! dol_delete_file($file,0,0,0,$this)) {
1016
+        				// For triggers
935 1017
         			{
936 1018
         				$this->error='ErrorFailToDeleteFile';
1019
+        			}
937 1020
         				$error++;
938 1021
         			}
939 1022
         		}
@@ -951,9 +1034,11 @@  discard block
 block discarded – undo
951 1034
         }
952 1035
 
953 1036
         // Remove extrafields
954
-        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1037
+        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
1038
+        	// For avoid conflicts if trigger used
955 1039
         {
956 1040
         	$result=$this->deleteExtraFields();
1041
+        }
957 1042
         	if ($result < 0)
958 1043
         	{
959 1044
         		$error++;
@@ -966,8 +1051,7 @@  discard block
 block discarded – undo
966 1051
         	dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
967 1052
         	$this->db->commit();
968 1053
         	return 1;
969
-        }
970
-        else
1054
+        } else
971 1055
         {
972 1056
         	$this->error=$this->db->lasterror();
973 1057
         	$this->db->rollback();
@@ -1001,10 +1085,11 @@  discard block
 block discarded – undo
1001 1085
         {
1002 1086
             // Call trigger
1003 1087
             $result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user);
1004
-            if ($result < 0) $error++;
1088
+            if ($result < 0) {
1089
+            	$error++;
1090
+            }
1005 1091
             // End call triggers
1006
-        }
1007
-        else
1092
+        } else
1008 1093
         {
1009 1094
             $error++;
1010 1095
             $this->error=$this->db->error();
@@ -1015,8 +1100,7 @@  discard block
 block discarded – undo
1015 1100
         {
1016 1101
             $this->db->commit();
1017 1102
             return 1;
1018
-        }
1019
-        else
1103
+        } else
1020 1104
         {
1021 1105
             $this->db->rollback();
1022 1106
             return -1;
@@ -1049,10 +1133,11 @@  discard block
 block discarded – undo
1049 1133
         {
1050 1134
             // Call trigger
1051 1135
             $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user);
1052
-            if ($result < 0) $error++;
1136
+            if ($result < 0) {
1137
+            	$error++;
1138
+            }
1053 1139
             // End call triggers
1054
-        }
1055
-        else
1140
+        } else
1056 1141
         {
1057 1142
             $error++;
1058 1143
             $this->error=$this->db->lasterror();
@@ -1063,8 +1148,7 @@  discard block
 block discarded – undo
1063 1148
         {
1064 1149
             $this->db->commit();
1065 1150
             return 1;
1066
-        }
1067
-        else
1151
+        } else
1068 1152
         {
1069 1153
             $this->db->rollback();
1070 1154
             return -1;
@@ -1095,9 +1179,11 @@  discard block
 block discarded – undo
1095 1179
         $this->fetch_lines();
1096 1180
 
1097 1181
         // Check parameters
1098
-        if ($this->statut > self::STATUS_DRAFT)	// This is to avoid to validate twice (avoid errors on logs and stock management)
1182
+        if ($this->statut > self::STATUS_DRAFT) {
1183
+        	// This is to avoid to validate twice (avoid errors on logs and stock management)
1099 1184
         {
1100 1185
             dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
1186
+        }
1101 1187
             return 0;
1102 1188
         }
1103 1189
         if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
@@ -1119,12 +1205,12 @@  discard block
 block discarded – undo
1119 1205
         if ($force_number)
1120 1206
         {
1121 1207
             $num = $force_number;
1122
-        }
1123
-        else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
1208
+        } else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) {
1209
+        	// empty should not happened, but when it occurs, the test save life
1124 1210
         {
1125 1211
             $num = $this->getNextNumRef($this->thirdparty);
1126 1212
         }
1127
-        else
1213
+        } else
1128 1214
 		{
1129 1215
             $num = $this->ref;
1130 1216
         }
@@ -1154,7 +1240,9 @@  discard block
 block discarded – undo
1154 1240
 						$mouvP->origin = &$this;
1155 1241
                         // We increase stock for product
1156 1242
                         $up_ht_disc=$this->lines[$i]->pu_ht;
1157
-                        if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1243
+                        if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) {
1244
+                        	$up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1245
+                        }
1158 1246
                         $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr",$num));
1159 1247
                         if ($result < 0) { $error++; }
1160 1248
                         unset($this->line);
@@ -1167,7 +1255,9 @@  discard block
 block discarded – undo
1167 1255
             {
1168 1256
                 // Call trigger
1169 1257
                 $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
1170
-                if ($result < 0) $error++;
1258
+                if ($result < 0) {
1259
+                	$error++;
1260
+                }
1171 1261
                 // End call triggers
1172 1262
             }
1173 1263
 
@@ -1219,14 +1309,12 @@  discard block
 block discarded – undo
1219 1309
             {
1220 1310
                 $this->db->commit();
1221 1311
                 return 1;
1222
-            }
1223
-            else
1312
+            } else
1224 1313
             {
1225 1314
                 $this->db->rollback();
1226 1315
                 return -1;
1227 1316
             }
1228
-        }
1229
-        else
1317
+        } else
1230 1318
         {
1231 1319
             $this->error=$this->db->error();
1232 1320
             $this->db->rollback();
@@ -1286,21 +1374,21 @@  discard block
 block discarded – undo
1286 1374
             {
1287 1375
                 // Call trigger
1288 1376
                 $result=$this->call_trigger('BILL_SUPPLIER_UNVALIDATE',$user);
1289
-                if ($result < 0) $error++;
1377
+                if ($result < 0) {
1378
+                	$error++;
1379
+                }
1290 1380
                 // End call triggers
1291 1381
             }
1292 1382
             if ($error == 0)
1293 1383
             {
1294 1384
                 $this->db->commit();
1295 1385
                 return 1;
1296
-            }
1297
-            else
1386
+            } else
1298 1387
             {
1299 1388
                 $this->db->rollback();
1300 1389
                 return -1;
1301 1390
             }
1302
-        }
1303
-        else
1391
+        } else
1304 1392
         {
1305 1393
             $this->error=$this->db->error();
1306 1394
             $this->db->rollback();
@@ -1347,14 +1435,30 @@  discard block
 block discarded – undo
1347 1435
         global $mysoc;
1348 1436
 
1349 1437
         // Clean parameters
1350
-        if (empty($remise_percent)) $remise_percent=0;
1351
-        if (empty($qty)) $qty=0;
1352
-        if (empty($info_bits)) $info_bits=0;
1353
-        if (empty($rang)) $rang=0;
1354
-        if (empty($ventil)) $ventil=0;
1355
-        if (empty($txtva)) $txtva=0;
1356
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1357
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1438
+        if (empty($remise_percent)) {
1439
+        	$remise_percent=0;
1440
+        }
1441
+        if (empty($qty)) {
1442
+        	$qty=0;
1443
+        }
1444
+        if (empty($info_bits)) {
1445
+        	$info_bits=0;
1446
+        }
1447
+        if (empty($rang)) {
1448
+        	$rang=0;
1449
+        }
1450
+        if (empty($ventil)) {
1451
+        	$ventil=0;
1452
+        }
1453
+        if (empty($txtva)) {
1454
+        	$txtva=0;
1455
+        }
1456
+        if (empty($txlocaltax1)) {
1457
+        	$txlocaltax1=0;
1458
+        }
1459
+        if (empty($txlocaltax2)) {
1460
+        	$txlocaltax2=0;
1461
+        }
1358 1462
 
1359 1463
         $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1360 1464
 
@@ -1388,7 +1492,9 @@  discard block
 block discarded – undo
1388 1492
 		$pu_ht_devise = $tabprice[19];
1389 1493
 
1390 1494
         // Check parameters
1391
-        if ($type < 0) return -1;
1495
+        if ($type < 0) {
1496
+        	return -1;
1497
+        }
1392 1498
 
1393 1499
         // Insert line
1394 1500
         $this->line=new SupplierInvoiceLine($this->db);
@@ -1442,7 +1548,9 @@  discard block
 block discarded – undo
1442 1548
         if ($result > 0)
1443 1549
         {
1444 1550
             // Reorder if child line
1445
-            if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1551
+            if (! empty($fk_parent_line)) {
1552
+            	$this->line_order(true,'DESC');
1553
+            }
1446 1554
 
1447 1555
             // Mise a jour informations denormalisees au niveau de la facture meme
1448 1556
             $result=$this->update_price(1,'auto',0,$this->thirdparty);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
@@ -1450,15 +1558,13 @@  discard block
 block discarded – undo
1450 1558
             {
1451 1559
                 $this->db->commit();
1452 1560
                 return $this->line->id;
1453
-            }
1454
-            else
1561
+            } else
1455 1562
             {
1456 1563
                 $this->error=$this->db->error();
1457 1564
                 $this->db->rollback();
1458 1565
                 return -1;
1459 1566
             }
1460
-        }
1461
-        else
1567
+        } else
1462 1568
         {
1463 1569
             $this->error=$this->line->error;
1464 1570
             $this->db->rollback();
@@ -1502,12 +1608,20 @@  discard block
 block discarded – undo
1502 1608
 
1503 1609
         // Check parameters
1504 1610
         //if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
1505
-        if ($type < 0) return -1;
1611
+        if ($type < 0) {
1612
+        	return -1;
1613
+        }
1506 1614
 
1507 1615
         // Clean parameters
1508
-		if (empty($vatrate)) $vatrate=0;
1509
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1510
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1616
+		if (empty($vatrate)) {
1617
+			$vatrate=0;
1618
+		}
1619
+        if (empty($txlocaltax1)) {
1620
+        	$txlocaltax1=0;
1621
+        }
1622
+        if (empty($txlocaltax2)) {
1623
+        	$txlocaltax2=0;
1624
+        }
1511 1625
 
1512 1626
         $txlocaltax1=price2num($txlocaltax1);
1513 1627
         $txlocaltax2=price2num($txlocaltax2);
@@ -1545,15 +1659,16 @@  discard block
 block discarded – undo
1545 1659
         $multicurrency_total_ttc = $tabprice[18];
1546 1660
 		$pu_ht_devise = $tabprice[19];
1547 1661
 
1548
-        if (empty($info_bits)) $info_bits=0;
1662
+        if (empty($info_bits)) {
1663
+        	$info_bits=0;
1664
+        }
1549 1665
 
1550 1666
         if ($idproduct)
1551 1667
         {
1552 1668
             $product=new Product($this->db);
1553 1669
             $result=$product->fetch($idproduct);
1554 1670
             $product_type = $product->type;
1555
-        }
1556
-        else
1671
+        } else
1557 1672
         {
1558 1673
             $product_type = $type;
1559 1674
         }
@@ -1680,8 +1795,7 @@  discard block
 block discarded – undo
1680 1795
                 //$this->date_validation   = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
1681 1796
             }
1682 1797
             $this->db->free($result);
1683
-        }
1684
-        else
1798
+        } else
1685 1799
         {
1686 1800
             dol_print_error($this->db);
1687 1801
         }
@@ -1710,7 +1824,9 @@  discard block
 block discarded – undo
1710 1824
 		$sql.= " AND f.paye = 0";					// Pas classee payee completement
1711 1825
 		$sql.= " AND pf.fk_paiementfourn IS NULL";	// Aucun paiement deja fait
1712 1826
 		$sql.= " AND ff.fk_statut IS NULL";			// Renvoi vrai si pas facture de remplacement
1713
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
1827
+		if ($socid > 0) {
1828
+			$sql.=" AND f.fk_soc = ".$socid;
1829
+		}
1714 1830
 		$sql.= " ORDER BY f.ref";
1715 1831
 
1716 1832
 		dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG);
@@ -1725,8 +1841,7 @@  discard block
 block discarded – undo
1725 1841
 			}
1726 1842
 			//print_r($return);
1727 1843
 			return $return;
1728
-		}
1729
-		else
1844
+		} else
1730 1845
 		{
1731 1846
 			$this->error=$this->db->error();
1732 1847
 			return -1;
@@ -1755,7 +1870,9 @@  discard block
 block discarded – undo
1755 1870
 		$sql.= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
1756 1871
 		$sql.= " AND ff.type IS NULL";									// Renvoi vrai si pas facture de remplacement
1757 1872
 		$sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE;				// Type non 2 si facture non avoir
1758
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
1873
+		if ($socid > 0) {
1874
+			$sql.=" AND f.fk_soc = ".$socid;
1875
+		}
1759 1876
 		$sql.= " ORDER BY f.ref";
1760 1877
 
1761 1878
 		dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG);
@@ -1765,8 +1882,12 @@  discard block
 block discarded – undo
1765 1882
 			while ($obj=$this->db->fetch_object($resql))
1766 1883
 			{
1767 1884
 				$qualified=0;
1768
-				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified=1;
1769
-				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified=1;
1885
+				if ($obj->fk_statut == self::STATUS_VALIDATED) {
1886
+					$qualified=1;
1887
+				}
1888
+				if ($obj->fk_statut == self::STATUS_CLOSED) {
1889
+					$qualified=1;
1890
+				}
1770 1891
 				if ($qualified)
1771 1892
 				{
1772 1893
 					$paymentornot=($obj->fk_paiementfourn?1:0);
@@ -1775,8 +1896,7 @@  discard block
 block discarded – undo
1775 1896
 			}
1776 1897
 
1777 1898
 			return $return;
1778
-		}
1779
-		else
1899
+		} else
1780 1900
 		{
1781 1901
 			$this->error=$this->db->error();
1782 1902
 			return -1;
@@ -1795,12 +1915,18 @@  discard block
 block discarded – undo
1795 1915
 
1796 1916
         $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut';
1797 1917
         $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
1798
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1918
+        if (!$user->rights->societe->client->voir && !$user->societe_id) {
1919
+        	$sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1920
+        }
1799 1921
         $sql.= ' WHERE ff.paye=0';
1800 1922
         $sql.= ' AND ff.fk_statut > 0';
1801 1923
         $sql.= " AND ff.entity = ".$conf->entity;
1802
-        if ($user->societe_id) $sql.=' AND ff.fk_soc = '.$user->societe_id;
1803
-        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1924
+        if ($user->societe_id) {
1925
+        	$sql.=' AND ff.fk_soc = '.$user->societe_id;
1926
+        }
1927
+        if (!$user->rights->societe->client->voir && !$user->societe_id) {
1928
+        	$sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
1929
+        }
1804 1930
 
1805 1931
         $resql=$this->db->query($sql);
1806 1932
         if ($resql)
@@ -1830,8 +1956,7 @@  discard block
 block discarded – undo
1830 1956
             }
1831 1957
             $this->db->free($resql);
1832 1958
             return $response;
1833
-        }
1834
-        else
1959
+        } else
1835 1960
         {
1836 1961
             dol_print_error($this->db);
1837 1962
             $this->error=$this->db->error();
@@ -1858,42 +1983,75 @@  discard block
 block discarded – undo
1858 1983
 
1859 1984
         $result='';
1860 1985
 
1861
-        if ($option == 'document')	$url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
1862
-        else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
1986
+        if ($option == 'document') {
1987
+        	$url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
1988
+        } else {
1989
+        	$url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
1990
+        }
1863 1991
 
1864
-        if ($short) return $url;
1992
+        if ($short) {
1993
+        	return $url;
1994
+        }
1865 1995
 
1866 1996
         if ($option !== 'nolink')
1867 1997
         {
1868 1998
         	// Add param to save lastsearch_values or not
1869 1999
         	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1870
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1871
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
2000
+        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
2001
+        		$add_save_lastsearch_values=1;
2002
+        	}
2003
+        	if ($add_save_lastsearch_values) {
2004
+        		$url.='&save_lastsearch_values=1';
2005
+        	}
1872 2006
         }
1873 2007
 
1874 2008
         $picto='bill';
1875
-        if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice
1876
-        if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note
1877
-        if ($this->type == self::TYPE_DEPOSIT)     $picto.='d'; // Deposit invoice
2009
+        if ($this->type == self::TYPE_REPLACEMENT) {
2010
+        	$picto.='r';
2011
+        }
2012
+        // Replacement invoice
2013
+        if ($this->type == self::TYPE_CREDIT_NOTE) {
2014
+        	$picto.='a';
2015
+        }
2016
+        // Credit note
2017
+        if ($this->type == self::TYPE_DEPOSIT) {
2018
+        	$picto.='d';
2019
+        }
2020
+        // Deposit invoice
1878 2021
 
1879 2022
         $label = '<u>' . $langs->trans("ShowSupplierInvoice") . '</u>';
1880
-        if (! empty($this->ref))
1881
-            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1882
-        if (! empty($this->ref_supplier))
1883
-            $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
1884
-        if (! empty($this->total_ht))
1885
-            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1886
-        if (! empty($this->total_tva))
1887
-            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1888
-        if (! empty($this->total_ttc))
1889
-            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1890
-        if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1891
-        if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1892
-        if ($this->type == self::TYPE_DEPOSIT)     $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1893
-        if ($moretitle) $label.=' - '.$moretitle;
2023
+        if (! empty($this->ref)) {
2024
+                    $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
2025
+        }
2026
+        if (! empty($this->ref_supplier)) {
2027
+                    $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
2028
+        }
2029
+        if (! empty($this->total_ht)) {
2030
+                    $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2031
+        }
2032
+        if (! empty($this->total_tva)) {
2033
+                    $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2034
+        }
2035
+        if (! empty($this->total_ttc)) {
2036
+                    $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2037
+        }
2038
+        if ($this->type == self::TYPE_REPLACEMENT) {
2039
+        	$label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
2040
+        }
2041
+        if ($this->type == self::TYPE_CREDIT_NOTE) {
2042
+        	$label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
2043
+        }
2044
+        if ($this->type == self::TYPE_DEPOSIT) {
2045
+        	$label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
2046
+        }
2047
+        if ($moretitle) {
2048
+        	$label.=' - '.$moretitle;
2049
+        }
1894 2050
 
1895 2051
         $ref=$this->ref;
1896
-        if (empty($ref)) $ref=$this->id;
2052
+        if (empty($ref)) {
2053
+        	$ref=$this->id;
2054
+        }
1897 2055
 
1898 2056
         $linkclose='';
1899 2057
         if (empty($notooltip))
@@ -1911,7 +2069,9 @@  discard block
 block discarded – undo
1911 2069
         $linkstart.=$linkclose.'>';
1912 2070
         $linkend='</a>';
1913 2071
 
1914
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
2072
+        if ($withpicto) {
2073
+        	$result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' ');
2074
+        }
1915 2075
         $result.=$linkstart.($max?dol_trunc($ref,$max):$ref).$linkend;
1916 2076
         return $result;
1917 2077
     }
@@ -1930,7 +2090,9 @@  discard block
 block discarded – undo
1930 2090
         $langs->load("orders");
1931 2091
 
1932 2092
         // Clean parameters (if not defined or using deprecated value)
1933
-        if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
2093
+        if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) {
2094
+        	$conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
2095
+        }
1934 2096
 
1935 2097
         $mybool=false;
1936 2098
 
@@ -1961,8 +2123,7 @@  discard block
 block discarded – undo
1961 2123
         if ($numref != "")
1962 2124
         {
1963 2125
         	return $numref;
1964
-        }
1965
-        else
2126
+        } else
1966 2127
        {
1967 2128
        		$this->error=$obj->error;
1968 2129
         	//dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error);
@@ -2042,8 +2203,7 @@  discard block
 block discarded – undo
2042 2203
 				    $line->total_ttc=59.8;
2043 2204
 				    $line->total_tva=9.8;
2044 2205
 	    			$line->remise_percent=50;
2045
-				}
2046
-				else
2206
+				} else
2047 2207
 				{
2048 2208
 				    $line->total_ht=100;
2049 2209
 				    $line->total_ttc=119.6;
@@ -2107,8 +2267,7 @@  discard block
 block discarded – undo
2107 2267
 			}
2108 2268
             $this->db->free($resql);
2109 2269
 			return 1;
2110
-		}
2111
-		else
2270
+		} else
2112 2271
 		{
2113 2272
 			dol_print_error($this->db);
2114 2273
 			$this->error=$this->db->error();
@@ -2156,10 +2315,12 @@  discard block
 block discarded – undo
2156 2315
         // Loop on each line of new invoice
2157 2316
         foreach($object->lines as $i => $line)
2158 2317
         {
2159
-            if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
2318
+            if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) {
2319
+            	// We do not clone line of discounts
2160 2320
             {
2161 2321
                 unset($object->lines[$i]);
2162 2322
             }
2323
+            }
2163 2324
         }
2164 2325
 
2165 2326
         // Create clone
@@ -2186,8 +2347,7 @@  discard block
 block discarded – undo
2186 2347
         {
2187 2348
             $this->db->commit();
2188 2349
             return $object->id;
2189
-        }
2190
-        else
2350
+        } else
2191 2351
         {
2192 2352
             $this->db->rollback();
2193 2353
             return -1;
@@ -2216,8 +2376,7 @@  discard block
 block discarded – undo
2216 2376
 			if (! empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF))
2217 2377
 			{
2218 2378
 				$modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF;
2219
-			}
2220
-			else
2379
+			} else
2221 2380
 			{
2222 2381
 				$modele = '';       // No default value. For supplier invoice, we allow to disable all PDF generation
2223 2382
 			}
@@ -2226,8 +2385,7 @@  discard block
 block discarded – undo
2226 2385
 		if (empty($modele))
2227 2386
 		{
2228 2387
 		    return 0;
2229
-		}
2230
-		else
2388
+		} else
2231 2389
 		{
2232 2390
             $modelpath = "core/modules/supplier_invoice/pdf/";
2233 2391
 
@@ -2525,8 +2683,7 @@  discard block
 block discarded – undo
2525 2683
 		{
2526 2684
 			$this->db->commit();
2527 2685
 			return 1;
2528
-		}
2529
-		else
2686
+		} else
2530 2687
 		{
2531 2688
 			$this->db->rollback();
2532 2689
 			return -1;
@@ -2547,17 +2704,27 @@  discard block
 block discarded – undo
2547 2704
 		$qty  = price2num($this->qty);
2548 2705
 
2549 2706
 		// Check parameters
2550
-		if (empty($this->qty)) $this->qty=0;
2707
+		if (empty($this->qty)) {
2708
+			$this->qty=0;
2709
+		}
2551 2710
 
2552 2711
 		if ($this->product_type < 0) {
2553 2712
 			return -1;
2554 2713
 		}
2555 2714
 
2556 2715
 		// Clean parameters
2557
-		if (empty($this->remise_percent)) $this->remise_percent = 0;
2558
-		if (empty($this->tva_tx))  		  $this->tva_tx = 0;
2559
-		if (empty($this->localtax1_tx))   $this->localtax1_tx = 0;
2560
-		if (empty($this->localtax2_tx))   $this->localtax2_tx = 0;
2716
+		if (empty($this->remise_percent)) {
2717
+			$this->remise_percent = 0;
2718
+		}
2719
+		if (empty($this->tva_tx)) {
2720
+			$this->tva_tx = 0;
2721
+		}
2722
+		if (empty($this->localtax1_tx)) {
2723
+			$this->localtax1_tx = 0;
2724
+		}
2725
+		if (empty($this->localtax2_tx)) {
2726
+			$this->localtax2_tx = 0;
2727
+		}
2561 2728
 
2562 2729
 		$this->db->begin();
2563 2730
 
@@ -2616,10 +2783,12 @@  discard block
 block discarded – undo
2616 2783
 		$this->rowid = $this->id;
2617 2784
 		$error = 0;
2618 2785
 
2619
-		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2786
+		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
2787
+			// For avoid conflicts if trigger used
2620 2788
 		{
2621 2789
 			if ($this->insertExtraFields() < 0) {
2622 2790
 				$error++;
2791
+		}
2623 2792
 			}
2624 2793
 		}
2625 2794
 
@@ -2660,26 +2829,64 @@  discard block
 block discarded – undo
2660 2829
 
2661 2830
         // Clean parameters
2662 2831
         $this->desc=trim($this->desc);
2663
-        if (empty($this->tva_tx)) $this->tva_tx=0;
2664
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
2665
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
2666
-        if (empty($this->localtax1_type)) $this->localtax1_type='0';
2667
-        if (empty($this->localtax2_type)) $this->localtax2_type='0';
2668
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
2669
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
2670
-        if (empty($this->rang)) $this->rang=0;
2671
-        if (empty($this->remise_percent)) $this->remise_percent=0;
2672
-        if (empty($this->info_bits)) $this->info_bits=0;
2673
-        if (empty($this->subprice)) $this->subprice=0;
2674
-        if (empty($this->special_code)) $this->special_code=0;
2675
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
2676
-        if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
2677
-
2678
-        if (empty($this->pa_ht)) $this->pa_ht=0;
2679
-        if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
2680
-        if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
2681
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
2682
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
2832
+        if (empty($this->tva_tx)) {
2833
+        	$this->tva_tx=0;
2834
+        }
2835
+        if (empty($this->localtax1_tx)) {
2836
+        	$this->localtax1_tx=0;
2837
+        }
2838
+        if (empty($this->localtax2_tx)) {
2839
+        	$this->localtax2_tx=0;
2840
+        }
2841
+        if (empty($this->localtax1_type)) {
2842
+        	$this->localtax1_type='0';
2843
+        }
2844
+        if (empty($this->localtax2_type)) {
2845
+        	$this->localtax2_type='0';
2846
+        }
2847
+        if (empty($this->total_localtax1)) {
2848
+        	$this->total_localtax1=0;
2849
+        }
2850
+        if (empty($this->total_localtax2)) {
2851
+        	$this->total_localtax2=0;
2852
+        }
2853
+        if (empty($this->rang)) {
2854
+        	$this->rang=0;
2855
+        }
2856
+        if (empty($this->remise_percent)) {
2857
+        	$this->remise_percent=0;
2858
+        }
2859
+        if (empty($this->info_bits)) {
2860
+        	$this->info_bits=0;
2861
+        }
2862
+        if (empty($this->subprice)) {
2863
+        	$this->subprice=0;
2864
+        }
2865
+        if (empty($this->special_code)) {
2866
+        	$this->special_code=0;
2867
+        }
2868
+        if (empty($this->fk_parent_line)) {
2869
+        	$this->fk_parent_line=0;
2870
+        }
2871
+        if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
2872
+        	$this->situation_percent = 100;
2873
+        }
2874
+
2875
+        if (empty($this->pa_ht)) {
2876
+        	$this->pa_ht=0;
2877
+        }
2878
+        if (empty($this->multicurrency_subprice)) {
2879
+        	$this->multicurrency_subprice=0;
2880
+        }
2881
+        if (empty($this->multicurrency_total_ht)) {
2882
+        	$this->multicurrency_total_ht=0;
2883
+        }
2884
+        if (empty($this->multicurrency_total_tva)) {
2885
+        	$this->multicurrency_total_tva=0;
2886
+        }
2887
+        if (empty($this->multicurrency_total_ttc)) {
2888
+        	$this->multicurrency_total_ttc=0;
2889
+        }
2683 2890
 
2684 2891
 
2685 2892
         // Check parameters
@@ -2754,9 +2961,11 @@  discard block
 block discarded – undo
2754 2961
             $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
2755 2962
             $this->rowid=$this->id;
2756 2963
 
2757
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2964
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
2965
+            	// For avoid conflicts if trigger used
2758 2966
             {
2759 2967
                 $result=$this->insertExtraFields();
2968
+            }
2760 2969
                 if ($result < 0)
2761 2970
                 {
2762 2971
                     $error++;
@@ -2778,8 +2987,7 @@  discard block
 block discarded – undo
2778 2987
             $this->db->commit();
2779 2988
             return $this->id;
2780 2989
 
2781
-        }
2782
-        else
2990
+        } else
2783 2991
         {
2784 2992
             $this->error=$this->db->error();
2785 2993
             $this->db->rollback();
@@ -2811,8 +3019,7 @@  discard block
 block discarded – undo
2811 3019
         {
2812 3020
             $this->db->commit();
2813 3021
             return 1;
2814
-        }
2815
-        else
3022
+        } else
2816 3023
         {
2817 3024
             $this->error=$this->db->error();
2818 3025
             $this->db->rollback();
Please login to merge, or discard this patch.
htdocs/core/modules/product/doc/pdf_standard.modules.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -570,8 +570,8 @@
 block discarded – undo
570 570
 	 *   Show table for lines
571 571
 	 *
572 572
 	 *   @param		TCPDF		$pdf     		Object PDF
573
-	 *   @param		string		$tab_top		Top position of table
574
-	 *   @param		string		$tab_height		Height of table (rectangle)
573
+	 *   @param		integer		$tab_top		Top position of table
574
+	 *   @param		integer		$tab_height		Height of table (rectangle)
575 575
 	 *   @param		int			$nexY			Y (not used)
576 576
 	 *   @param		Translate	$outputlangs	Langs object
577 577
 	 *   @param		int			$hidetop		1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title
Please login to merge, or discard this patch.
Braces   +43 added lines, -27 removed lines patch added patch discarded remove patch
@@ -113,7 +113,10 @@  discard block
 block discarded – undo
113 113
 
114 114
 		// Recupere emetteur
115 115
 		$this->emetteur=$mysoc;
116
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
116
+		if (! $this->emetteur->country_code) {
117
+			$this->emetteur->country_code=substr($langs->defaultlang,-2);
118
+		}
119
+		// By default if not defined
117 120
 	}
118 121
 
119 122
 
@@ -132,9 +135,13 @@  discard block
 block discarded – undo
132 135
 	{
133 136
 		global $user,$langs,$conf,$mysoc,$db,$hookmanager;
134 137
 
135
-		if (! is_object($outputlangs)) $outputlangs=$langs;
138
+		if (! is_object($outputlangs)) {
139
+			$outputlangs=$langs;
140
+		}
136 141
 		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
137
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
142
+		if (! empty($conf->global->MAIN_USE_FPDF)) {
143
+			$outputlangs->charset_output='ISO-8859-1';
144
+		}
138 145
 
139 146
 		$outputlangs->load("main");
140 147
 		$outputlangs->load("dict");
@@ -153,8 +160,7 @@  discard block
 block discarded – undo
153 160
 			{
154 161
 				$dir = $conf->produit->dir_output;
155 162
 				$file = $dir . "/SPECIMEN.pdf";
156
-			}
157
-			else
163
+			} else
158 164
 			{
159 165
 				$objectref = dol_sanitizeFileName($object->ref);
160 166
 				$dir = $conf->produit->dir_output . "/" . $objectref;
@@ -218,14 +224,18 @@  discard block
 block discarded – undo
218 224
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
219 225
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
220 226
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order")." ".$outputlangs->convToOutputCharset($object->thirdparty->name));
221
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
227
+				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
228
+					$pdf->SetCompression(false);
229
+				}
222 230
 
223 231
 				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
224 232
 
225 233
 
226 234
 				// New page
227 235
 				$pdf->AddPage();
228
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
236
+				if (! empty($tplidx)) {
237
+					$pdf->useTemplate($tplidx);
238
+				}
229 239
 				$pagenb++;
230 240
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
231 241
 				$pdf->SetFont('','', $default_font_size - 1);
@@ -282,7 +292,9 @@  discard block
 block discarded – undo
282 292
 						$salereparray=$object->thirdparty->getSalesRepresentatives($user);
283 293
 						$salerepobj=new User($this->db);
284 294
 						$salerepobj->fetch($salereparray[0]['id']);
285
-						if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
295
+						if (! empty($salerepobj->signature)) {
296
+							$notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
297
+						}
286 298
 					}
287 299
 				}
288 300
 				if ($notetoshow)
@@ -300,8 +312,7 @@  discard block
 block discarded – undo
300 312
 
301 313
 					$tab_height = $tab_height - $height_note;
302 314
 					$tab_top = $nexY+6;
303
-				}
304
-				else
315
+				} else
305 316
 				{
306 317
 					$height_note=0;
307 318
 				}
@@ -527,7 +538,9 @@  discard block
 block discarded – undo
527 538
 
528 539
 				// Pied de page
529 540
 				$this->_pagefoot($pdf,$object,$outputlangs);
530
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
541
+				if (method_exists($pdf,'AliasNbPages')) {
542
+					$pdf->AliasNbPages();
543
+				}
531 544
 
532 545
 				$pdf->Close();
533 546
 
@@ -539,20 +552,19 @@  discard block
 block discarded – undo
539 552
 				global $action;
540 553
 				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
541 554
 
542
-				if (! empty($conf->global->MAIN_UMASK))
543
-					@chmod($file, octdec($conf->global->MAIN_UMASK));
555
+				if (! empty($conf->global->MAIN_UMASK)) {
556
+									@chmod($file, octdec($conf->global->MAIN_UMASK));
557
+				}
544 558
 
545 559
 				$this->result = array('fullpath'=>$file);
546 560
 				
547 561
 				return 1;   // Pas d'erreur
548
-			}
549
-			else
562
+			} else
550 563
 			{
551 564
 				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
552 565
 				return 0;
553 566
 			}
554
-		}
555
-		else
567
+		} else
556 568
 		{
557 569
 			$this->error=$langs->trans("ErrorConstantNotDefined","PRODUCT_OUTPUTDIR");
558 570
 			return 0;
@@ -579,7 +591,9 @@  discard block
 block discarded – undo
579 591
 	
580 592
 	    // Force to disable hidetop and hidebottom
581 593
 	    $hidebottom=0;
582
-	    if ($hidetop) $hidetop=-1;
594
+	    if ($hidetop) {
595
+	    	$hidetop=-1;
596
+	    }
583 597
 	
584 598
 	    $currency = !empty($currency) ? $currency : $conf->currency;
585 599
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
@@ -595,7 +609,9 @@  discard block
 block discarded – undo
595 609
 	        $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
596 610
 	
597 611
 	        //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
598
-	        if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
612
+	        if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) {
613
+	        	$pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
614
+	        }
599 615
 	    }
600 616
 	
601 617
 	    $pdf->SetDrawColor(128,128,128);
@@ -636,8 +652,7 @@  discard block
 block discarded – undo
636 652
 	        if($conf->global->PRODUCT_USE_UNITS)
637 653
 	        {
638 654
 	            $pdf->MultiCell($this->posxunit-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
639
-	        }
640
-	        else
655
+	        } else
641 656
 	        {
642 657
 	            $pdf->MultiCell($this->posxdiscount-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
643 658
 	        }
@@ -694,8 +709,11 @@  discard block
 block discarded – undo
694 709
 	    $outputlangs->load("orders");
695 710
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
696 711
 	
697
-	    if ($object->type == 1) $titlekey='ServiceSheet';
698
-	    else $titlekey='ProductSheet';
712
+	    if ($object->type == 1) {
713
+	    	$titlekey='ServiceSheet';
714
+	    } else {
715
+	    	$titlekey='ProductSheet';
716
+	    }
699 717
 	        
700 718
 	    pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
701 719
 	
@@ -721,16 +739,14 @@  discard block
 block discarded – undo
721 739
 	        {
722 740
 	            $height=pdf_getHeightForLogo($logo);
723 741
 	            $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
724
-	        }
725
-	        else
742
+	        } else
726 743
 	        {
727 744
 	            $pdf->SetTextColor(200,0,0);
728 745
 	            $pdf->SetFont('','B', $default_font_size -2);
729 746
 	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
730 747
 	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
731 748
 	        }
732
-	    }
733
-	    else
749
+	    } else
734 750
 	    {
735 751
 	        $text=$this->emetteur->name;
736 752
 	        $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
Please login to merge, or discard this patch.
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -36,47 +36,47 @@  discard block
 block discarded – undo
36 36
  */
37 37
 class pdf_standard extends ModelePDFProduct
38 38
 {
39
-    /**
40
-     * @var DoliDb Database handler
41
-     */
42
-    public $db;
39
+	/**
40
+	 * @var DoliDb Database handler
41
+	 */
42
+	public $db;
43 43
 
44 44
 	/**
45
-     * @var string model name
46
-     */
47
-    public $name;
45
+	 * @var string model name
46
+	 */
47
+	public $name;
48 48
 
49 49
 	/**
50
-     * @var string model description (short text)
51
-     */
52
-    public $description;
50
+	 * @var string model description (short text)
51
+	 */
52
+	public $description;
53 53
 
54 54
 	/**
55
-     * @var string document type
56
-     */
57
-    public $type;
55
+	 * @var string document type
56
+	 */
57
+	public $type;
58 58
 
59 59
 	/**
60
-     * @var array() Minimum version of PHP required by module.
60
+	 * @var array() Minimum version of PHP required by module.
61 61
 	 * e.g.: PHP ≥ 5.3 = array(5, 3)
62
-     */
62
+	 */
63 63
 	public $phpmin = array(5, 2);
64 64
 
65 65
 	/**
66
-     * Dolibarr version of the loaded document
67
-     * @public string
68
-     */
66
+	 * Dolibarr version of the loaded document
67
+	 * @public string
68
+	 */
69 69
 	public $version = 'dolibarr';
70 70
 
71
-    public $page_largeur;
72
-    public $page_hauteur;
73
-    public $format;
71
+	public $page_largeur;
72
+	public $page_hauteur;
73
+	public $format;
74 74
 	public $marge_gauche;
75 75
 	public $marge_droite;
76 76
 	public $marge_haute;
77 77
 	public $marge_basse;
78 78
 
79
-    public $emetteur;	// Objet societe qui emet
79
+	public $emetteur;	// Objet societe qui emet
80 80
 
81 81
 
82 82
 	/**
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 
149 149
 		if ($conf->produit->dir_output)
150 150
 		{
151
-		    // Definition of $dir and $file
151
+			// Definition of $dir and $file
152 152
 			if ($object->specimen)
153 153
 			{
154 154
 				$dir = $conf->produit->dir_output;
@@ -193,21 +193,21 @@  discard block
 block discarded – undo
193 193
 				$pdf->SetAutoPageBreak(1,0);
194 194
 
195 195
 				$heightforinfotot = 40;	// Height reserved to output the info and total part
196
-		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
197
-	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
198
-
199
-                if (class_exists('TCPDF'))
200
-                {
201
-                    $pdf->setPrintHeader(false);
202
-                    $pdf->setPrintFooter(false);
203
-                }
204
-                $pdf->SetFont(pdf_getPDFFont($outputlangs));
205
-                // Set path to the background PDF File
206
-                if (empty($conf->global->MAIN_DISABLE_FPDI) && ! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
207
-                {
208
-                    $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
209
-                    $tplidx = $pdf->importPage(1);
210
-                }
196
+				$heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
197
+				$heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
198
+
199
+				if (class_exists('TCPDF'))
200
+				{
201
+					$pdf->setPrintHeader(false);
202
+					$pdf->setPrintFooter(false);
203
+				}
204
+				$pdf->SetFont(pdf_getPDFFont($outputlangs));
205
+				// Set path to the background PDF File
206
+				if (empty($conf->global->MAIN_DISABLE_FPDI) && ! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
207
+				{
208
+					$pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
209
+					$tplidx = $pdf->importPage(1);
210
+				}
211 211
 
212 212
 				$pdf->Open();
213 213
 				$pagenb=0;
@@ -251,23 +251,23 @@  discard block
 block discarded – undo
251 251
 
252 252
 				if ($object->weight)
253 253
 				{
254
-				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Weight").': '.dol_htmlentitiesbr($object->weight), 0, 1);
255
-				    $nexY = $pdf->GetY();
254
+					$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Weight").': '.dol_htmlentitiesbr($object->weight), 0, 1);
255
+					$nexY = $pdf->GetY();
256 256
 				}
257 257
 				if ($object->weight)
258 258
 				{
259
-				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.($object->length != ''?$object->length:'?').' x '.($object->width != ''?$object->width:'?').' x '.($object->height != ''?$object->height:'?'), 0, 1);
260
-				    $nexY = $pdf->GetY();
259
+					$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.($object->length != ''?$object->length:'?').' x '.($object->width != ''?$object->width:'?').' x '.($object->height != ''?$object->height:'?'), 0, 1);
260
+					$nexY = $pdf->GetY();
261 261
 				}
262 262
 				if ($object->surface)
263 263
 				{
264
-				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Area").': '.dol_htmlentitiesbr($object->surface), 0, 1);
265
-				    $nexY = $pdf->GetY();
264
+					$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Area").': '.dol_htmlentitiesbr($object->surface), 0, 1);
265
+					$nexY = $pdf->GetY();
266 266
 				}
267 267
 				if ($object->volume)
268 268
 				{
269
-    				$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Volume").': '.dol_htmlentitiesbr($object->volume), 0, 1);
270
-	   			    $nexY = $pdf->GetY();
269
+					$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Volume").': '.dol_htmlentitiesbr($object->volume), 0, 1);
270
+	   				$nexY = $pdf->GetY();
271 271
 				}
272 272
 
273 273
 
@@ -572,102 +572,102 @@  discard block
 block discarded – undo
572 572
 	 */
573 573
 	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0, $currency='')
574 574
 	{
575
-	    global $conf;
575
+		global $conf;
576 576
 
577
-	    // Force to disable hidetop and hidebottom
578
-	    $hidebottom=0;
579
-	    if ($hidetop) $hidetop=-1;
577
+		// Force to disable hidetop and hidebottom
578
+		$hidebottom=0;
579
+		if ($hidetop) $hidetop=-1;
580 580
 
581
-	    $currency = !empty($currency) ? $currency : $conf->currency;
582
-	    $default_font_size = pdf_getPDFFontSize($outputlangs);
581
+		$currency = !empty($currency) ? $currency : $conf->currency;
582
+		$default_font_size = pdf_getPDFFontSize($outputlangs);
583 583
 
584
-	    // Amount in (at tab_top - 1)
585
-	    $pdf->SetTextColor(0,0,0);
586
-	    $pdf->SetFont('','', $default_font_size - 2);
584
+		// Amount in (at tab_top - 1)
585
+		$pdf->SetTextColor(0,0,0);
586
+		$pdf->SetFont('','', $default_font_size - 2);
587 587
 
588
-	    if (empty($hidetop))
589
-	    {
590
-	        $titre = $outputlangs->transnoentities("AmountInCurrency",$outputlangs->transnoentitiesnoconv("Currency".$currency));
591
-	        $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4);
592
-	        $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
588
+		if (empty($hidetop))
589
+		{
590
+			$titre = $outputlangs->transnoentities("AmountInCurrency",$outputlangs->transnoentitiesnoconv("Currency".$currency));
591
+			$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4);
592
+			$pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
593 593
 
594
-	        //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
595
-	        if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
596
-	    }
594
+			//$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
595
+			if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
596
+		}
597 597
 
598
-	    $pdf->SetDrawColor(128,128,128);
599
-	    $pdf->SetFont('','', $default_font_size - 1);
598
+		$pdf->SetDrawColor(128,128,128);
599
+		$pdf->SetFont('','', $default_font_size - 1);
600 600
 
601
-	    // Output Rect
602
-	    $this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
601
+		// Output Rect
602
+		$this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
603 603
 
604
-	    if (empty($hidetop))
605
-	    {
606
-	        $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);	// line prend une position y en 2eme param et 4eme param
604
+		if (empty($hidetop))
605
+		{
606
+			$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);	// line prend une position y en 2eme param et 4eme param
607 607
 
608
-	        $pdf->SetXY($this->posxdesc-1, $tab_top+1);
609
-	        $pdf->MultiCell(108,2, $outputlangs->transnoentities("Designation"),'','L');
610
-	    }
608
+			$pdf->SetXY($this->posxdesc-1, $tab_top+1);
609
+			$pdf->MultiCell(108,2, $outputlangs->transnoentities("Designation"),'','L');
610
+		}
611 611
 
612
-	    if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN))
613
-	    {
614
-	        $pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height);
615
-	        if (empty($hidetop))
616
-	        {
617
-	            $pdf->SetXY($this->posxtva-3, $tab_top+1);
618
-	            $pdf->MultiCell($this->posxup-$this->posxtva+3,2, $outputlangs->transnoentities("VAT"),'','C');
619
-	        }
620
-	    }
612
+		if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN))
613
+		{
614
+			$pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height);
615
+			if (empty($hidetop))
616
+			{
617
+				$pdf->SetXY($this->posxtva-3, $tab_top+1);
618
+				$pdf->MultiCell($this->posxup-$this->posxtva+3,2, $outputlangs->transnoentities("VAT"),'','C');
619
+			}
620
+		}
621 621
 
622
-	    $pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
623
-	    if (empty($hidetop))
624
-	    {
625
-	        $pdf->SetXY($this->posxup-1, $tab_top+1);
626
-	        $pdf->MultiCell($this->posxqty-$this->posxup-1,2, $outputlangs->transnoentities("PriceUHT"),'','C');
627
-	    }
622
+		$pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
623
+		if (empty($hidetop))
624
+		{
625
+			$pdf->SetXY($this->posxup-1, $tab_top+1);
626
+			$pdf->MultiCell($this->posxqty-$this->posxup-1,2, $outputlangs->transnoentities("PriceUHT"),'','C');
627
+		}
628 628
 
629
-	    $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height);
630
-	    if (empty($hidetop))
631
-	    {
632
-	        $pdf->SetXY($this->posxqty-1, $tab_top+1);
633
-	        if($conf->global->PRODUCT_USE_UNITS)
634
-	        {
635
-	            $pdf->MultiCell($this->posxunit-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
636
-	        }
637
-	        else
638
-	        {
639
-	            $pdf->MultiCell($this->posxdiscount-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
640
-	        }
641
-	    }
642
-
643
-	    if($conf->global->PRODUCT_USE_UNITS) {
644
-	        $pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height);
645
-	        if (empty($hidetop)) {
646
-	            $pdf->SetXY($this->posxunit - 1, $tab_top + 1);
647
-	            $pdf->MultiCell($this->posxdiscount - $this->posxunit - 1, 2, $outputlangs->transnoentities("Unit"), '',
648
-	                'C');
649
-	        }
650
-	    }
629
+		$pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height);
630
+		if (empty($hidetop))
631
+		{
632
+			$pdf->SetXY($this->posxqty-1, $tab_top+1);
633
+			if($conf->global->PRODUCT_USE_UNITS)
634
+			{
635
+				$pdf->MultiCell($this->posxunit-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
636
+			}
637
+			else
638
+			{
639
+				$pdf->MultiCell($this->posxdiscount-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
640
+			}
641
+		}
651 642
 
652
-	    $pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height);
653
-	    if (empty($hidetop))
654
-	    {
655
-	        if ($this->atleastonediscount)
656
-	        {
657
-	            $pdf->SetXY($this->posxdiscount-1, $tab_top+1);
658
-	            $pdf->MultiCell($this->postotalht-$this->posxdiscount+1,2, $outputlangs->transnoentities("ReductionShort"),'','C');
659
-	        }
660
-	    }
643
+		if($conf->global->PRODUCT_USE_UNITS) {
644
+			$pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height);
645
+			if (empty($hidetop)) {
646
+				$pdf->SetXY($this->posxunit - 1, $tab_top + 1);
647
+				$pdf->MultiCell($this->posxdiscount - $this->posxunit - 1, 2, $outputlangs->transnoentities("Unit"), '',
648
+					'C');
649
+			}
650
+		}
661 651
 
662
-	    if ($this->atleastonediscount)
663
-	    {
664
-	        $pdf->line($this->postotalht, $tab_top, $this->postotalht, $tab_top + $tab_height);
665
-	    }
666
-	    if (empty($hidetop))
667
-	    {
668
-	        $pdf->SetXY($this->postotalht-1, $tab_top+1);
669
-	        $pdf->MultiCell(30,2, $outputlangs->transnoentities("TotalHT"),'','C');
670
-	    }
652
+		$pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height);
653
+		if (empty($hidetop))
654
+		{
655
+			if ($this->atleastonediscount)
656
+			{
657
+				$pdf->SetXY($this->posxdiscount-1, $tab_top+1);
658
+				$pdf->MultiCell($this->postotalht-$this->posxdiscount+1,2, $outputlangs->transnoentities("ReductionShort"),'','C');
659
+			}
660
+		}
661
+
662
+		if ($this->atleastonediscount)
663
+		{
664
+			$pdf->line($this->postotalht, $tab_top, $this->postotalht, $tab_top + $tab_height);
665
+		}
666
+		if (empty($hidetop))
667
+		{
668
+			$pdf->SetXY($this->postotalht-1, $tab_top+1);
669
+			$pdf->MultiCell(30,2, $outputlangs->transnoentities("TotalHT"),'','C');
670
+		}
671 671
 	}
672 672
 
673 673
 	/**
@@ -682,74 +682,74 @@  discard block
 block discarded – undo
682 682
 	 */
683 683
 	function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey="")
684 684
 	{
685
-	    global $conf,$langs,$hookmanager;
685
+		global $conf,$langs,$hookmanager;
686 686
 
687
-	    $outputlangs->load("main");
688
-	    $outputlangs->load("bills");
689
-	    $outputlangs->load("propal");
690
-	    $outputlangs->load("companies");
691
-	    $outputlangs->load("orders");
692
-	    $default_font_size = pdf_getPDFFontSize($outputlangs);
687
+		$outputlangs->load("main");
688
+		$outputlangs->load("bills");
689
+		$outputlangs->load("propal");
690
+		$outputlangs->load("companies");
691
+		$outputlangs->load("orders");
692
+		$default_font_size = pdf_getPDFFontSize($outputlangs);
693 693
 
694
-	    if ($object->type == 1) $titlekey='ServiceSheet';
695
-	    else $titlekey='ProductSheet';
694
+		if ($object->type == 1) $titlekey='ServiceSheet';
695
+		else $titlekey='ProductSheet';
696 696
 
697
-	    pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
697
+		pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
698 698
 
699
-	    // Show Draft Watermark
700
-	    if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) )
701
-	    {
702
-	        pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->COMMANDE_DRAFT_WATERMARK);
703
-	    }
699
+		// Show Draft Watermark
700
+		if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) )
701
+		{
702
+			pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->COMMANDE_DRAFT_WATERMARK);
703
+		}
704 704
 
705
-	    $pdf->SetTextColor(0,0,60);
706
-	    $pdf->SetFont('','B', $default_font_size + 3);
705
+		$pdf->SetTextColor(0,0,60);
706
+		$pdf->SetFont('','B', $default_font_size + 3);
707 707
 
708
-	    $posy=$this->marge_haute;
709
-	    $posx=$this->page_largeur-$this->marge_droite-100;
708
+		$posy=$this->marge_haute;
709
+		$posx=$this->page_largeur-$this->marge_droite-100;
710 710
 
711
-	    $pdf->SetXY($this->marge_gauche,$posy);
711
+		$pdf->SetXY($this->marge_gauche,$posy);
712 712
 
713
-	    // Logo
714
-	    $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
715
-	    if ($this->emetteur->logo)
716
-	    {
717
-	        if (is_readable($logo))
718
-	        {
719
-	            $height=pdf_getHeightForLogo($logo);
720
-	            $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
721
-	        }
722
-	        else
723
-	        {
724
-	            $pdf->SetTextColor(200,0,0);
725
-	            $pdf->SetFont('','B', $default_font_size -2);
726
-	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
727
-	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
728
-	        }
729
-	    }
730
-	    else
731
-	    {
732
-	        $text=$this->emetteur->name;
733
-	        $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
734
-	    }
713
+		// Logo
714
+		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
715
+		if ($this->emetteur->logo)
716
+		{
717
+			if (is_readable($logo))
718
+			{
719
+				$height=pdf_getHeightForLogo($logo);
720
+				$pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
721
+			}
722
+			else
723
+			{
724
+				$pdf->SetTextColor(200,0,0);
725
+				$pdf->SetFont('','B', $default_font_size -2);
726
+				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
727
+				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
728
+			}
729
+		}
730
+		else
731
+		{
732
+			$text=$this->emetteur->name;
733
+			$pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
734
+		}
735 735
 
736
-	    $pdf->SetFont('','B', $default_font_size + 3);
737
-	    $pdf->SetXY($posx,$posy);
738
-	    $pdf->SetTextColor(0,0,60);
739
-	    $title=$outputlangs->transnoentities($titlekey);
740
-	    $pdf->MultiCell(100, 3, $title, '', 'R');
736
+		$pdf->SetFont('','B', $default_font_size + 3);
737
+		$pdf->SetXY($posx,$posy);
738
+		$pdf->SetTextColor(0,0,60);
739
+		$title=$outputlangs->transnoentities($titlekey);
740
+		$pdf->MultiCell(100, 3, $title, '', 'R');
741 741
 
742
-	    $pdf->SetFont('','B',$default_font_size);
742
+		$pdf->SetFont('','B',$default_font_size);
743 743
 
744
-	    $posy+=5;
745
-	    $pdf->SetXY($posx,$posy);
746
-	    $pdf->SetTextColor(0,0,60);
747
-	    $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R');
744
+		$posy+=5;
745
+		$pdf->SetXY($posx,$posy);
746
+		$pdf->SetTextColor(0,0,60);
747
+		$pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R');
748 748
 
749
-	    $posy+=1;
750
-	    $pdf->SetFont('','', $default_font_size - 1);
749
+		$posy+=1;
750
+		$pdf->SetFont('','', $default_font_size - 1);
751 751
 
752
-	    /*if ($object->ref_client)
752
+		/*if ($object->ref_client)
753 753
 	    {
754 754
 	        $posy+=5;
755 755
 	        $pdf->SetXY($posx,$posy);
@@ -757,14 +757,14 @@  discard block
 block discarded – undo
757 757
 	        $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : " . $outputlangs->convToOutputCharset($object->ref_client), '', 'R');
758 758
 	    }*/
759 759
 
760
-	    /*$posy+=4;
760
+		/*$posy+=4;
761 761
 	    $pdf->SetXY($posx,$posy);
762 762
 	    $pdf->SetTextColor(0,0,60);
763 763
 	    $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : " . dol_print_date($object->date,"%d %b %Y",false,$outputlangs,true), '', 'R');
764 764
 	    */
765 765
 
766
-	    // Get contact
767
-	    /*
766
+		// Get contact
767
+		/*
768 768
 	    if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP))
769 769
 	    {
770 770
 	        $arrayidcontact=$object->getIdContact('internal','SALESREPFOLL');
@@ -779,14 +779,14 @@  discard block
 block discarded – undo
779 779
 	        }
780 780
 	    }*/
781 781
 
782
-	    $posy+=2;
782
+		$posy+=2;
783 783
 
784
-	    // Show list of linked objects
785
-	    $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);
784
+		// Show list of linked objects
785
+		$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);
786 786
 
787
-	    if ($showaddress)
788
-	    {
789
-	        /*
787
+		if ($showaddress)
788
+		{
789
+			/*
790 790
 	        // Sender properties
791 791
 	        $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty);
792 792
 
@@ -817,9 +817,9 @@  discard block
 block discarded – undo
817 817
 	        $pdf->SetFont('','', $default_font_size - 1);
818 818
 	        $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L');
819 819
 	        */
820
-	    }
820
+		}
821 821
 
822
-	    $pdf->SetTextColor(0,0,0);
822
+		$pdf->SetTextColor(0,0,0);
823 823
 	}
824 824
 
825 825
 	/**
@@ -833,9 +833,9 @@  discard block
 block discarded – undo
833 833
 	 */
834 834
 	function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
835 835
 	{
836
-	    global $conf;
837
-	    $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
838
-	    return pdf_pagefoot($pdf,$outputlangs,'PRODUCT_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
836
+		global $conf;
837
+		$showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
838
+		return pdf_pagefoot($pdf,$outputlangs,'PRODUCT_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
839 839
 	}
840 840
 
841 841
 }
Please login to merge, or discard this patch.
Spacing   +134 added lines, -134 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	public $marge_haute;
77 77
 	public $marge_basse;
78 78
 
79
-    public $emetteur;	// Objet societe qui emet
79
+    public $emetteur; // Objet societe qui emet
80 80
 
81 81
 
82 82
 	/**
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	public function __construct($db)
88 88
 	{
89
-		global $conf,$langs,$mysoc;
89
+		global $conf, $langs, $mysoc;
90 90
 
91 91
 		$langs->load("main");
92 92
 		$langs->load("companies");
@@ -97,23 +97,23 @@  discard block
 block discarded – undo
97 97
 
98 98
 		// Dimension page pour format A4
99 99
 		$this->type = 'pdf';
100
-		$formatarray=pdf_getFormat();
100
+		$formatarray = pdf_getFormat();
101 101
 		$this->page_largeur = $formatarray['width'];
102 102
 		$this->page_hauteur = $formatarray['height'];
103
-		$this->format = array($this->page_largeur,$this->page_hauteur);
104
-		$this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
105
-		$this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
106
-		$this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
107
-		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
103
+		$this->format = array($this->page_largeur, $this->page_hauteur);
104
+		$this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10;
105
+		$this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10;
106
+		$this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10;
107
+		$this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10;
108 108
 
109
-		$this->option_logo = 1;                    // Affiche logo
110
-		$this->option_codeproduitservice = 0;      // Affiche code produit-service
111
-		$this->option_multilang = 1;               // Dispo en plusieurs langues
112
-		$this->option_freetext = 0;				   // Support add of a personalised text
109
+		$this->option_logo = 1; // Affiche logo
110
+		$this->option_codeproduitservice = 0; // Affiche code produit-service
111
+		$this->option_multilang = 1; // Dispo en plusieurs langues
112
+		$this->option_freetext = 0; // Support add of a personalised text
113 113
 
114 114
 		// Recupere emetteur
115
-		$this->emetteur=$mysoc;
116
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
115
+		$this->emetteur = $mysoc;
116
+		if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
117 117
 	}
118 118
 
119 119
 
@@ -128,13 +128,13 @@  discard block
 block discarded – undo
128 128
 	 *  @param		int			$hideref			Do not show ref
129 129
 	 *	@return		int         					1 if OK, <=0 if KO
130 130
 	 */
131
-	function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
131
+	function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
132 132
 	{
133
-		global $user,$langs,$conf,$mysoc,$db,$hookmanager;
133
+		global $user, $langs, $conf, $mysoc, $db, $hookmanager;
134 134
 
135
-		if (! is_object($outputlangs)) $outputlangs=$langs;
135
+		if (!is_object($outputlangs)) $outputlangs = $langs;
136 136
 		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
137
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
137
+		if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1';
138 138
 
139 139
 		$outputlangs->load("main");
140 140
 		$outputlangs->load("dict");
@@ -152,24 +152,24 @@  discard block
 block discarded – undo
152 152
 			if ($object->specimen)
153 153
 			{
154 154
 				$dir = $conf->produit->dir_output;
155
-				$file = $dir . "/SPECIMEN.pdf";
155
+				$file = $dir."/SPECIMEN.pdf";
156 156
 			}
157 157
 			else
158 158
 			{
159 159
 				$objectref = dol_sanitizeFileName($object->ref);
160
-				$dir = $conf->produit->dir_output . "/" . $objectref;
161
-				$file = $dir . "/" . $objectref . ".pdf";
160
+				$dir = $conf->produit->dir_output."/".$objectref;
161
+				$file = $dir."/".$objectref.".pdf";
162 162
 			}
163 163
 
164 164
 			$productFournisseur = new ProductFournisseur($this->db);
165 165
 			$supplierprices = $productFournisseur->list_product_fournisseur_price($object->id);
166 166
 			$object->supplierprices = $supplierprices;
167 167
 
168
-			if (! file_exists($dir))
168
+			if (!file_exists($dir))
169 169
 			{
170 170
 				if (dol_mkdir($dir) < 0)
171 171
 				{
172
-					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
172
+					$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
173 173
 					return -1;
174 174
 				}
175 175
 			}
@@ -177,24 +177,24 @@  discard block
 block discarded – undo
177 177
 			if (file_exists($dir))
178 178
 			{
179 179
 							// Add pdfgeneration hook
180
-				if (! is_object($hookmanager))
180
+				if (!is_object($hookmanager))
181 181
 				{
182 182
 					include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
183
-					$hookmanager=new HookManager($this->db);
183
+					$hookmanager = new HookManager($this->db);
184 184
 				}
185 185
 				$hookmanager->initHooks(array('pdfgeneration'));
186
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
186
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
187 187
 				global $action;
188
-				$reshook=$hookmanager->executeHooks('beforePDFCreation',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
188
+				$reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
189 189
 
190 190
 				// Create pdf instance
191
-				$pdf=pdf_getInstance($this->format);
192
-				$default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
193
-				$pdf->SetAutoPageBreak(1,0);
191
+				$pdf = pdf_getInstance($this->format);
192
+				$default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance
193
+				$pdf->SetAutoPageBreak(1, 0);
194 194
 
195
-				$heightforinfotot = 40;	// Height reserved to output the info and total part
196
-		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
197
-	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
195
+				$heightforinfotot = 40; // Height reserved to output the info and total part
196
+		        $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page
197
+	            $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin)
198 198
 
199 199
                 if (class_exists('TCPDF'))
200 200
                 {
@@ -203,51 +203,51 @@  discard block
 block discarded – undo
203 203
                 }
204 204
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
205 205
                 // Set path to the background PDF File
206
-                if (empty($conf->global->MAIN_DISABLE_FPDI) && ! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
206
+                if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
207 207
                 {
208 208
                     $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
209 209
                     $tplidx = $pdf->importPage(1);
210 210
                 }
211 211
 
212 212
 				$pdf->Open();
213
-				$pagenb=0;
214
-				$pdf->SetDrawColor(128,128,128);
213
+				$pagenb = 0;
214
+				$pdf->SetDrawColor(128, 128, 128);
215 215
 
216 216
 				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
217 217
 				$pdf->SetSubject($outputlangs->transnoentities("Order"));
218 218
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
219 219
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
220 220
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order")." ".$outputlangs->convToOutputCharset($object->thirdparty->name));
221
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
221
+				if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
222 222
 
223
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
223
+				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right
224 224
 
225 225
 
226 226
 				// New page
227 227
 				$pdf->AddPage();
228
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
228
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
229 229
 				$pagenb++;
230 230
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
231
-				$pdf->SetFont('','', $default_font_size - 1);
232
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
233
-				$pdf->SetTextColor(0,0,0);
231
+				$pdf->SetFont('', '', $default_font_size - 1);
232
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
233
+				$pdf->SetTextColor(0, 0, 0);
234 234
 
235 235
 
236 236
 				$tab_top = 42;
237
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
237
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10);
238 238
 				$tab_height = 130;
239 239
 				$tab_height_newpage = 150;
240 240
 
241 241
 				//
242
-				$pdf->SetFont('','B', $default_font_size);
242
+				$pdf->SetFont('', 'B', $default_font_size);
243 243
 				$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $tab_top, dol_htmlentitiesbr($object->label), 0, 1);
244 244
 				$nexY = $pdf->GetY();
245 245
 
246
-				$pdf->SetFont('','', $default_font_size);
246
+				$pdf->SetFont('', '', $default_font_size);
247 247
 				$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, dol_htmlentitiesbr($object->description), 0, 1);
248 248
 				$nexY = $pdf->GetY();
249 249
 
250
-				$nexY+=5;
250
+				$nexY += 5;
251 251
 
252 252
 				if ($object->weight)
253 253
 				{
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 				}
257 257
 				if ($object->weight)
258 258
 				{
259
-				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.($object->length != ''?$object->length:'?').' x '.($object->width != ''?$object->width:'?').' x '.($object->height != ''?$object->height:'?'), 0, 1);
259
+				    $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $nexY, $langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").': '.($object->length != '' ? $object->length : '?').' x '.($object->width != '' ? $object->width : '?').' x '.($object->height != '' ? $object->height : '?'), 0, 1);
260 260
 				    $nexY = $pdf->GetY();
261 261
 				}
262 262
 				if ($object->surface)
@@ -273,37 +273,37 @@  discard block
 block discarded – undo
273 273
 
274 274
 				// Affiche notes
275 275
 				// TODO There is no public note on product yet
276
-				$notetoshow=empty($object->note_public)?'':$object->note_public;
277
-				if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
276
+				$notetoshow = empty($object->note_public) ? '' : $object->note_public;
277
+				if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
278 278
 				{
279 279
 					// Get first sale rep
280 280
 					if (is_object($object->thirdparty))
281 281
 					{
282
-						$salereparray=$object->thirdparty->getSalesRepresentatives($user);
283
-						$salerepobj=new User($this->db);
282
+						$salereparray = $object->thirdparty->getSalesRepresentatives($user);
283
+						$salerepobj = new User($this->db);
284 284
 						$salerepobj->fetch($salereparray[0]['id']);
285
-						if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
285
+						if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
286 286
 					}
287 287
 				}
288 288
 				if ($notetoshow)
289 289
 				{
290 290
 					$tab_top = 88;
291 291
 
292
-					$pdf->SetFont('','', $default_font_size - 1);
293
-					$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
292
+					$pdf->SetFont('', '', $default_font_size - 1);
293
+					$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
294 294
 					$nexY = $pdf->GetY();
295
-					$height_note=$nexY-$tab_top;
295
+					$height_note = $nexY - $tab_top;
296 296
 
297 297
 					// Rect prend une longueur en 3eme param
298
-					$pdf->SetDrawColor(192,192,192);
299
-					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
298
+					$pdf->SetDrawColor(192, 192, 192);
299
+					$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1);
300 300
 
301 301
 					$tab_height = $tab_height - $height_note;
302
-					$tab_top = $nexY+6;
302
+					$tab_top = $nexY + 6;
303 303
 				}
304 304
 				else
305 305
 				{
306
-					$height_note=0;
306
+					$height_note = 0;
307 307
 				}
308 308
 
309 309
 				$iniY = $tab_top + 7;
@@ -523,35 +523,35 @@  discard block
 block discarded – undo
523 523
 				//$posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);
524 524
 
525 525
 				// Pied de page
526
-				$this->_pagefoot($pdf,$object,$outputlangs);
527
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
526
+				$this->_pagefoot($pdf, $object, $outputlangs);
527
+				if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages();
528 528
 
529 529
 				$pdf->Close();
530 530
 
531
-				$pdf->Output($file,'F');
531
+				$pdf->Output($file, 'F');
532 532
 
533 533
 				// Add pdfgeneration hook
534 534
 				$hookmanager->initHooks(array('pdfgeneration'));
535
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
535
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
536 536
 				global $action;
537
-				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
537
+				$reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
538 538
 
539
-				if (! empty($conf->global->MAIN_UMASK))
539
+				if (!empty($conf->global->MAIN_UMASK))
540 540
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
541 541
 
542 542
 				$this->result = array('fullpath'=>$file);
543 543
 				
544
-				return 1;   // Pas d'erreur
544
+				return 1; // Pas d'erreur
545 545
 			}
546 546
 			else
547 547
 			{
548
-				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
548
+				$this->error = $langs->trans("ErrorCanNotCreateDir", $dir);
549 549
 				return 0;
550 550
 			}
551 551
 		}
552 552
 		else
553 553
 		{
554
-			$this->error=$langs->trans("ErrorConstantNotDefined","PRODUCT_OUTPUTDIR");
554
+			$this->error = $langs->trans("ErrorConstantNotDefined", "PRODUCT_OUTPUTDIR");
555 555
 			return 0;
556 556
 		}
557 557
 	}
@@ -570,77 +570,77 @@  discard block
 block discarded – undo
570 570
 	 *   @param		string		$currency		Currency code
571 571
 	 *   @return	void
572 572
 	 */
573
-	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0, $currency='')
573
+	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '')
574 574
 	{
575 575
 	    global $conf;
576 576
 
577 577
 	    // Force to disable hidetop and hidebottom
578
-	    $hidebottom=0;
579
-	    if ($hidetop) $hidetop=-1;
578
+	    $hidebottom = 0;
579
+	    if ($hidetop) $hidetop = -1;
580 580
 
581 581
 	    $currency = !empty($currency) ? $currency : $conf->currency;
582 582
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
583 583
 
584 584
 	    // Amount in (at tab_top - 1)
585
-	    $pdf->SetTextColor(0,0,0);
586
-	    $pdf->SetFont('','', $default_font_size - 2);
585
+	    $pdf->SetTextColor(0, 0, 0);
586
+	    $pdf->SetFont('', '', $default_font_size - 2);
587 587
 
588 588
 	    if (empty($hidetop))
589 589
 	    {
590
-	        $titre = $outputlangs->transnoentities("AmountInCurrency",$outputlangs->transnoentitiesnoconv("Currency".$currency));
591
-	        $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4);
590
+	        $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency));
591
+	        $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4);
592 592
 	        $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
593 593
 
594 594
 	        //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
595
-	        if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',',$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
595
+	        if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
596 596
 	    }
597 597
 
598
-	    $pdf->SetDrawColor(128,128,128);
599
-	    $pdf->SetFont('','', $default_font_size - 1);
598
+	    $pdf->SetDrawColor(128, 128, 128);
599
+	    $pdf->SetFont('', '', $default_font_size - 1);
600 600
 
601 601
 	    // Output Rect
602
-	    $this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
602
+	    $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect prend une longueur en 3eme param et 4eme param
603 603
 
604 604
 	    if (empty($hidetop))
605 605
 	    {
606
-	        $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);	// line prend une position y en 2eme param et 4eme param
606
+	        $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); // line prend une position y en 2eme param et 4eme param
607 607
 
608
-	        $pdf->SetXY($this->posxdesc-1, $tab_top+1);
609
-	        $pdf->MultiCell(108,2, $outputlangs->transnoentities("Designation"),'','L');
608
+	        $pdf->SetXY($this->posxdesc - 1, $tab_top + 1);
609
+	        $pdf->MultiCell(108, 2, $outputlangs->transnoentities("Designation"), '', 'L');
610 610
 	    }
611 611
 
612 612
 	    if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN))
613 613
 	    {
614
-	        $pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height);
614
+	        $pdf->line($this->posxtva - 1, $tab_top, $this->posxtva - 1, $tab_top + $tab_height);
615 615
 	        if (empty($hidetop))
616 616
 	        {
617
-	            $pdf->SetXY($this->posxtva-3, $tab_top+1);
618
-	            $pdf->MultiCell($this->posxup-$this->posxtva+3,2, $outputlangs->transnoentities("VAT"),'','C');
617
+	            $pdf->SetXY($this->posxtva - 3, $tab_top + 1);
618
+	            $pdf->MultiCell($this->posxup - $this->posxtva + 3, 2, $outputlangs->transnoentities("VAT"), '', 'C');
619 619
 	        }
620 620
 	    }
621 621
 
622
-	    $pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
622
+	    $pdf->line($this->posxup - 1, $tab_top, $this->posxup - 1, $tab_top + $tab_height);
623 623
 	    if (empty($hidetop))
624 624
 	    {
625
-	        $pdf->SetXY($this->posxup-1, $tab_top+1);
626
-	        $pdf->MultiCell($this->posxqty-$this->posxup-1,2, $outputlangs->transnoentities("PriceUHT"),'','C');
625
+	        $pdf->SetXY($this->posxup - 1, $tab_top + 1);
626
+	        $pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C');
627 627
 	    }
628 628
 
629
-	    $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height);
629
+	    $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height);
630 630
 	    if (empty($hidetop))
631 631
 	    {
632
-	        $pdf->SetXY($this->posxqty-1, $tab_top+1);
633
-	        if($conf->global->PRODUCT_USE_UNITS)
632
+	        $pdf->SetXY($this->posxqty - 1, $tab_top + 1);
633
+	        if ($conf->global->PRODUCT_USE_UNITS)
634 634
 	        {
635
-	            $pdf->MultiCell($this->posxunit-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
635
+	            $pdf->MultiCell($this->posxunit - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C');
636 636
 	        }
637 637
 	        else
638 638
 	        {
639
-	            $pdf->MultiCell($this->posxdiscount-$this->posxqty-1,2, $outputlangs->transnoentities("Qty"),'','C');
639
+	            $pdf->MultiCell($this->posxdiscount - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C');
640 640
 	        }
641 641
 	    }
642 642
 
643
-	    if($conf->global->PRODUCT_USE_UNITS) {
643
+	    if ($conf->global->PRODUCT_USE_UNITS) {
644 644
 	        $pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height);
645 645
 	        if (empty($hidetop)) {
646 646
 	            $pdf->SetXY($this->posxunit - 1, $tab_top + 1);
@@ -649,13 +649,13 @@  discard block
 block discarded – undo
649 649
 	        }
650 650
 	    }
651 651
 
652
-	    $pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height);
652
+	    $pdf->line($this->posxdiscount - 1, $tab_top, $this->posxdiscount - 1, $tab_top + $tab_height);
653 653
 	    if (empty($hidetop))
654 654
 	    {
655 655
 	        if ($this->atleastonediscount)
656 656
 	        {
657
-	            $pdf->SetXY($this->posxdiscount-1, $tab_top+1);
658
-	            $pdf->MultiCell($this->postotalht-$this->posxdiscount+1,2, $outputlangs->transnoentities("ReductionShort"),'','C');
657
+	            $pdf->SetXY($this->posxdiscount - 1, $tab_top + 1);
658
+	            $pdf->MultiCell($this->postotalht - $this->posxdiscount + 1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C');
659 659
 	        }
660 660
 	    }
661 661
 
@@ -665,8 +665,8 @@  discard block
 block discarded – undo
665 665
 	    }
666 666
 	    if (empty($hidetop))
667 667
 	    {
668
-	        $pdf->SetXY($this->postotalht-1, $tab_top+1);
669
-	        $pdf->MultiCell(30,2, $outputlangs->transnoentities("TotalHT"),'','C');
668
+	        $pdf->SetXY($this->postotalht - 1, $tab_top + 1);
669
+	        $pdf->MultiCell(30, 2, $outputlangs->transnoentities("TotalHT"), '', 'C');
670 670
 	    }
671 671
 	}
672 672
 
@@ -680,9 +680,9 @@  discard block
 block discarded – undo
680 680
 	 *  @param	string		$titlekey		Translation key to show as title of document
681 681
 	 *  @return	void
682 682
 	 */
683
-	function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey="")
683
+	function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "")
684 684
 	{
685
-	    global $conf,$langs,$hookmanager;
685
+	    global $conf, $langs, $hookmanager;
686 686
 
687 687
 	    $outputlangs->load("main");
688 688
 	    $outputlangs->load("bills");
@@ -691,63 +691,63 @@  discard block
 block discarded – undo
691 691
 	    $outputlangs->load("orders");
692 692
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
693 693
 
694
-	    if ($object->type == 1) $titlekey='ServiceSheet';
695
-	    else $titlekey='ProductSheet';
694
+	    if ($object->type == 1) $titlekey = 'ServiceSheet';
695
+	    else $titlekey = 'ProductSheet';
696 696
 
697
-	    pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
697
+	    pdf_pagehead($pdf, $outputlangs, $this->page_hauteur);
698 698
 
699 699
 	    // Show Draft Watermark
700
-	    if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) )
700
+	    if ($object->statut == 0 && (!empty($conf->global->COMMANDE_DRAFT_WATERMARK)))
701 701
 	    {
702
-	        pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->COMMANDE_DRAFT_WATERMARK);
702
+	        pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->COMMANDE_DRAFT_WATERMARK);
703 703
 	    }
704 704
 
705
-	    $pdf->SetTextColor(0,0,60);
706
-	    $pdf->SetFont('','B', $default_font_size + 3);
705
+	    $pdf->SetTextColor(0, 0, 60);
706
+	    $pdf->SetFont('', 'B', $default_font_size + 3);
707 707
 
708
-	    $posy=$this->marge_haute;
709
-	    $posx=$this->page_largeur-$this->marge_droite-100;
708
+	    $posy = $this->marge_haute;
709
+	    $posx = $this->page_largeur - $this->marge_droite - 100;
710 710
 
711
-	    $pdf->SetXY($this->marge_gauche,$posy);
711
+	    $pdf->SetXY($this->marge_gauche, $posy);
712 712
 
713 713
 	    // Logo
714
-	    $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
714
+	    $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
715 715
 	    if ($this->emetteur->logo)
716 716
 	    {
717 717
 	        if (is_readable($logo))
718 718
 	        {
719
-	            $height=pdf_getHeightForLogo($logo);
720
-	            $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
719
+	            $height = pdf_getHeightForLogo($logo);
720
+	            $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
721 721
 	        }
722 722
 	        else
723 723
 	        {
724
-	            $pdf->SetTextColor(200,0,0);
725
-	            $pdf->SetFont('','B', $default_font_size -2);
726
-	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
724
+	            $pdf->SetTextColor(200, 0, 0);
725
+	            $pdf->SetFont('', 'B', $default_font_size - 2);
726
+	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L');
727 727
 	            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
728 728
 	        }
729 729
 	    }
730 730
 	    else
731 731
 	    {
732
-	        $text=$this->emetteur->name;
732
+	        $text = $this->emetteur->name;
733 733
 	        $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
734 734
 	    }
735 735
 
736
-	    $pdf->SetFont('','B', $default_font_size + 3);
737
-	    $pdf->SetXY($posx,$posy);
738
-	    $pdf->SetTextColor(0,0,60);
739
-	    $title=$outputlangs->transnoentities($titlekey);
736
+	    $pdf->SetFont('', 'B', $default_font_size + 3);
737
+	    $pdf->SetXY($posx, $posy);
738
+	    $pdf->SetTextColor(0, 0, 60);
739
+	    $title = $outputlangs->transnoentities($titlekey);
740 740
 	    $pdf->MultiCell(100, 3, $title, '', 'R');
741 741
 
742
-	    $pdf->SetFont('','B',$default_font_size);
742
+	    $pdf->SetFont('', 'B', $default_font_size);
743 743
 
744
-	    $posy+=5;
745
-	    $pdf->SetXY($posx,$posy);
746
-	    $pdf->SetTextColor(0,0,60);
747
-	    $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R');
744
+	    $posy += 5;
745
+	    $pdf->SetXY($posx, $posy);
746
+	    $pdf->SetTextColor(0, 0, 60);
747
+	    $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref), '', 'R');
748 748
 
749
-	    $posy+=1;
750
-	    $pdf->SetFont('','', $default_font_size - 1);
749
+	    $posy += 1;
750
+	    $pdf->SetFont('', '', $default_font_size - 1);
751 751
 
752 752
 	    /*if ($object->ref_client)
753 753
 	    {
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 	        }
780 780
 	    }*/
781 781
 
782
-	    $posy+=2;
782
+	    $posy += 2;
783 783
 
784 784
 	    // Show list of linked objects
785 785
 	    $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
 	        */
820 820
 	    }
821 821
 
822
-	    $pdf->SetTextColor(0,0,0);
822
+	    $pdf->SetTextColor(0, 0, 0);
823 823
 	}
824 824
 
825 825
 	/**
@@ -831,11 +831,11 @@  discard block
 block discarded – undo
831 831
 	 *      @param	int			$hidefreetext		1=Hide free text
832 832
 	 *      @return	int								Return height of bottom margin including footer text
833 833
 	 */
834
-	function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
834
+	function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0)
835 835
 	{
836 836
 	    global $conf;
837
-	    $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
838
-	    return pdf_pagefoot($pdf,$outputlangs,'PRODUCT_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
837
+	    $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
838
+	    return pdf_pagefoot($pdf, $outputlangs, 'PRODUCT_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext);
839 839
 	}
840 840
 
841 841
 }
Please login to merge, or discard this patch.
htdocs/core/class/html.formfile.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1676,7 +1676,7 @@
 block discarded – undo
1676 1676
      * @param   array     $file           File
1677 1677
      * @param   string    $modulepart     propal, facture, facture_fourn, ...
1678 1678
      * @param   string    $relativepath   Relative path of docs
1679
-     * @param   string    $ruleforpicto   Rule for picto: 0=Preview picto, 1=Use picto of mime type of file)
1679
+     * @param   integer    $ruleforpicto   Rule for picto: 0=Preview picto, 1=Use picto of mime type of file)
1680 1680
      * @param	string	  $param		  More param on http links
1681 1681
      * @return  string    $out            Output string with HTML
1682 1682
      */
Please login to merge, or discard this patch.
Braces   +367 added lines, -227 removed lines patch added patch discarded remove patch
@@ -77,7 +77,9 @@  discard block
 block discarded – undo
77 77
         $hookmanager->initHooks(array('formfile'));
78 78
 
79 79
 
80
-        if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
80
+        if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
81
+        	$useajax=0;
82
+        }
81 83
 
82 84
 		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
83 85
         {
@@ -86,8 +88,7 @@  discard block
 block discarded – undo
86 88
         	// TODO: This does not support option savingdocmask
87 89
         	// TODO: This break feature to upload links too
88 90
         	return $this->_formAjaxFileUpload($object);
89
-        }
90
-        else
91
+        } else
91 92
        	{
92 93
 	        //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
93 94
 	        if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
@@ -98,8 +99,12 @@  discard block
 block discarded – undo
98 99
 
99 100
             $out = "\n\n<!-- Start form attach new file -->\n";
100 101
 
101
-            if (empty($title)) $title=$langs->trans("AttachANewFile");
102
-            if ($title != 'none') $out.=load_fiche_titre($title, null, null);
102
+            if (empty($title)) {
103
+            	$title=$langs->trans("AttachANewFile");
104
+            }
105
+            if ($title != 'none') {
106
+            	$out.=load_fiche_titre($title, null, null);
107
+            }
103 108
 
104 109
             $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
105 110
             $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="">';
@@ -109,18 +114,30 @@  discard block
 block discarded – undo
109 114
             $out .= '<table width="100%" class="nobordernopadding">';
110 115
             $out .= '<tr>';
111 116
 
112
-            if (! empty($options)) $out .= '<td>'.$options.'</td>';
117
+            if (! empty($options)) {
118
+            	$out .= '<td>'.$options.'</td>';
119
+            }
113 120
 
114 121
             $out .= '<td valign="middle">';
115 122
 
116 123
             $max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
117 124
             $maxphp=@ini_get('upload_max_filesize');	// En inconnu
118
-            if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
119
-            if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
120
-            if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
121
-            if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
125
+            if (preg_match('/k$/i',$maxphp)) {
126
+            	$maxphp=$maxphp*1;
127
+            }
128
+            if (preg_match('/m$/i',$maxphp)) {
129
+            	$maxphp=$maxphp*1024;
130
+            }
131
+            if (preg_match('/g$/i',$maxphp)) {
132
+            	$maxphp=$maxphp*1024*1024;
133
+            }
134
+            if (preg_match('/t$/i',$maxphp)) {
135
+            	$maxphp=$maxphp*1024*1024*1024;
136
+            }
122 137
             // Now $max and $maxphp are in Kb
123
-            if ($maxphp > 0) $max=min($max,$maxphp);
138
+            if ($maxphp > 0) {
139
+            	$max=min($max,$maxphp);
140
+            }
124 141
 
125 142
             if ($max > 0)
126 143
             {
@@ -150,8 +167,7 @@  discard block
 block discarded – undo
150 167
                     $out .= ' ';
151 168
                     $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
152 169
                 }
153
-            }
154
-            else
170
+            } else
155 171
             {
156 172
                 $out .= ' ('.$langs->trans("UploadDisabled").')';
157 173
             }
@@ -160,7 +176,9 @@  discard block
 block discarded – undo
160 176
             if ($savingdocmask)
161 177
             {
162 178
             	$out .= '<tr>';
163
-   	            if (! empty($options)) $out .= '<td>'.$options.'</td>';
179
+   	            if (! empty($options)) {
180
+   	            	$out .= '<td>'.$options.'</td>';
181
+   	            }
164 182
 	            $out .= '<td valign="middle" class="nowrap">';
165 183
 				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
166 184
             	$out .= '</td>';
@@ -170,7 +188,9 @@  discard block
 block discarded – undo
170 188
             $out .= "</table>";
171 189
 
172 190
             $out .= '</form>';
173
-            if (empty($sectionid)) $out .= '<br>';
191
+            if (empty($sectionid)) {
192
+            	$out .= '<br>';
193
+            }
174 194
 
175 195
             $out .= "\n<!-- End form attach new file -->\n";
176 196
 
@@ -187,11 +207,15 @@  discard block
 block discarded – undo
187 207
 
188 208
 	            $out .= '<div class="valignmiddle" >';
189 209
 	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
190
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
210
+	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
211
+	            	$out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
212
+	            }
191 213
 	            $out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
192 214
 	            $out .= '</div>';
193 215
 	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
194
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
216
+	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
217
+	            	$out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
218
+	            }
195 219
 	            $out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
196 220
 	            $out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
197 221
 	            $out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
@@ -286,7 +310,9 @@  discard block
 block discarded – undo
286 310
         global $langs, $conf, $user, $hookmanager;
287 311
         global $form, $bc;
288 312
 
289
-        if (! is_object($form)) $form=new Form($this->db);
313
+        if (! is_object($form)) {
314
+        	$form=new Form($this->db);
315
+        }
290 316
 
291 317
         include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
292 318
 
@@ -296,10 +322,12 @@  discard block
 block discarded – undo
296 322
         }
297 323
 
298 324
         $printer=0;
299
-        if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport')))	// The direct print feature is implemented only for such elements
325
+        if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport'))) {
326
+        	// The direct print feature is implemented only for such elements
300 327
         {
301 328
             $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
302 329
         }
330
+        }
303 331
 
304 332
         $hookmanager->initHooks(array('formfile'));
305 333
         $forname='builddoc';
@@ -338,7 +366,9 @@  discard block
 block discarded – undo
338 366
         }
339 367
 
340 368
         $titletoshow=$langs->trans("Documents");
341
-        if (! empty($title)) $titletoshow=$title;
369
+        if (! empty($title)) {
370
+        	$titletoshow=$title;
371
+        }
342 372
 
343 373
         // Show table
344 374
         if ($genallowed)
@@ -348,216 +378,215 @@  discard block
 block discarded – undo
348 378
             if ($modulepart == 'company')
349 379
             {
350 380
                 $showempty=1;
351
-                if (is_array($genallowed)) $modellist=$genallowed;
352
-                else
381
+                if (is_array($genallowed)) {
382
+                	$modellist=$genallowed;
383
+                } else
353 384
                 {
354 385
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
355 386
                     $modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
356 387
                 }
357
-            }
358
-            else if ($modulepart == 'propal')
388
+            } else if ($modulepart == 'propal')
359 389
             {
360
-                if (is_array($genallowed)) $modellist=$genallowed;
361
-                else
390
+                if (is_array($genallowed)) {
391
+                	$modellist=$genallowed;
392
+                } else
362 393
                 {
363 394
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
364 395
                     $modellist=ModelePDFPropales::liste_modeles($this->db);
365 396
                 }
366
-            }
367
-			else if ($modulepart == 'supplier_proposal')
397
+            } else if ($modulepart == 'supplier_proposal')
368 398
             {
369
-                if (is_array($genallowed)) $modellist=$genallowed;
370
-                else
399
+                if (is_array($genallowed)) {
400
+                	$modellist=$genallowed;
401
+                } else
371 402
                 {
372 403
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
373 404
                     $modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
374 405
                 }
375
-            }
376
-            else if ($modulepart == 'commande')
406
+            } else if ($modulepart == 'commande')
377 407
             {
378
-                if (is_array($genallowed)) $modellist=$genallowed;
379
-                else
408
+                if (is_array($genallowed)) {
409
+                	$modellist=$genallowed;
410
+                } else
380 411
                 {
381 412
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
382 413
                     $modellist=ModelePDFCommandes::liste_modeles($this->db);
383 414
                 }
384
-            }
385
-            elseif ($modulepart == 'expedition')
415
+            } elseif ($modulepart == 'expedition')
386 416
             {
387
-                if (is_array($genallowed)) $modellist=$genallowed;
388
-                else
417
+                if (is_array($genallowed)) {
418
+                	$modellist=$genallowed;
419
+                } else
389 420
                 {
390 421
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
391 422
                     $modellist=ModelePDFExpedition::liste_modeles($this->db);
392 423
                 }
393
-            }
394
-            elseif ($modulepart == 'livraison')
424
+            } elseif ($modulepart == 'livraison')
395 425
             {
396
-                if (is_array($genallowed)) $modellist=$genallowed;
397
-                else
426
+                if (is_array($genallowed)) {
427
+                	$modellist=$genallowed;
428
+                } else
398 429
                 {
399 430
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
400 431
                     $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
401 432
                 }
402
-            }
403
-            else if ($modulepart == 'ficheinter')
433
+            } else if ($modulepart == 'ficheinter')
404 434
             {
405
-                if (is_array($genallowed)) $modellist=$genallowed;
406
-                else
435
+                if (is_array($genallowed)) {
436
+                	$modellist=$genallowed;
437
+                } else
407 438
                 {
408 439
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
409 440
                     $modellist=ModelePDFFicheinter::liste_modeles($this->db);
410 441
                 }
411
-            }
412
-            elseif ($modulepart == 'facture')
442
+            } elseif ($modulepart == 'facture')
413 443
             {
414
-                if (is_array($genallowed)) $modellist=$genallowed;
415
-                else
444
+                if (is_array($genallowed)) {
445
+                	$modellist=$genallowed;
446
+                } else
416 447
                 {
417 448
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
418 449
                     $modellist=ModelePDFFactures::liste_modeles($this->db);
419 450
                 }
420
-            }
421
-            elseif ($modulepart == 'contract')
451
+            } elseif ($modulepart == 'contract')
422 452
             {
423
-            	if (is_array($genallowed)) $modellist=$genallowed;
424
-            	else
453
+            	if (is_array($genallowed)) {
454
+            		$modellist=$genallowed;
455
+            	} else
425 456
             	{
426 457
             		include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
427 458
             		$modellist=ModelePDFContract::liste_modeles($this->db);
428 459
             	}
429
-            }
430
-            elseif ($modulepart == 'project')
460
+            } elseif ($modulepart == 'project')
431 461
             {
432
-                if (is_array($genallowed)) $modellist=$genallowed;
433
-                else
462
+                if (is_array($genallowed)) {
463
+                	$modellist=$genallowed;
464
+                } else
434 465
                 {
435 466
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
436 467
                     $modellist=ModelePDFProjects::liste_modeles($this->db);
437 468
                 }
438
-            }
439
-            elseif ($modulepart == 'project_task')
469
+            } elseif ($modulepart == 'project_task')
440 470
             {
441
-            	if (is_array($genallowed)) $modellist=$genallowed;
442
-            	else
471
+            	if (is_array($genallowed)) {
472
+            		$modellist=$genallowed;
473
+            	} else
443 474
             	{
444 475
             		include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
445 476
             		$modellist=ModelePDFTask::liste_modeles($this->db);
446 477
             	}
447
-            }
448
-            elseif ($modulepart == 'product')
478
+            } elseif ($modulepart == 'product')
449 479
             {
450
-                if (is_array($genallowed)) $modellist=$genallowed;
451
-                else
480
+                if (is_array($genallowed)) {
481
+                	$modellist=$genallowed;
482
+                } else
452 483
                 {
453 484
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
454 485
                     $modellist=ModelePDFProduct::liste_modeles($this->db);
455 486
                 }
456
-            }
457
-            elseif ($modulepart == 'export')
487
+            } elseif ($modulepart == 'export')
458 488
             {
459
-                if (is_array($genallowed)) $modellist=$genallowed;
460
-                else
489
+                if (is_array($genallowed)) {
490
+                	$modellist=$genallowed;
491
+                } else
461 492
                 {
462 493
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
463 494
                     $modellist=ModeleExports::liste_modeles($this->db);
464 495
                 }
465
-            }
466
-            else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
496
+            } else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
467 497
             {
468
-                if (is_array($genallowed)) $modellist=$genallowed;
469
-                else
498
+                if (is_array($genallowed)) {
499
+                	$modellist=$genallowed;
500
+                } else
470 501
                 {
471 502
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
472 503
                     $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
473 504
                 }
474
-            }
475
-            else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
505
+            } else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
476 506
             {
477
-                if (is_array($genallowed)) $modellist=$genallowed;
478
-                else
507
+                if (is_array($genallowed)) {
508
+                	$modellist=$genallowed;
509
+                } else
479 510
                 {
480 511
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
481 512
                     $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
482 513
                 }
483
-            }
484
-			else if ($modulepart == 'supplier_payment')
514
+            } else if ($modulepart == 'supplier_payment')
485 515
 			{
486
-                if (is_array($genallowed)) $modellist=$genallowed;
487
-                else
516
+                if (is_array($genallowed)) {
517
+                	$modellist=$genallowed;
518
+                } else
488 519
                 {
489 520
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
490 521
                     $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
491 522
                 }
492
-			}
493
-            else if ($modulepart == 'remisecheque')
523
+			} else if ($modulepart == 'remisecheque')
494 524
             {
495
-                if (is_array($genallowed)) $modellist=$genallowed;
496
-                else
525
+                if (is_array($genallowed)) {
526
+                	$modellist=$genallowed;
527
+                } else
497 528
                 {
498 529
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
499 530
                     $modellist=ModeleChequeReceipts::liste_modeles($this->db);
500 531
                 }
501
-            }
502
-            elseif ($modulepart == 'donation')
532
+            } elseif ($modulepart == 'donation')
503 533
             {
504
-                if (is_array($genallowed)) $modellist=$genallowed;
505
-                else
534
+                if (is_array($genallowed)) {
535
+                	$modellist=$genallowed;
536
+                } else
506 537
                 {
507 538
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
508 539
                     $modellist=ModeleDon::liste_modeles($this->db);
509 540
                 }
510
-            }
511
-            elseif ($modulepart == 'member')
541
+            } elseif ($modulepart == 'member')
512 542
             {
513
-                if (is_array($genallowed)) $modellist=$genallowed;
514
-                else
543
+                if (is_array($genallowed)) {
544
+                	$modellist=$genallowed;
545
+                } else
515 546
                 {
516 547
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
517 548
                     $modellist=ModelePDFCards::liste_modeles($this->db);
518 549
                 }
519
-            }
520
-            elseif ($modulepart == 'agenda')
550
+            } elseif ($modulepart == 'agenda')
521 551
             {
522
-                if (is_array($genallowed)) $modellist=$genallowed;
523
-                else
552
+                if (is_array($genallowed)) {
553
+                	$modellist=$genallowed;
554
+                } else
524 555
                 {
525 556
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
526 557
                     $modellist=ModeleAction::liste_modeles($this->db);
527 558
                 }
528
-            }
529
-            else if ($modulepart == 'expensereport')
559
+            } else if ($modulepart == 'expensereport')
530 560
             {
531
-                if (is_array($genallowed)) $modellist=$genallowed;
532
-                else
561
+                if (is_array($genallowed)) {
562
+                	$modellist=$genallowed;
563
+                } else
533 564
                 {
534 565
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
535 566
                     $modellist=ModeleExpenseReport::liste_modeles($this->db);
536 567
                 }
537
-            }
538
-            else if ($modulepart == 'unpaid')
568
+            } else if ($modulepart == 'unpaid')
539 569
             {
540 570
                 $modellist='';
541
-            }
542
-            elseif ($modulepart == 'user')
571
+            } elseif ($modulepart == 'user')
543 572
             {
544
-                if (is_array($genallowed)) $modellist=$genallowed;
545
-                else
573
+                if (is_array($genallowed)) {
574
+                	$modellist=$genallowed;
575
+                } else
546 576
                 {
547 577
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
548 578
                     $modellist=ModelePDFUser::liste_modeles($this->db);
549 579
                 }
550
-            }
551
-            elseif ($modulepart == 'usergroup')
580
+            } elseif ($modulepart == 'usergroup')
552 581
             {
553
-                if (is_array($genallowed)) $modellist=$genallowed;
554
-                else
582
+                if (is_array($genallowed)) {
583
+                	$modellist=$genallowed;
584
+                } else
555 585
                 {
556 586
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
557 587
                     $modellist=ModelePDFUserGroup::liste_modeles($this->db);
558 588
                 }
559
-            }
560
-            else //if ($modulepart != 'agenda')
589
+            } else //if ($modulepart != 'agenda')
561 590
             {
562 591
             	// For normalized standard modules
563 592
             	$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
@@ -575,8 +604,7 @@  discard block
 block discarded – undo
575 604
                 if (class_exists($class))
576 605
                 {
577 606
                     $modellist=call_user_func($class.'::liste_modeles',$this->db);
578
-                }
579
-                else
607
+                } else
580 608
               {
581 609
                     dol_print_error($this->db,'Bad value for modulepart');
582 610
                     return -1;
@@ -587,10 +615,17 @@  discard block
 block discarded – undo
587 615
             $headershown=1;
588 616
 
589 617
             $buttonlabeltoshow=$buttonlabel;
590
-            if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
618
+            if (empty($buttonlabel)) {
619
+            	$buttonlabel=$langs->trans('Generate');
620
+            }
591 621
 
592
-            if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
593
-            if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
622
+            if ($conf->browser->layout == 'phone') {
623
+            	$urlsource.='#'.$forname.'_form';
624
+            }
625
+            // So we switch to form after a generation
626
+            if (empty($noform)) {
627
+            	$out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
628
+            }
594 629
             $out.= '<input type="hidden" name="action" value="builddoc">';
595 630
             $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
596 631
 
@@ -607,15 +642,16 @@  discard block
 block discarded – undo
607 642
             if (! empty($modellist))
608 643
             {
609 644
                 $out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
610
-                if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
645
+                if (is_array($modellist) && count($modellist) == 1) {
646
+                	// If there is only one element
611 647
                 {
612 648
                     $arraykeys=array_keys($modellist);
649
+                }
613 650
                     $modelselected=$arraykeys[0];
614 651
                 }
615 652
                 $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
616 653
                 $out.= ajax_combobox('model');
617
-            }
618
-            else
654
+            } else
619 655
             {
620 656
                 $out.= '<div class="float">'.$langs->trans("Files").'</div>';
621 657
             }
@@ -627,10 +663,11 @@  discard block
 block discarded – undo
627 663
                 $formadmin=new FormAdmin($this->db);
628 664
                 $defaultlang=$codelang?$codelang:$langs->getDefaultLang();
629 665
                 $morecss='maxwidth150';
630
-                if (! empty($conf->browser->phone)) $morecss='maxwidth100';
666
+                if (! empty($conf->browser->phone)) {
667
+                	$morecss='maxwidth100';
668
+                }
631 669
                 $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
632
-            }
633
-            else
670
+            } else
634 671
             {
635 672
                 $out.= '&nbsp;';
636 673
             }
@@ -638,15 +675,21 @@  discard block
 block discarded – undo
638 675
             // Button
639 676
             $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
640 677
             $genbutton.= ' type="submit" value="'.$buttonlabel.'"';
641
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
678
+            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) {
679
+            	$genbutton.= ' disabled';
680
+            }
642 681
             $genbutton.= '>';
643 682
             if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
644 683
             {
645 684
                	$langs->load("errors");
646 685
                	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
647 686
             }
648
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
649
-            if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
687
+            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
688
+            	$genbutton='';
689
+            }
690
+            if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') {
691
+            	$genbutton='';
692
+            }
650 693
             $out.= $genbutton;
651 694
             $out.= '</th>';
652 695
 
@@ -654,7 +697,9 @@  discard block
 block discarded – undo
654 697
             {
655 698
                 foreach($hookmanager->hooks['formfile'] as $module)
656 699
                 {
657
-                    if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
700
+                    if (method_exists($module, 'formBuilddocLineOptions')) {
701
+                    	$out .= '<th></th>';
702
+                    }
658 703
                 }
659 704
             }
660 705
             $out.= '</tr>';
@@ -701,13 +746,22 @@  discard block
 block discarded – undo
701 746
 				{
702 747
 					// Define relative path for download link (depends on module)
703 748
 					$relativepath=$file["name"];										// Cas general
704
-                    if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
705
-					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
749
+                    if ($modulesubdir) {
750
+                    	$relativepath=$modulesubdir."/".$file["name"];
751
+                    }
752
+                    // Cas propal, facture...
753
+					if ($modulepart == 'export') {
754
+						$relativepath = $file["name"];
755
+					}
756
+					// Other case
706 757
 
707 758
 					$out.= '<tr class="oddeven">';
708 759
 
709 760
 					$documenturl = DOL_URL_ROOT.'/document.php';
710
-					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
761
+					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
762
+						$documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;
763
+					}
764
+					// To use another wrapper
711 765
 
712 766
 					// Show file name with link to download
713 767
 					$out.= '<td class="tdoverflowmax300">';
@@ -715,7 +769,9 @@  discard block
 block discarded – undo
715 769
                     $out.= ($tmp?$tmp.' ':'');
716 770
 					$out.= '<a class="documentdownload" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
717 771
 					$mime=dol_mimetype($relativepath,'',0);
718
-					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
772
+					if (preg_match('/text/',$mime)) {
773
+						$out.= ' target="_blank"';
774
+					}
719 775
 					$out.= ' target="_blank">';
720 776
 					$out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]).' '.$file["name"];
721 777
 					$out.= '</a>'."\n";
@@ -764,8 +820,10 @@  discard block
 block discarded – undo
764 820
                         {
765 821
                             $out .= $hookmanager->resPrint;		// Complete line
766 822
                             $out.= '</tr>';
823
+                        } else {
824
+                        	$out = $hookmanager->resPrint;
767 825
                         }
768
-                        else $out = $hookmanager->resPrint;		// Replace line
826
+                        // Replace line
769 827
               		}
770 828
 				}
771 829
 
@@ -787,7 +845,9 @@  discard block
 block discarded – undo
787 845
                     $out.='<td align="right">';
788 846
                     $out.=dol_print_date($file->datea,'dayhour');
789 847
                     $out.='</td>';
790
-                    if ($delallowed || $printer || $morepicto) $out.='<td></td>';
848
+                    if ($delallowed || $printer || $morepicto) {
849
+                    	$out.='<td></td>';
850
+                    }
791 851
                     $out.='</tr>'."\n";
792 852
                 }
793 853
                 $this->numoffiles++;
@@ -807,7 +867,9 @@  discard block
 block discarded – undo
807 867
             $out.= "</div>\n";
808 868
             if ($genallowed)
809 869
             {
810
-                if (empty($noform)) $out.= '</form>'."\n";
870
+                if (empty($noform)) {
871
+                	$out.= '</form>'."\n";
872
+                }
811 873
             }
812 874
         }
813 875
         $out.= '<!-- End show_document -->'."\n";
@@ -852,11 +914,17 @@  discard block
 block discarded – undo
852 914
     		foreach($file_list as $file)
853 915
     		{
854 916
     		    $i++;
855
-    			if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
917
+    			if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) {
918
+    				continue;
919
+    			}
920
+    			// Discard this. It does not match provided filter.
856 921
 
857 922
     			// Define relative path for download link (depends on module)
858 923
     			$relativepath=$file["name"];								// Cas general
859
-    			if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
924
+    			if ($modulesubdir) {
925
+    				$relativepath=$modulesubdir."/".$file["name"];
926
+    			}
927
+    			// Cas propal, facture...
860 928
     			// Autre cas
861 929
     			if ($modulepart == 'donation')            {
862 930
     				$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
@@ -868,20 +936,27 @@  discard block
 block discarded – undo
868 936
     			$this->infofiles['nboffiles']++;
869 937
     			$this->infofiles['files'][]=$file['fullname'];
870 938
     			$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
871
-    			if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
872
-    			else $this->infofiles['extensions'][$ext]++;
939
+    			if (empty($this->infofiles[$ext])) {
940
+    				$this->infofiles['extensions'][$ext]=1;
941
+    			} else {
942
+    				$this->infofiles['extensions'][$ext]++;
943
+    			}
873 944
 
874 945
     			// Preview
875 946
     			if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
876 947
     			{
877 948
                     $tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
878
-                    if ($tmparray && $tmparray['url']) $tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>'.img_picto('','detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
949
+                    if ($tmparray && $tmparray['url']) {
950
+                    	$tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>'.img_picto('','detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
951
+                    }
879 952
     			}
880 953
 
881 954
     			// Download
882 955
     		    $tmpout.= '<li><a class="pictopreview" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
883 956
     			$mime=dol_mimetype($relativepath,'',0);
884
-    			if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
957
+    			if (preg_match('/text/',$mime)) {
958
+    				$tmpout.= ' target="_blank"';
959
+    			}
885 960
     			$tmpout.= '>';
886 961
     			$tmpout.=img_mime($relativepath, $file["name"]).' ';
887 962
     			$tmpout.= $langs->trans("Download").' '.$ext;
@@ -890,8 +965,7 @@  discard block
 block discarded – undo
890 965
     		$out.=$tmpout;
891 966
     		$out.='</ul></div></dd>
892 967
     			</dl>';
893
-    	}
894
-    	else
968
+    	} else
895 969
     	{
896 970
     	    // TODO Add link to regenerate doc ?
897 971
     	    //$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
@@ -936,8 +1010,13 @@  discard block
 block discarded – undo
936 1010
 		if (empty($relativepath))
937 1011
 		{
938 1012
 		    $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
939
-		    if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
940
-		    if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1013
+		    if ($object->element == 'invoice_supplier') {
1014
+		    	$relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;
1015
+		    }
1016
+		    // TODO Call using a defined value for $relativepath
1017
+		    if ($object->element == 'project_task') {
1018
+		    	$relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1019
+		    }
941 1020
 		}
942 1021
 		// For backward compatiblity, we detect file is stored into an old path
943 1022
 		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos')
@@ -969,21 +1048,28 @@  discard block
 block discarded – undo
969 1048
 		);
970 1049
 		$reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
971 1050
 
972
-		if (isset($reshook) && $reshook != '') // null or '' for bypass
1051
+		if (isset($reshook) && $reshook != '') {
1052
+			// null or '' for bypass
973 1053
 		{
974 1054
 			return $reshook;
975 1055
 		}
976
-		else
1056
+		} else
977 1057
 		{
978 1058
 			$param = (isset($object->id)?'&id='.$object->id:'').$param;
979 1059
 
980
-			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1060
+			if ($permtoeditline < 0) {
1061
+				// Old behaviour for backward compatibility. New feature should call method with value 0 or 1
981 1062
 			{
982 1063
 			    $permtoeditline=0;
1064
+			}
983 1065
 			    if (in_array($modulepart, array('product','produit','service')))
984 1066
 			    {
985
-			        if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
986
-			        if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
1067
+			        if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) {
1068
+			        	$permtoeditline=1;
1069
+			        }
1070
+			        if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) {
1071
+			        	$permtoeditline=1;
1072
+			        }
987 1073
 			    }
988 1074
 			}
989 1075
 			if (empty($conf->global->MAIN_UPLOAD_DOC))
@@ -993,8 +1079,12 @@  discard block
 block discarded – undo
993 1079
 			}
994 1080
 
995 1081
 			// Show list of existing files
996
-			if (empty($useinecm)) print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
997
-			if (empty($url)) $url=$_SERVER["PHP_SELF"];
1082
+			if (empty($useinecm)) {
1083
+				print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1084
+			}
1085
+			if (empty($url)) {
1086
+				$url=$_SERVER["PHP_SELF"];
1087
+			}
998 1088
 
999 1089
 			print '<!-- html.formfile::list_of_documents -->'."\n";
1000 1090
 			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
@@ -1014,9 +1104,13 @@  discard block
 block discarded – undo
1014 1104
 				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1015 1105
 				print '<td></td>';
1016 1106
 				print '<td></td>';
1017
-				if (empty($useinecm)) print '<td></td>';
1107
+				if (empty($useinecm)) {
1108
+					print '<td></td>';
1109
+				}
1018 1110
 				print '<td></td>';
1019
-				if (! $disablemove) print '<td></td>';
1111
+				if (! $disablemove) {
1112
+					print '<td></td>';
1113
+				}
1020 1114
 				print "</tr>\n";
1021 1115
 			}
1022 1116
 
@@ -1024,9 +1118,13 @@  discard block
 block discarded – undo
1024 1118
 			print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1025 1119
 			print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1026 1120
 			print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1027
-			if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');
1121
+			if (empty($useinecm)) {
1122
+				print_liste_field_titre('',$url,"","",$param,'align="center"');
1123
+			}
1028 1124
 			print_liste_field_titre('');
1029
-			if (! $disablemove) print_liste_field_titre('');
1125
+			if (! $disablemove) {
1126
+				print_liste_field_titre('');
1127
+			}
1030 1128
 			print "</tr>\n";
1031 1129
 
1032 1130
 			// Get list of files stored into database for same relative directory
@@ -1044,16 +1142,20 @@  discard block
 block discarded – undo
1044 1142
 			}
1045 1143
 
1046 1144
 			$nboffiles=count($filearray);
1047
-			if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1145
+			if ($nboffiles > 0) {
1146
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1147
+			}
1048 1148
 
1049 1149
 			$var=true; $i=0; $nboflines = 0; $lastrowid=0;
1050
-			foreach($filearray as $key => $file)      // filearray must be only files here
1150
+			foreach($filearray as $key => $file) {
1151
+				// filearray must be only files here
1051 1152
 			{
1052 1153
 				if ($file['name'] != '.'
1053 1154
 						&& $file['name'] != '..'
1054 1155
 						&& ! preg_match('/\.meta$/i',$file['name']))
1055 1156
 				{
1056 1157
 					if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1158
+			}
1057 1159
 
1058 1160
 					$editline=0;
1059 1161
 					$nboflines++;
@@ -1065,17 +1167,25 @@  discard block
 block discarded – undo
1065 1167
 
1066 1168
 					$filepath=$relativepath.$file['name'];
1067 1169
 
1068
-					if (! $editline) print $this->showPreview($file,$modulepart,$filepath);
1170
+					if (! $editline) {
1171
+						print $this->showPreview($file,$modulepart,$filepath);
1172
+					}
1069 1173
 
1070 1174
 					//print "XX".$file['name'];	//$file['name'] must be utf8
1071 1175
 					print '<a class="paddingleft" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1072
-					if ($forcedownload) print '&attachment=1';
1073
-					if (! empty($object->entity)) print '&entity='.$object->entity;
1176
+					if ($forcedownload) {
1177
+						print '&attachment=1';
1178
+					}
1179
+					if (! empty($object->entity)) {
1180
+						print '&entity='.$object->entity;
1181
+					}
1074 1182
 					print '&file='.urlencode($filepath);
1075 1183
 					print '">';
1076 1184
 
1077 1185
 					print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1078
-					if ($showrelpart == 1) print $relativepath;
1186
+					if ($showrelpart == 1) {
1187
+						print $relativepath;
1188
+					}
1079 1189
 					//print dol_trunc($file['name'],$maxlength,'middle');
1080 1190
 					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile')))
1081 1191
 					{
@@ -1083,8 +1193,7 @@  discard block
 block discarded – undo
1083 1193
 					    print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1084 1194
 					    print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1085 1195
 					    $editline=1;
1086
-					}
1087
-					else
1196
+					} else
1088 1197
 					{
1089 1198
 					    print $file['name'];
1090 1199
 					    print '</a>';
@@ -1104,16 +1213,22 @@  discard block
 block discarded – undo
1104 1213
 						if (image_format_supported($file['name']) > 0)
1105 1214
 						{
1106 1215
 						    $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1107
-						    if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1216
+						    if (! dol_is_file($file['path'].'/'.$minifile)) {
1217
+						    	$minifile=getImageFileNameForSize($file['name'], '_mini', '.png');
1218
+						    }
1219
+						    // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1108 1220
 						    //print $file['path'].'/'.$minifile.'<br>';
1109 1221
 
1110 1222
 						    $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1111
-						    if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1223
+						    if (empty($urlforhref)) {
1224
+						    	$urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1225
+						    }
1112 1226
 						    print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1113 1227
 							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1114 1228
 							print '</a>';
1229
+						} else {
1230
+							print '&nbsp;';
1115 1231
 						}
1116
-						else print '&nbsp;';
1117 1232
 						print '</td>';
1118 1233
 					}
1119 1234
 					if (! $editline)
@@ -1124,14 +1239,17 @@  discard block
 block discarded – undo
1124 1239
     					if ($useinecm)
1125 1240
     					{
1126 1241
     					    print '<a href="'.DOL_URL_ROOT.'/ecm/docfile.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_view('default', 0, 'class="paddingrightonly"').'</a>';
1127
-    					}
1128
-    					else
1242
+    					} else
1129 1243
     					{
1130 1244
         					$newmodulepart=$modulepart;
1131
-        					if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1245
+        					if (in_array($modulepart, array('product','produit','service'))) {
1246
+        						$newmodulepart='produit|service';
1247
+        					}
1132 1248
 
1133 1249
         					$disablecrop=1;
1134
-        					if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0;
1250
+        					if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) {
1251
+        						$disablecrop=0;
1252
+        					}
1135 1253
 
1136 1254
     					    if (! $disablecrop && image_format_supported($file['name']) > 0)
1137 1255
     						{
@@ -1156,9 +1274,15 @@  discard block
 block discarded – undo
1156 1274
     							$filepath=$file['name'];
1157 1275
     						*/
1158 1276
     						$useajax=1;
1159
-    						if (! empty($conf->dol_use_jmobile)) $useajax=0;
1160
-    						if (empty($conf->use_javascript_ajax)) $useajax=0;
1161
-    						if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1277
+    						if (! empty($conf->dol_use_jmobile)) {
1278
+    							$useajax=0;
1279
+    						}
1280
+    						if (empty($conf->use_javascript_ajax)) {
1281
+    							$useajax=0;
1282
+    						}
1283
+    						if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) {
1284
+    							$useajax=0;
1285
+    						}
1162 1286
 
1163 1287
     						print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1164 1288
     					}
@@ -1175,20 +1299,20 @@  discard block
 block discarded – undo
1175 1299
     					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1176 1300
     				    		}
1177 1301
     					    	print '</td>';
1178
-    					    }
1179
-    					    else {
1302
+    					    } else {
1180 1303
     					       	print '<td align="center"'.((empty($conf->browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1181 1304
     					       	print '</td>';
1182 1305
     					    }
1183 1306
 					   }
1184
-					}
1185
-					else
1307
+					} else
1186 1308
 					{
1187 1309
 					    print '<td class="right">';
1188 1310
 					    print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1189 1311
 					    print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1190 1312
 					    print '</td>';
1191
-					    if (empty($disablemove)) print '<td class="right"></td>';
1313
+					    if (empty($disablemove)) {
1314
+					    	print '<td class="right"></td>';
1315
+					    }
1192 1316
 					}
1193 1317
 					print "</tr>\n";
1194 1318
 
@@ -1198,10 +1322,15 @@  discard block
 block discarded – undo
1198 1322
 			if ($nboffiles == 0)
1199 1323
 			{
1200 1324
 			    $colspan=(empty($useinecm)?'5':'5');
1201
-			    if (empty($disablemove)) $colspan++;
1325
+			    if (empty($disablemove)) {
1326
+			    	$colspan++;
1327
+			    }
1202 1328
 				print '<tr '.$bc[false].'><td colspan="'.$colspan.'" class="opacitymedium">';
1203
-				if (empty($textifempty)) print $langs->trans("NoFileFound");
1204
-				else print $textifempty;
1329
+				if (empty($textifempty)) {
1330
+					print $langs->trans("NoFileFound");
1331
+				} else {
1332
+					print $textifempty;
1333
+				}
1205 1334
 				print '</td></tr>';
1206 1335
 			}
1207 1336
 			print "</table>";
@@ -1251,8 +1380,12 @@  discard block
 block discarded – undo
1251 1380
         dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1252 1381
 
1253 1382
         // Show list of documents
1254
-        if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1255
-        if (empty($url)) $url=$_SERVER["PHP_SELF"];
1383
+        if (empty($useinecm)) {
1384
+        	print load_fiche_titre($langs->trans("AttachedFiles"));
1385
+        }
1386
+        if (empty($url)) {
1387
+        	$url=$_SERVER["PHP_SELF"];
1388
+        }
1256 1389
 
1257 1390
         if (! empty($addfilterfields))
1258 1391
         {
@@ -1280,7 +1413,9 @@  discard block
 block discarded – undo
1280 1413
 
1281 1414
         print '<tr class="liste_titre">';
1282 1415
         $sortref="fullname";
1283
-        if ($modulepart == 'invoice_supplier') $sortref='level1name';
1416
+        if ($modulepart == 'invoice_supplier') {
1417
+        	$sortref='level1name';
1418
+        }
1284 1419
         print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1285 1420
         print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1286 1421
         print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
@@ -1293,68 +1428,55 @@  discard block
 block discarded – undo
1293 1428
         {
1294 1429
             include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1295 1430
             $object_instance=new Societe($this->db);
1296
-        }
1297
-        else if ($modulepart == 'invoice')
1431
+        } else if ($modulepart == 'invoice')
1298 1432
         {
1299 1433
             include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1300 1434
             $object_instance=new Facture($this->db);
1301
-        }
1302
-        else if ($modulepart == 'invoice_supplier')
1435
+        } else if ($modulepart == 'invoice_supplier')
1303 1436
         {
1304 1437
             include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1305 1438
             $object_instance=new FactureFournisseur($this->db);
1306
-        }
1307
-        else if ($modulepart == 'propal')
1439
+        } else if ($modulepart == 'propal')
1308 1440
         {
1309 1441
             include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1310 1442
             $object_instance=new Propal($this->db);
1311
-        }
1312
-        else if ($modulepart == 'supplier_proposal')
1443
+        } else if ($modulepart == 'supplier_proposal')
1313 1444
         {
1314 1445
             include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1315 1446
             $object_instance=new SupplierProposal($this->db);
1316
-        }
1317
-        else if ($modulepart == 'order')
1447
+        } else if ($modulepart == 'order')
1318 1448
         {
1319 1449
             include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1320 1450
             $object_instance=new Commande($this->db);
1321
-        }
1322
-        else if ($modulepart == 'order_supplier')
1451
+        } else if ($modulepart == 'order_supplier')
1323 1452
         {
1324 1453
             include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1325 1454
             $object_instance=new CommandeFournisseur($this->db);
1326
-        }
1327
-        else if ($modulepart == 'contract')
1455
+        } else if ($modulepart == 'contract')
1328 1456
         {
1329 1457
             include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1330 1458
             $object_instance=new Contrat($this->db);
1331
-        }
1332
-        else if ($modulepart == 'product')
1459
+        } else if ($modulepart == 'product')
1333 1460
         {
1334 1461
             include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1335 1462
             $object_instance=new Product($this->db);
1336
-        }
1337
-        else if ($modulepart == 'tax')
1463
+        } else if ($modulepart == 'tax')
1338 1464
         {
1339 1465
             include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1340 1466
             $object_instance=new ChargeSociales($this->db);
1341
-        }
1342
-        else if ($modulepart == 'project')
1467
+        } else if ($modulepart == 'project')
1343 1468
         {
1344 1469
         	include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1345 1470
         	$object_instance=new Project($this->db);
1346
-        }
1347
-        else if ($modulepart == 'fichinter')
1471
+        } else if ($modulepart == 'fichinter')
1348 1472
         {
1349 1473
         	include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1350 1474
         	$object_instance=new Fichinter($this->db);
1351
-        }
1352
-        else if ($modulepart == 'user')
1475
+        } else if ($modulepart == 'user')
1353 1476
         {
1354 1477
         	include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1355 1478
         	$object_instance=new User($this->db);
1356
-        }
1357
-        else if ($modulepart == 'expensereport')
1479
+        } else if ($modulepart == 'expensereport')
1358 1480
         {
1359 1481
         	include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1360 1482
         	$object_instance=new ExpenseReport($this->db);
@@ -1391,13 +1513,14 @@  discard block
 block discarded – undo
1391 1513
                 if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1392 1514
                 if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1393 1515
 
1394
-                if (! $id && ! $ref) continue;
1516
+                if (! $id && ! $ref) {
1517
+                	continue;
1518
+                }
1395 1519
                 $found=0;
1396 1520
                 if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1397 1521
                 {
1398 1522
                     $found=1;
1399
-                }
1400
-                else
1523
+                } else
1401 1524
                 {
1402 1525
                     //print 'Fetch '.$id." - ".$ref.'<br>';
1403 1526
 
@@ -1419,13 +1542,19 @@  discard block
 block discarded – undo
1419 1542
                     if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1420 1543
                 }
1421 1544
 
1422
-                if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1545
+                if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
1546
+                	continue;
1547
+                }
1548
+                // We do not show orphelins files
1423 1549
 
1424 1550
                 print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1425 1551
                 print '<tr class="oddeven">';
1426 1552
                 print '<td>';
1427
-                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1428
-                else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1553
+                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
1554
+                	print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1555
+                } else {
1556
+                	print $langs->trans("ObjectDeleted",($id?$id:$ref));
1557
+                }
1429 1558
 
1430 1559
                 //$modulesubdir=dol_sanitizeFileName($ref);
1431 1560
                 $modulesubdir=dirname($relativefile);
@@ -1441,7 +1570,9 @@  discard block
 block discarded – undo
1441 1570
                 print '<td>';
1442 1571
                 //print "XX".$file['name']; //$file['name'] must be utf8
1443 1572
                 print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1444
-                if ($forcedownload) print '&attachment=1';
1573
+                if ($forcedownload) {
1574
+                	print '&attachment=1';
1575
+                }
1445 1576
                 print '&file='.urlencode($relativefile).'">';
1446 1577
                 print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1447 1578
                 print dol_trunc($file['name'],$maxlength,'middle');
@@ -1466,14 +1597,19 @@  discard block
 block discarded – undo
1466 1597
         if (count($filearray) == 0)
1467 1598
         {
1468 1599
             print '<tr '.$bc[false].'><td colspan="5">';
1469
-            if (empty($textifempty)) print $langs->trans("NoFileFound");
1470
-            else print $textifempty;
1600
+            if (empty($textifempty)) {
1601
+            	print $langs->trans("NoFileFound");
1602
+            } else {
1603
+            	print $textifempty;
1604
+            }
1471 1605
             print '</td></tr>';
1472 1606
         }
1473 1607
         print "</table>";
1474 1608
         print '</div>';
1475 1609
 
1476
-        if (! empty($addfilterfields)) print '</form>';
1610
+        if (! empty($addfilterfields)) {
1611
+        	print '</form>';
1612
+        }
1477 1613
         // Fin de zone
1478 1614
     }
1479 1615
 
@@ -1586,7 +1722,9 @@  discard block
 block discarded – undo
1586 1722
         print_liste_field_titre('','','');
1587 1723
         print '</tr>';
1588 1724
         $nboflinks = count($links);
1589
-        if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1725
+        if ($nboflinks > 0) {
1726
+        	include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1727
+        }
1590 1728
 
1591 1729
         $var = true;
1592 1730
         foreach ($links as $link)
@@ -1611,8 +1749,7 @@  discard block
 block discarded – undo
1611 1749
                 print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1612 1750
                 print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1613 1751
                 print '</td>';
1614
-            }
1615
-            else
1752
+            } else
1616 1753
 			{
1617 1754
                 print '<td>';
1618 1755
                 print img_picto('', 'object_globe').' ';
@@ -1670,8 +1807,11 @@  discard block
 block discarded – undo
1670 1807
             {
1671 1808
                 $out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1672 1809
                 //$out.= '<a class="pictopreview">';
1673
-            	if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1674
-                else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1810
+            	if (empty($ruleforpicto)) {
1811
+            		$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1812
+            	} else {
1813
+                	$out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1814
+                }
1675 1815
                 $out.= '</a>';
1676 1816
             }
1677 1817
         }
Please login to merge, or discard this patch.
Indentation   +1324 added lines, -1324 removed lines patch added patch discarded remove patch
@@ -34,289 +34,289 @@  discard block
 block discarded – undo
34 34
  */
35 35
 class FormFile
36 36
 {
37
-    private $db;
37
+	private $db;
38 38
 
39
-    public $error;
40
-    public $numoffiles;
41
-    public $infofiles;			// Used to return informations by function getDocumentsLink
39
+	public $error;
40
+	public $numoffiles;
41
+	public $infofiles;			// Used to return informations by function getDocumentsLink
42 42
 
43 43
 
44
-    /**
44
+	/**
45 45
 	 *	Constructor
46 46
 	 *
47 47
 	 *  @param		DoliDB		$db      Database handler
48
-     */
49
-    function __construct($db)
50
-    {
51
-        $this->db = $db;
52
-        $this->numoffiles=0;
53
-        return 1;
54
-    }
48
+	 */
49
+	function __construct($db)
50
+	{
51
+		$this->db = $db;
52
+		$this->numoffiles=0;
53
+		return 1;
54
+	}
55 55
 
56 56
 
57
-    /**
58
-     *  Show form to upload a new file
57
+	/**
58
+	 *  Show form to upload a new file
59 59
 	 *
60
-     *  @param  string		$url			Url
61
-     *  @param  string		$title			Title zone (Title or '' or 'none')
62
-     *  @param  int		$addcancel		1=Add 'Cancel' button
63
-     *	@param	int		$sectionid		If upload must be done inside a particular ECM section
64
-     * 	@param	int		$perm			Value of permission to allow upload
65
-     *  @param  int		$size          		Length of input file area. Deprecated.
66
-     *  @param	Object		$object			Object to use (when attachment is done on an element)
67
-     *  @param	string		$options		Add an option column
68
-     *  @param	integer		$useajax		Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used.
69
-     *  @param	string		$savingdocmask		Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
70
-     *  @param	integer		$linkfiles		1=Also add form to link files, 0=Do not show form to link files
71
-     *  @param	string		$htmlname		Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM)
72
-     *  @param	string		$accept			Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
73
-     * 	@return	int						<0 if KO, >0 if OK
74
-     */
75
-    function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='')
76
-    {
77
-        global $conf,$langs, $hookmanager;
78
-        $hookmanager->initHooks(array('formfile'));
79
-
80
-
81
-        if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
60
+	 *  @param  string		$url			Url
61
+	 *  @param  string		$title			Title zone (Title or '' or 'none')
62
+	 *  @param  int		$addcancel		1=Add 'Cancel' button
63
+	 *	@param	int		$sectionid		If upload must be done inside a particular ECM section
64
+	 * 	@param	int		$perm			Value of permission to allow upload
65
+	 *  @param  int		$size          		Length of input file area. Deprecated.
66
+	 *  @param	Object		$object			Object to use (when attachment is done on an element)
67
+	 *  @param	string		$options		Add an option column
68
+	 *  @param	integer		$useajax		Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used.
69
+	 *  @param	string		$savingdocmask		Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
70
+	 *  @param	integer		$linkfiles		1=Also add form to link files, 0=Do not show form to link files
71
+	 *  @param	string		$htmlname		Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM)
72
+	 *  @param	string		$accept			Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
73
+	 * 	@return	int						<0 if KO, >0 if OK
74
+	 */
75
+	function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='')
76
+	{
77
+		global $conf,$langs, $hookmanager;
78
+		$hookmanager->initHooks(array('formfile'));
79
+
80
+
81
+		if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
82 82
 
83 83
 		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
84
-        {
85
-        	// TODO: Check this works with 2 forms on same page
86
-        	// TODO: Check this works with GED module, otherwise, force useajax to 0
87
-        	// TODO: This does not support option savingdocmask
88
-        	// TODO: This break feature to upload links too
89
-        	return $this->_formAjaxFileUpload($object);
90
-        }
91
-        else
92
-       	{
93
-	        //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
94
-	        if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
95
-		        return 1;
96
-	        }
97
-
98
-            $maxlength=$size;
99
-
100
-            $out = "\n\n<!-- Start form attach new file -->\n";
101
-
102
-            if (empty($title)) $title=$langs->trans("AttachANewFile");
103
-            if ($title != 'none') $out.=load_fiche_titre($title, null, null);
104
-
105
-            $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
106
-            $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="">';
107
-            $out .= '<input type="hidden" id="'.$htmlname.'_section_id"  name="section_id" value="'.$sectionid.'">';
108
-            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
109
-
110
-            $out .= '<table width="100%" class="nobordernopadding">';
111
-            $out .= '<tr>';
112
-
113
-            if (! empty($options)) $out .= '<td>'.$options.'</td>';
114
-
115
-            $out .= '<td valign="middle">';
116
-
117
-            $max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
118
-            $maxphp=@ini_get('upload_max_filesize');	// En inconnu
119
-            if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
120
-            if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
121
-            if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
122
-            if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
123
-            // Now $max and $maxphp are in Kb
124
-            if ($maxphp > 0) $max=min($max,$maxphp);
125
-
126
-            if ($max > 0)
127
-            {
128
-                $out .= '<input type="hidden" name="max_file_size" value="'.($max*1024).'">';
129
-            }
130
-
131
-            $out .= '<input class="flat minwidth400" type="file"';
132
-            $out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
133
-            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
134
-            $out .= (!empty($accept)?' accept="'.$accept.'"':'accept=""');
135
-            $out .= '>';
136
-            $out .= ' ';
137
-            $out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
138
-            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
139
-            $out .= '>';
140
-
141
-            if ($addcancel)
142
-            {
143
-                $out .= ' &nbsp; ';
144
-                $out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
145
-            }
146
-
147
-            if (! empty($conf->global->MAIN_UPLOAD_DOC))
148
-            {
149
-                if ($perm)
150
-                {
151
-                	$langs->load('other');
152
-                    $out .= ' ';
153
-                    $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
154
-                }
155
-            }
156
-            else
157
-            {
158
-                $out .= ' ('.$langs->trans("UploadDisabled").')';
159
-            }
160
-            $out .= "</td></tr>";
161
-
162
-            if ($savingdocmask)
163
-            {
164
-            	$out .= '<tr>';
165
-   	            if (! empty($options)) $out .= '<td>'.$options.'</td>';
166
-	            $out .= '<td valign="middle" class="nowrap">';
84
+		{
85
+			// TODO: Check this works with 2 forms on same page
86
+			// TODO: Check this works with GED module, otherwise, force useajax to 0
87
+			// TODO: This does not support option savingdocmask
88
+			// TODO: This break feature to upload links too
89
+			return $this->_formAjaxFileUpload($object);
90
+		}
91
+		else
92
+	   	{
93
+			//If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
94
+			if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
95
+				return 1;
96
+			}
97
+
98
+			$maxlength=$size;
99
+
100
+			$out = "\n\n<!-- Start form attach new file -->\n";
101
+
102
+			if (empty($title)) $title=$langs->trans("AttachANewFile");
103
+			if ($title != 'none') $out.=load_fiche_titre($title, null, null);
104
+
105
+			$out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
106
+			$out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="">';
107
+			$out .= '<input type="hidden" id="'.$htmlname.'_section_id"  name="section_id" value="'.$sectionid.'">';
108
+			$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
109
+
110
+			$out .= '<table width="100%" class="nobordernopadding">';
111
+			$out .= '<tr>';
112
+
113
+			if (! empty($options)) $out .= '<td>'.$options.'</td>';
114
+
115
+			$out .= '<td valign="middle">';
116
+
117
+			$max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
118
+			$maxphp=@ini_get('upload_max_filesize');	// En inconnu
119
+			if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
120
+			if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
121
+			if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
122
+			if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
123
+			// Now $max and $maxphp are in Kb
124
+			if ($maxphp > 0) $max=min($max,$maxphp);
125
+
126
+			if ($max > 0)
127
+			{
128
+				$out .= '<input type="hidden" name="max_file_size" value="'.($max*1024).'">';
129
+			}
130
+
131
+			$out .= '<input class="flat minwidth400" type="file"';
132
+			$out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
133
+			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
134
+			$out .= (!empty($accept)?' accept="'.$accept.'"':'accept=""');
135
+			$out .= '>';
136
+			$out .= ' ';
137
+			$out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
138
+			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
139
+			$out .= '>';
140
+
141
+			if ($addcancel)
142
+			{
143
+				$out .= ' &nbsp; ';
144
+				$out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
145
+			}
146
+
147
+			if (! empty($conf->global->MAIN_UPLOAD_DOC))
148
+			{
149
+				if ($perm)
150
+				{
151
+					$langs->load('other');
152
+					$out .= ' ';
153
+					$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
154
+				}
155
+			}
156
+			else
157
+			{
158
+				$out .= ' ('.$langs->trans("UploadDisabled").')';
159
+			}
160
+			$out .= "</td></tr>";
161
+
162
+			if ($savingdocmask)
163
+			{
164
+				$out .= '<tr>';
165
+   				if (! empty($options)) $out .= '<td>'.$options.'</td>';
166
+				$out .= '<td valign="middle" class="nowrap">';
167 167
 				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
168
-            	$out .= '</td>';
169
-            	$out .= '</tr>';
170
-            }
171
-
172
-            $out .= "</table>";
173
-
174
-            $out .= '</form>';
175
-            if (empty($sectionid)) $out .= '<br>';
176
-
177
-            $out .= "\n<!-- End form attach new file -->\n";
178
-
179
-            if ($linkfiles)
180
-            {
181
-	            $out .= "\n<!-- Start form attach new link -->\n";
182
-	            $langs->load('link');
183
-	            $title = $langs->trans("LinkANewFile");
184
-	            $out .= load_fiche_titre($title, null, null);
185
-	            $out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">';
186
-	            $out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">';
187
-	            $out .= '<input type="hidden" id="'.$htmlname.'_link_section_id"  name="link_section_id" value="'.$sectionid.'">';
188
-	            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
-
190
-	            $out .= '<div class="valignmiddle" >';
191
-	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
192
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
193
-	            $out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
194
-	            $out .= '</div>';
195
-	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
196
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
197
-	            $out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
198
-	            $out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
199
-	            $out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
200
-	            $out .= '</div>';
201
-	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
202
-	            $out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
203
-	            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
204
-	            $out .= '>';
205
-	            $out .= '</div>';
206
-                $out .= '</div>';
207
-                $out .= '<div class="clearboth"></div>';
208
-	            $out .= '</form><br>';
209
-	            $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
210
-	            $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
211
-
212
-	            $out .= "\n<!-- End form attach new file -->\n";
213
-            }
214
-
215
-            if (empty($res))
216
-            {
217
-        		print '<div class="attacharea attacharea'.$htmlname.'">';
218
-            	print $out;
219
-            	print '</div>';
220
-            }
221
-
222
-            print $hookmanager->resPrint;
223
-
224
-            return 1;
225
-        }
226
-    }
227
-
228
-    /**
229
-     *      Show the box with list of available documents for object
230
-     *
231
-     *      @param      string				$modulepart         propal, facture, facture_fourn, ...
232
-     *      @param      string				$modulesubdir       Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
233
-     *      @param      string				$filedir            Directory to scan
234
-     *      @param      string				$urlsource          Url of origin page (for return)
235
-     *      @param      int					$genallowed         Generation is allowed (1/0 or array of formats)
236
-     *      @param      int					$delallowed         Remove is allowed (1/0)
237
-     *      @param      string				$modelselected      Model to preselect by default
238
-     *      @param      integer				$allowgenifempty	Show warning if no model activated
239
-     *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
240
-     *      @param      int					$iconPDF            Show only PDF icon with link (1/0)
241
-     * 		@param		int					$notused	        Not used
242
-     * 		@param		integer				$noform				Do not output html form tags
243
-     * 		@param		string				$param				More param on http links
244
-     * 		@param		string				$title				Title to show on top of form
245
-     * 		@param		string				$buttonlabel		Label on submit button
246
-     * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
247
-     * 		@return		int										<0 if KO, number of shown files if OK
248
-     *      @deprecated                                         Use print xxx->showdocuments() instead.
249
-     */
250
-    function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
251
-    {
252
-        $this->numoffiles=0;
253
-        print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
254
-        return $this->numoffiles;
255
-    }
256
-
257
-    /**
258
-     *      Return a string to show the box with list of available documents for object.
259
-     *      This also set the property $this->numoffiles
260
-     *
261
-     *      @param      string				$modulepart         Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...)
262
-     *      @param      string				$modulesubdir       Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
263
-     *      @param      string				$filedir            Directory to scan
264
-     *      @param      string				$urlsource          Url of origin page (for return)
265
-     *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
266
-     *      @param      int					$delallowed         Remove is allowed (1/0)
267
-     *      @param      string				$modelselected      Model to preselect by default
268
-     *      @param      integer				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
269
-     *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
270
-     *      @param      int					$iconPDF            Deprecated, see getDocumentsLink
271
-     * 		@param		int					$notused	        Not used
272
-     * 		@param		integer				$noform				Do not output html form tags
273
-     * 		@param		string				$param				More param on http links
274
-     * 		@param		string				$title				Title to show on top of form
275
-     * 		@param		string				$buttonlabel		Label on submit button
276
-     * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
277
-     * 		@param		string				$morepicto			Add more HTML content into cell with picto
278
-     *      @param      Object              $object             Object when method is called from an object card.
279
-     * 		@return		string              					Output string with HTML array of documents (might be empty string)
280
-     */
281
-    function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null)
282
-    {
168
+				$out .= '</td>';
169
+				$out .= '</tr>';
170
+			}
171
+
172
+			$out .= "</table>";
173
+
174
+			$out .= '</form>';
175
+			if (empty($sectionid)) $out .= '<br>';
176
+
177
+			$out .= "\n<!-- End form attach new file -->\n";
178
+
179
+			if ($linkfiles)
180
+			{
181
+				$out .= "\n<!-- Start form attach new link -->\n";
182
+				$langs->load('link');
183
+				$title = $langs->trans("LinkANewFile");
184
+				$out .= load_fiche_titre($title, null, null);
185
+				$out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">';
186
+				$out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">';
187
+				$out .= '<input type="hidden" id="'.$htmlname.'_link_section_id"  name="link_section_id" value="'.$sectionid.'">';
188
+				$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
+
190
+				$out .= '<div class="valignmiddle" >';
191
+				$out .= '<div class="inline-block" style="padding-right: 10px;">';
192
+				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
193
+				$out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
194
+				$out .= '</div>';
195
+				$out .= '<div class="inline-block" style="padding-right: 10px;">';
196
+				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
197
+				$out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
198
+				$out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
199
+				$out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
200
+				$out .= '</div>';
201
+				$out .= '<div class="inline-block" style="padding-right: 10px;">';
202
+				$out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
203
+				$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
204
+				$out .= '>';
205
+				$out .= '</div>';
206
+				$out .= '</div>';
207
+				$out .= '<div class="clearboth"></div>';
208
+				$out .= '</form><br>';
209
+				$parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
210
+				$res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
211
+
212
+				$out .= "\n<!-- End form attach new file -->\n";
213
+			}
214
+
215
+			if (empty($res))
216
+			{
217
+				print '<div class="attacharea attacharea'.$htmlname.'">';
218
+				print $out;
219
+				print '</div>';
220
+			}
221
+
222
+			print $hookmanager->resPrint;
223
+
224
+			return 1;
225
+		}
226
+	}
227
+
228
+	/**
229
+	 *      Show the box with list of available documents for object
230
+	 *
231
+	 *      @param      string				$modulepart         propal, facture, facture_fourn, ...
232
+	 *      @param      string				$modulesubdir       Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
233
+	 *      @param      string				$filedir            Directory to scan
234
+	 *      @param      string				$urlsource          Url of origin page (for return)
235
+	 *      @param      int					$genallowed         Generation is allowed (1/0 or array of formats)
236
+	 *      @param      int					$delallowed         Remove is allowed (1/0)
237
+	 *      @param      string				$modelselected      Model to preselect by default
238
+	 *      @param      integer				$allowgenifempty	Show warning if no model activated
239
+	 *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
240
+	 *      @param      int					$iconPDF            Show only PDF icon with link (1/0)
241
+	 * 		@param		int					$notused	        Not used
242
+	 * 		@param		integer				$noform				Do not output html form tags
243
+	 * 		@param		string				$param				More param on http links
244
+	 * 		@param		string				$title				Title to show on top of form
245
+	 * 		@param		string				$buttonlabel		Label on submit button
246
+	 * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
247
+	 * 		@return		int										<0 if KO, number of shown files if OK
248
+	 *      @deprecated                                         Use print xxx->showdocuments() instead.
249
+	 */
250
+	function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
251
+	{
252
+		$this->numoffiles=0;
253
+		print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
254
+		return $this->numoffiles;
255
+	}
256
+
257
+	/**
258
+	 *      Return a string to show the box with list of available documents for object.
259
+	 *      This also set the property $this->numoffiles
260
+	 *
261
+	 *      @param      string				$modulepart         Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...)
262
+	 *      @param      string				$modulesubdir       Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
263
+	 *      @param      string				$filedir            Directory to scan
264
+	 *      @param      string				$urlsource          Url of origin page (for return)
265
+	 *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
266
+	 *      @param      int					$delallowed         Remove is allowed (1/0)
267
+	 *      @param      string				$modelselected      Model to preselect by default
268
+	 *      @param      integer				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
269
+	 *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
270
+	 *      @param      int					$iconPDF            Deprecated, see getDocumentsLink
271
+	 * 		@param		int					$notused	        Not used
272
+	 * 		@param		integer				$noform				Do not output html form tags
273
+	 * 		@param		string				$param				More param on http links
274
+	 * 		@param		string				$title				Title to show on top of form
275
+	 * 		@param		string				$buttonlabel		Label on submit button
276
+	 * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
277
+	 * 		@param		string				$morepicto			Add more HTML content into cell with picto
278
+	 *      @param      Object              $object             Object when method is called from an object card.
279
+	 * 		@return		string              					Output string with HTML array of documents (might be empty string)
280
+	 */
281
+	function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null)
282
+	{
283 283
 		// Deprecation warning
284 284
 		if (0 !== $iconPDF) {
285 285
 			dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
286 286
 		}
287 287
 
288
-        global $langs, $conf, $user, $hookmanager;
289
-        global $form, $bc;
288
+		global $langs, $conf, $user, $hookmanager;
289
+		global $form, $bc;
290 290
 
291
-        if (! is_object($form)) $form=new Form($this->db);
291
+		if (! is_object($form)) $form=new Form($this->db);
292 292
 
293
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
293
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
294 294
 
295
-        // For backward compatibility
296
-        if (! empty($iconPDF)) {
297
-        	return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
298
-        }
295
+		// For backward compatibility
296
+		if (! empty($iconPDF)) {
297
+			return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
298
+		}
299 299
 
300
-        $printer=0;
301
-        if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport')))	// The direct print feature is implemented only for such elements
302
-        {
303
-            $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
304
-        }
300
+		$printer=0;
301
+		if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport')))	// The direct print feature is implemented only for such elements
302
+		{
303
+			$printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
304
+		}
305 305
 
306
-        $hookmanager->initHooks(array('formfile'));
307
-        $forname='builddoc';
308
-        $out='';
306
+		$hookmanager->initHooks(array('formfile'));
307
+		$forname='builddoc';
308
+		$out='';
309 309
 
310
-        $headershown=0;
311
-        $showempty=0;
312
-        $i=0;
310
+		$headershown=0;
311
+		$showempty=0;
312
+		$i=0;
313 313
 
314
-        $out.= "\n".'<!-- Start show_document -->'."\n";
315
-        //print 'filedir='.$filedir;
314
+		$out.= "\n".'<!-- Start show_document -->'."\n";
315
+		//print 'filedir='.$filedir;
316 316
 
317
-        if (preg_match('/massfilesarea_/', $modulepart))
318
-        {
319
-	        $out.='<div id="show_files"><br></div>'."\n";
317
+		if (preg_match('/massfilesarea_/', $modulepart))
318
+		{
319
+			$out.='<div id="show_files"><br></div>'."\n";
320 320
 			$title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
321 321
 			$title.='<script type="text/javascript" language="javascript">
322 322
 				jQuery(document).ready(function() {
@@ -337,373 +337,373 @@  discard block
 block discarded – undo
337 337
 					});
338 338
 				});
339 339
 				</script>';
340
-        }
341
-
342
-        $titletoshow=$langs->trans("Documents");
343
-        if (! empty($title)) $titletoshow=$title;
344
-
345
-        // Show table
346
-        if ($genallowed)
347
-        {
348
-            $modellist=array();
349
-
350
-            if ($modulepart == 'company')
351
-            {
352
-                $showempty=1;
353
-                if (is_array($genallowed)) $modellist=$genallowed;
354
-                else
355
-                {
356
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
357
-                    $modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
358
-                }
359
-            }
360
-            else if ($modulepart == 'propal')
361
-            {
362
-                if (is_array($genallowed)) $modellist=$genallowed;
363
-                else
364
-                {
365
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
366
-                    $modellist=ModelePDFPropales::liste_modeles($this->db);
367
-                }
368
-            }
340
+		}
341
+
342
+		$titletoshow=$langs->trans("Documents");
343
+		if (! empty($title)) $titletoshow=$title;
344
+
345
+		// Show table
346
+		if ($genallowed)
347
+		{
348
+			$modellist=array();
349
+
350
+			if ($modulepart == 'company')
351
+			{
352
+				$showempty=1;
353
+				if (is_array($genallowed)) $modellist=$genallowed;
354
+				else
355
+				{
356
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
357
+					$modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
358
+				}
359
+			}
360
+			else if ($modulepart == 'propal')
361
+			{
362
+				if (is_array($genallowed)) $modellist=$genallowed;
363
+				else
364
+				{
365
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
366
+					$modellist=ModelePDFPropales::liste_modeles($this->db);
367
+				}
368
+			}
369 369
 			else if ($modulepart == 'supplier_proposal')
370
-            {
371
-                if (is_array($genallowed)) $modellist=$genallowed;
372
-                else
373
-                {
374
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
375
-                    $modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
376
-                }
377
-            }
378
-            else if ($modulepart == 'commande')
379
-            {
380
-                if (is_array($genallowed)) $modellist=$genallowed;
381
-                else
382
-                {
383
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
384
-                    $modellist=ModelePDFCommandes::liste_modeles($this->db);
385
-                }
386
-            }
387
-            elseif ($modulepart == 'expedition')
388
-            {
389
-                if (is_array($genallowed)) $modellist=$genallowed;
390
-                else
391
-                {
392
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
393
-                    $modellist=ModelePDFExpedition::liste_modeles($this->db);
394
-                }
395
-            }
396
-            elseif ($modulepart == 'livraison')
397
-            {
398
-                if (is_array($genallowed)) $modellist=$genallowed;
399
-                else
400
-                {
401
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
402
-                    $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
403
-                }
404
-            }
405
-            else if ($modulepart == 'ficheinter')
406
-            {
407
-                if (is_array($genallowed)) $modellist=$genallowed;
408
-                else
409
-                {
410
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
411
-                    $modellist=ModelePDFFicheinter::liste_modeles($this->db);
412
-                }
413
-            }
414
-            elseif ($modulepart == 'facture')
415
-            {
416
-                if (is_array($genallowed)) $modellist=$genallowed;
417
-                else
418
-                {
419
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
420
-                    $modellist=ModelePDFFactures::liste_modeles($this->db);
421
-                }
422
-            }
423
-            elseif ($modulepart == 'contract')
424
-            {
425
-            	if (is_array($genallowed)) $modellist=$genallowed;
426
-            	else
427
-            	{
428
-            		include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
429
-            		$modellist=ModelePDFContract::liste_modeles($this->db);
430
-            	}
431
-            }
432
-            elseif ($modulepart == 'project')
433
-            {
434
-                if (is_array($genallowed)) $modellist=$genallowed;
435
-                else
436
-                {
437
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
438
-                    $modellist=ModelePDFProjects::liste_modeles($this->db);
439
-                }
440
-            }
441
-            elseif ($modulepart == 'project_task')
442
-            {
443
-            	if (is_array($genallowed)) $modellist=$genallowed;
444
-            	else
445
-            	{
446
-            		include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
447
-            		$modellist=ModelePDFTask::liste_modeles($this->db);
448
-            	}
449
-            }
450
-            elseif ($modulepart == 'product')
451
-            {
452
-                if (is_array($genallowed)) $modellist=$genallowed;
453
-                else
454
-                {
455
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
456
-                    $modellist=ModelePDFProduct::liste_modeles($this->db);
457
-                }
458
-            }
459
-            elseif ($modulepart == 'export')
460
-            {
461
-                if (is_array($genallowed)) $modellist=$genallowed;
462
-                else
463
-                {
464
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
465
-                    $modellist=ModeleExports::liste_modeles($this->db);
466
-                }
467
-            }
468
-            else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
469
-            {
470
-                if (is_array($genallowed)) $modellist=$genallowed;
471
-                else
472
-                {
473
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
474
-                    $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
475
-                }
476
-            }
477
-            else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
478
-            {
479
-                if (is_array($genallowed)) $modellist=$genallowed;
480
-                else
481
-                {
482
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
483
-                    $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
484
-                }
485
-            }
370
+			{
371
+				if (is_array($genallowed)) $modellist=$genallowed;
372
+				else
373
+				{
374
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
375
+					$modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
376
+				}
377
+			}
378
+			else if ($modulepart == 'commande')
379
+			{
380
+				if (is_array($genallowed)) $modellist=$genallowed;
381
+				else
382
+				{
383
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
384
+					$modellist=ModelePDFCommandes::liste_modeles($this->db);
385
+				}
386
+			}
387
+			elseif ($modulepart == 'expedition')
388
+			{
389
+				if (is_array($genallowed)) $modellist=$genallowed;
390
+				else
391
+				{
392
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
393
+					$modellist=ModelePDFExpedition::liste_modeles($this->db);
394
+				}
395
+			}
396
+			elseif ($modulepart == 'livraison')
397
+			{
398
+				if (is_array($genallowed)) $modellist=$genallowed;
399
+				else
400
+				{
401
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
402
+					$modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
403
+				}
404
+			}
405
+			else if ($modulepart == 'ficheinter')
406
+			{
407
+				if (is_array($genallowed)) $modellist=$genallowed;
408
+				else
409
+				{
410
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
411
+					$modellist=ModelePDFFicheinter::liste_modeles($this->db);
412
+				}
413
+			}
414
+			elseif ($modulepart == 'facture')
415
+			{
416
+				if (is_array($genallowed)) $modellist=$genallowed;
417
+				else
418
+				{
419
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
420
+					$modellist=ModelePDFFactures::liste_modeles($this->db);
421
+				}
422
+			}
423
+			elseif ($modulepart == 'contract')
424
+			{
425
+				if (is_array($genallowed)) $modellist=$genallowed;
426
+				else
427
+				{
428
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
429
+					$modellist=ModelePDFContract::liste_modeles($this->db);
430
+				}
431
+			}
432
+			elseif ($modulepart == 'project')
433
+			{
434
+				if (is_array($genallowed)) $modellist=$genallowed;
435
+				else
436
+				{
437
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
438
+					$modellist=ModelePDFProjects::liste_modeles($this->db);
439
+				}
440
+			}
441
+			elseif ($modulepart == 'project_task')
442
+			{
443
+				if (is_array($genallowed)) $modellist=$genallowed;
444
+				else
445
+				{
446
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
447
+					$modellist=ModelePDFTask::liste_modeles($this->db);
448
+				}
449
+			}
450
+			elseif ($modulepart == 'product')
451
+			{
452
+				if (is_array($genallowed)) $modellist=$genallowed;
453
+				else
454
+				{
455
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
456
+					$modellist=ModelePDFProduct::liste_modeles($this->db);
457
+				}
458
+			}
459
+			elseif ($modulepart == 'export')
460
+			{
461
+				if (is_array($genallowed)) $modellist=$genallowed;
462
+				else
463
+				{
464
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
465
+					$modellist=ModeleExports::liste_modeles($this->db);
466
+				}
467
+			}
468
+			else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
469
+			{
470
+				if (is_array($genallowed)) $modellist=$genallowed;
471
+				else
472
+				{
473
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
474
+					$modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
475
+				}
476
+			}
477
+			else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
478
+			{
479
+				if (is_array($genallowed)) $modellist=$genallowed;
480
+				else
481
+				{
482
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
483
+					$modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
484
+				}
485
+			}
486 486
 			else if ($modulepart == 'supplier_payment')
487 487
 			{
488
-                if (is_array($genallowed)) $modellist=$genallowed;
489
-                else
490
-                {
491
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
492
-                    $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
493
-                }
488
+				if (is_array($genallowed)) $modellist=$genallowed;
489
+				else
490
+				{
491
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
492
+					$modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
493
+				}
494 494
 			}
495
-            else if ($modulepart == 'remisecheque')
496
-            {
497
-                if (is_array($genallowed)) $modellist=$genallowed;
498
-                else
499
-                {
500
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
501
-                    $modellist=ModeleChequeReceipts::liste_modeles($this->db);
502
-                }
503
-            }
504
-            elseif ($modulepart == 'donation')
505
-            {
506
-                if (is_array($genallowed)) $modellist=$genallowed;
507
-                else
508
-                {
509
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
510
-                    $modellist=ModeleDon::liste_modeles($this->db);
511
-                }
512
-            }
513
-            elseif ($modulepart == 'member')
514
-            {
515
-                if (is_array($genallowed)) $modellist=$genallowed;
516
-                else
517
-                {
518
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
519
-                    $modellist=ModelePDFCards::liste_modeles($this->db);
520
-                }
521
-            }
522
-            elseif ($modulepart == 'agenda')
523
-            {
524
-                if (is_array($genallowed)) $modellist=$genallowed;
525
-                else
526
-                {
527
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
528
-                    $modellist=ModeleAction::liste_modeles($this->db);
529
-                }
530
-            }
531
-            else if ($modulepart == 'expensereport')
532
-            {
533
-                if (is_array($genallowed)) $modellist=$genallowed;
534
-                else
535
-                {
536
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
537
-                    $modellist=ModeleExpenseReport::liste_modeles($this->db);
538
-                }
539
-            }
540
-            else if ($modulepart == 'unpaid')
541
-            {
542
-                $modellist='';
543
-            }
544
-            elseif ($modulepart == 'user')
545
-            {
546
-                if (is_array($genallowed)) $modellist=$genallowed;
547
-                else
548
-                {
549
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
550
-                    $modellist=ModelePDFUser::liste_modeles($this->db);
551
-                }
552
-            }
553
-            elseif ($modulepart == 'usergroup')
554
-            {
555
-                if (is_array($genallowed)) $modellist=$genallowed;
556
-                else
557
-                {
558
-                    include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
559
-                    $modellist=ModelePDFUserGroup::liste_modeles($this->db);
560
-                }
561
-            }
562
-            else //if ($modulepart != 'agenda')
563
-            {
564
-            	// For normalized standard modules
565
-            	$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
566
-                if (file_exists($file))
567
-                {
568
-                	$res=include_once $file;
569
-                }
570
-                // For normalized external modules
571
-                else
495
+			else if ($modulepart == 'remisecheque')
496
+			{
497
+				if (is_array($genallowed)) $modellist=$genallowed;
498
+				else
499
+				{
500
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
501
+					$modellist=ModeleChequeReceipts::liste_modeles($this->db);
502
+				}
503
+			}
504
+			elseif ($modulepart == 'donation')
505
+			{
506
+				if (is_array($genallowed)) $modellist=$genallowed;
507
+				else
572 508
 				{
573
-                	$file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
574
-                	$res=include_once $file;
575
-                }
576
-                $class='Modele'.ucfirst($modulepart);
577
-                if (class_exists($class))
578
-                {
579
-                    $modellist=call_user_func($class.'::liste_modeles',$this->db);
580
-                }
581
-                else
582
-              {
583
-                    dol_print_error($this->db,'Bad value for modulepart');
584
-                    return -1;
585
-                }
586
-            }
587
-
588
-            // Set headershown to avoit to have table opened a second time later
589
-            $headershown=1;
590
-
591
-            $buttonlabeltoshow=$buttonlabel;
592
-            if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
593
-
594
-            if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
595
-            if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
596
-            $out.= '<input type="hidden" name="action" value="builddoc">';
597
-            $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
598
-
599
-            $out.= load_fiche_titre($titletoshow, '', '');
600
-            $out.= '<div class="div-table-responsive-no-min">';
601
-            $out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
602
-
603
-            $out.= '<tr class="liste_titre">';
604
-
605
-            $addcolumforpicto=($delallowed || $printer || $morepicto);
606
-            $out.= '<th align="center" colspan="'.(3+($addcolumforpicto?'2':'1')).'" class="formdoc liste_titre maxwidthonsmartphone">';
607
-
608
-            // Model
609
-            if (! empty($modellist))
610
-            {
611
-                $out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
612
-                if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
613
-                {
614
-                    $arraykeys=array_keys($modellist);
615
-                    $modelselected=$arraykeys[0];
616
-                }
617
-                $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
618
-                $out.= ajax_combobox('model');
619
-            }
620
-            else
621
-            {
622
-                $out.= '<div class="float">'.$langs->trans("Files").'</div>';
623
-            }
624
-
625
-            // Language code (if multilang)
626
-            if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
627
-            {
628
-                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
629
-                $formadmin=new FormAdmin($this->db);
630
-                $defaultlang=$codelang?$codelang:$langs->getDefaultLang();
631
-                $morecss='maxwidth150';
632
-                if (! empty($conf->browser->phone)) $morecss='maxwidth100';
633
-                $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
634
-            }
635
-            else
636
-            {
637
-                $out.= '&nbsp;';
638
-            }
639
-
640
-            // Button
641
-            $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
642
-            $genbutton.= ' type="submit" value="'.$buttonlabel.'"';
643
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
644
-            $genbutton.= '>';
645
-            if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
646
-            {
647
-               	$langs->load("errors");
648
-               	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
649
-            }
650
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
651
-            if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
652
-            $out.= $genbutton;
653
-            $out.= '</th>';
654
-
655
-            if (!empty($hookmanager->hooks['formfile']))
656
-            {
657
-                foreach($hookmanager->hooks['formfile'] as $module)
658
-                {
659
-                    if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
660
-                }
661
-            }
662
-            $out.= '</tr>';
663
-
664
-            // Execute hooks
665
-            $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
666
-            if (is_object($hookmanager))
667
-            {
668
-            	$reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
669
-            	$out.= $hookmanager->resPrint;
670
-            }
671
-
672
-        }
673
-
674
-        // Get list of files
675
-        if (! empty($filedir))
676
-        {
677
-            $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
678
-
679
-            $link_list = array();
680
-            if (is_object($object))
681
-            {
682
-                require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
683
-                $link = new Link($this->db);
684
-                $sortfield = $sortorder = null;
685
-                $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
686
-            }
687
-
688
-            $out.= '<!-- html.formfile::showdocuments -->'."\n";
689
-
690
-            // Show title of array if not already shown
691
-            if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown)
692
-            {
693
-                $headershown=1;
694
-                $out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
695
-                $out.= '<div class="div-table-responsive-no-min">';
696
-                $out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
697
-            }
698
-
699
-            // Loop on each file found
509
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
510
+					$modellist=ModeleDon::liste_modeles($this->db);
511
+				}
512
+			}
513
+			elseif ($modulepart == 'member')
514
+			{
515
+				if (is_array($genallowed)) $modellist=$genallowed;
516
+				else
517
+				{
518
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
519
+					$modellist=ModelePDFCards::liste_modeles($this->db);
520
+				}
521
+			}
522
+			elseif ($modulepart == 'agenda')
523
+			{
524
+				if (is_array($genallowed)) $modellist=$genallowed;
525
+				else
526
+				{
527
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
528
+					$modellist=ModeleAction::liste_modeles($this->db);
529
+				}
530
+			}
531
+			else if ($modulepart == 'expensereport')
532
+			{
533
+				if (is_array($genallowed)) $modellist=$genallowed;
534
+				else
535
+				{
536
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
537
+					$modellist=ModeleExpenseReport::liste_modeles($this->db);
538
+				}
539
+			}
540
+			else if ($modulepart == 'unpaid')
541
+			{
542
+				$modellist='';
543
+			}
544
+			elseif ($modulepart == 'user')
545
+			{
546
+				if (is_array($genallowed)) $modellist=$genallowed;
547
+				else
548
+				{
549
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
550
+					$modellist=ModelePDFUser::liste_modeles($this->db);
551
+				}
552
+			}
553
+			elseif ($modulepart == 'usergroup')
554
+			{
555
+				if (is_array($genallowed)) $modellist=$genallowed;
556
+				else
557
+				{
558
+					include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
559
+					$modellist=ModelePDFUserGroup::liste_modeles($this->db);
560
+				}
561
+			}
562
+			else //if ($modulepart != 'agenda')
563
+			{
564
+				// For normalized standard modules
565
+				$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
566
+				if (file_exists($file))
567
+				{
568
+					$res=include_once $file;
569
+				}
570
+				// For normalized external modules
571
+				else
572
+				{
573
+					$file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
574
+					$res=include_once $file;
575
+				}
576
+				$class='Modele'.ucfirst($modulepart);
577
+				if (class_exists($class))
578
+				{
579
+					$modellist=call_user_func($class.'::liste_modeles',$this->db);
580
+				}
581
+				else
582
+			  {
583
+					dol_print_error($this->db,'Bad value for modulepart');
584
+					return -1;
585
+				}
586
+			}
587
+
588
+			// Set headershown to avoit to have table opened a second time later
589
+			$headershown=1;
590
+
591
+			$buttonlabeltoshow=$buttonlabel;
592
+			if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
593
+
594
+			if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
595
+			if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
596
+			$out.= '<input type="hidden" name="action" value="builddoc">';
597
+			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
598
+
599
+			$out.= load_fiche_titre($titletoshow, '', '');
600
+			$out.= '<div class="div-table-responsive-no-min">';
601
+			$out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
602
+
603
+			$out.= '<tr class="liste_titre">';
604
+
605
+			$addcolumforpicto=($delallowed || $printer || $morepicto);
606
+			$out.= '<th align="center" colspan="'.(3+($addcolumforpicto?'2':'1')).'" class="formdoc liste_titre maxwidthonsmartphone">';
607
+
608
+			// Model
609
+			if (! empty($modellist))
610
+			{
611
+				$out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
612
+				if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
613
+				{
614
+					$arraykeys=array_keys($modellist);
615
+					$modelselected=$arraykeys[0];
616
+				}
617
+				$out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
618
+				$out.= ajax_combobox('model');
619
+			}
620
+			else
621
+			{
622
+				$out.= '<div class="float">'.$langs->trans("Files").'</div>';
623
+			}
624
+
625
+			// Language code (if multilang)
626
+			if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
627
+			{
628
+				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
629
+				$formadmin=new FormAdmin($this->db);
630
+				$defaultlang=$codelang?$codelang:$langs->getDefaultLang();
631
+				$morecss='maxwidth150';
632
+				if (! empty($conf->browser->phone)) $morecss='maxwidth100';
633
+				$out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
634
+			}
635
+			else
636
+			{
637
+				$out.= '&nbsp;';
638
+			}
639
+
640
+			// Button
641
+			$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
642
+			$genbutton.= ' type="submit" value="'.$buttonlabel.'"';
643
+			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
644
+			$genbutton.= '>';
645
+			if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
646
+			{
647
+			   	$langs->load("errors");
648
+			   	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
649
+			}
650
+			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
651
+			if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
652
+			$out.= $genbutton;
653
+			$out.= '</th>';
654
+
655
+			if (!empty($hookmanager->hooks['formfile']))
656
+			{
657
+				foreach($hookmanager->hooks['formfile'] as $module)
658
+				{
659
+					if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
660
+				}
661
+			}
662
+			$out.= '</tr>';
663
+
664
+			// Execute hooks
665
+			$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
666
+			if (is_object($hookmanager))
667
+			{
668
+				$reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
669
+				$out.= $hookmanager->resPrint;
670
+			}
671
+
672
+		}
673
+
674
+		// Get list of files
675
+		if (! empty($filedir))
676
+		{
677
+			$file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
678
+
679
+			$link_list = array();
680
+			if (is_object($object))
681
+			{
682
+				require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
683
+				$link = new Link($this->db);
684
+				$sortfield = $sortorder = null;
685
+				$res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
686
+			}
687
+
688
+			$out.= '<!-- html.formfile::showdocuments -->'."\n";
689
+
690
+			// Show title of array if not already shown
691
+			if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown)
692
+			{
693
+				$headershown=1;
694
+				$out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
695
+				$out.= '<div class="div-table-responsive-no-min">';
696
+				$out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
697
+			}
698
+
699
+			// Loop on each file found
700 700
 			if (is_array($file_list))
701 701
 			{
702 702
 				foreach($file_list as $file)
703 703
 				{
704 704
 					// Define relative path for download link (depends on module)
705 705
 					$relativepath=$file["name"];										// Cas general
706
-                    if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
706
+					if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
707 707
 					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
708 708
 
709 709
 					$out.= '<tr class="oddeven">';
@@ -713,8 +713,8 @@  discard block
 block discarded – undo
713 713
 
714 714
 					// Show file name with link to download
715 715
 					$out.= '<td class="tdoverflowmax300">';
716
-                    $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param);
717
-                    $out.= ($tmp?$tmp.' ':'');
716
+					$tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param);
717
+					$out.= ($tmp?$tmp.' ':'');
718 718
 					$out.= '<a class="documentdownload" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
719 719
 					$mime=dol_mimetype($relativepath,'',0);
720 720
 					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
@@ -746,188 +746,188 @@  discard block
 block discarded – undo
746 746
 						if ($printer)
747 747
 						{
748 748
 							//$out.= '<td align="right">';
749
-                            $out.= '&nbsp;<a href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
750
-                            $out.= ($param?'&amp;'.$param:'');
751
-                            $out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
749
+							$out.= '&nbsp;<a href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
750
+							$out.= ($param?'&amp;'.$param:'');
751
+							$out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
752 752
 						}
753 753
 						if ($morepicto)
754 754
 						{
755 755
 							$morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto);
756
-                        	$out.=$morepicto;
756
+							$out.=$morepicto;
757
+						}
758
+						$out.='</td>';
759
+					}
760
+
761
+					if (is_object($hookmanager))
762
+					{
763
+						$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
764
+						$res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
765
+						if (empty($res))
766
+						{
767
+							$out .= $hookmanager->resPrint;		// Complete line
768
+							$out.= '</tr>';
757 769
 						}
758
-                        $out.='</td>';
759
-                    }
760
-
761
-                    if (is_object($hookmanager))
762
-                    {
763
-            			$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
764
-                    	$res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
765
-                        if (empty($res))
766
-                        {
767
-                            $out .= $hookmanager->resPrint;		// Complete line
768
-                            $out.= '</tr>';
769
-                        }
770
-                        else $out = $hookmanager->resPrint;		// Replace line
771
-              		}
770
+						else $out = $hookmanager->resPrint;		// Replace line
771
+			  		}
772 772
 				}
773 773
 
774
-                $this->numoffiles++;
775
-            }
776
-            // Loop on each file found
777
-            if (is_array($link_list))
778
-            {
779
-                $colspan=2;
780
-
781
-                foreach($link_list as $file)
782
-                {
783
-                    $out.='<tr class="oddeven">';
784
-                    $out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
785
-                    $out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
786
-                    $out.=$file->label;
787
-                    $out.='</a>';
788
-                    $out.='</td>';
789
-                    $out.='<td align="right">';
790
-                    $out.=dol_print_date($file->datea,'dayhour');
791
-                    $out.='</td>';
792
-                    if ($delallowed || $printer || $morepicto) $out.='<td></td>';
793
-                    $out.='</tr>'."\n";
794
-                }
795
-                $this->numoffiles++;
796
-            }
774
+				$this->numoffiles++;
775
+			}
776
+			// Loop on each file found
777
+			if (is_array($link_list))
778
+			{
779
+				$colspan=2;
780
+
781
+				foreach($link_list as $file)
782
+				{
783
+					$out.='<tr class="oddeven">';
784
+					$out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
785
+					$out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
786
+					$out.=$file->label;
787
+					$out.='</a>';
788
+					$out.='</td>';
789
+					$out.='<td align="right">';
790
+					$out.=dol_print_date($file->datea,'dayhour');
791
+					$out.='</td>';
792
+					if ($delallowed || $printer || $morepicto) $out.='<td></td>';
793
+					$out.='</tr>'."\n";
794
+				}
795
+				$this->numoffiles++;
796
+			}
797 797
 
798 798
 		 	if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
799
-            {
800
-	        	$out.='<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
801
-    	    }
802
-
803
-        }
804
-
805
-        if ($headershown)
806
-        {
807
-            // Affiche pied du tableau
808
-            $out.= "</table>\n";
809
-            $out.= "</div>\n";
810
-            if ($genallowed)
811
-            {
812
-                if (empty($noform)) $out.= '</form>'."\n";
813
-            }
814
-        }
815
-        $out.= '<!-- End show_document -->'."\n";
816
-        //return ($i?$i:$headershown);
817
-        return $out;
818
-    }
819
-
820
-    /**
821
-     *	Show a Document icon with link(s)
822
-     *  You may want to call this into a div like this:
823
-     *  print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>';
824
-     *
825
-     *	@param	string	$modulepart		propal, facture, facture_fourn, ...
826
-     *	@param	string	$modulesubdir	Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
827
-     *	@param	string	$filedir		Full path to directory to scan
828
-     *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
829
-     *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
830
-     */
831
-    function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
832
-    {
833
-        global $conf, $langs;
834
-
835
-    	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
836
-
837
-    	$out='';
838
-    	$this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
839
-
840
-    	$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
841
-
842
-    	$file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// Get list of files starting with name of ref (but not followed by "-" to discard uploaded files)
843
-
844
-    	// For ajax treatment
799
+			{
800
+				$out.='<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
801
+			}
802
+
803
+		}
804
+
805
+		if ($headershown)
806
+		{
807
+			// Affiche pied du tableau
808
+			$out.= "</table>\n";
809
+			$out.= "</div>\n";
810
+			if ($genallowed)
811
+			{
812
+				if (empty($noform)) $out.= '</form>'."\n";
813
+			}
814
+		}
815
+		$out.= '<!-- End show_document -->'."\n";
816
+		//return ($i?$i:$headershown);
817
+		return $out;
818
+	}
819
+
820
+	/**
821
+	 *	Show a Document icon with link(s)
822
+	 *  You may want to call this into a div like this:
823
+	 *  print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>';
824
+	 *
825
+	 *	@param	string	$modulepart		propal, facture, facture_fourn, ...
826
+	 *	@param	string	$modulesubdir	Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
827
+	 *	@param	string	$filedir		Full path to directory to scan
828
+	 *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
829
+	 *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
830
+	 */
831
+	function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
832
+	{
833
+		global $conf, $langs;
834
+
835
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
836
+
837
+		$out='';
838
+		$this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
839
+
840
+		$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
841
+
842
+		$file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// Get list of files starting with name of ref (but not followed by "-" to discard uploaded files)
843
+
844
+		// For ajax treatment
845 845
 		$out.= '<!-- html.formfile::getDocumentsLink -->'."\n";
846
-    	if (! empty($file_list))
847
-    	{
848
-    	    $out='<dl class="dropdown inline-block">
846
+		if (! empty($file_list))
847
+		{
848
+			$out='<dl class="dropdown inline-block">
849 849
     			<dt><a data-ajax="false" href="#" onClick="return false;">'.img_picto('', 'listlight').'</a></dt>
850 850
     			<dd><div class="multichoicedoc" style="position:absolute;left:100px;" ><ul class="ulselectedfields" style="display: none;">';
851
-    	    $tmpout='';
852
-
853
-    		// Loop on each file found
854
-    		foreach($file_list as $file)
855
-    		{
856
-    		    $i++;
857
-    			if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
858
-
859
-    			// Define relative path for download link (depends on module)
860
-    			$relativepath=$file["name"];								// Cas general
861
-    			if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
862
-    			// Autre cas
863
-    			if ($modulepart == 'donation')            {
864
-    				$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
865
-    			}
866
-    			if ($modulepart == 'export')              {
867
-    				$relativepath = $file["name"];
868
-    			}
869
-
870
-    			$this->infofiles['nboffiles']++;
871
-    			$this->infofiles['files'][]=$file['fullname'];
872
-    			$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
873
-    			if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
874
-    			else $this->infofiles['extensions'][$ext]++;
875
-
876
-    			// Preview
877
-    			if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
878
-    			{
879
-                    $tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
880
-                    if ($tmparray && $tmparray['url']) $tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>'.img_picto('','detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
881
-    			}
882
-
883
-    			// Download
884
-    		    $tmpout.= '<li><a class="pictopreview" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
885
-    			$mime=dol_mimetype($relativepath,'',0);
886
-    			if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
887
-    			$tmpout.= '>';
888
-    			$tmpout.=img_mime($relativepath, $file["name"]).' ';
889
-    			$tmpout.= $langs->trans("Download").' '.$ext;
890
-    			$tmpout.= '</a></li>'."\n";
891
-    		}
892
-    		$out.=$tmpout;
893
-    		$out.='</ul></div></dd>
851
+			$tmpout='';
852
+
853
+			// Loop on each file found
854
+			foreach($file_list as $file)
855
+			{
856
+				$i++;
857
+				if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
858
+
859
+				// Define relative path for download link (depends on module)
860
+				$relativepath=$file["name"];								// Cas general
861
+				if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
862
+				// Autre cas
863
+				if ($modulepart == 'donation')            {
864
+					$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
865
+				}
866
+				if ($modulepart == 'export')              {
867
+					$relativepath = $file["name"];
868
+				}
869
+
870
+				$this->infofiles['nboffiles']++;
871
+				$this->infofiles['files'][]=$file['fullname'];
872
+				$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
873
+				if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
874
+				else $this->infofiles['extensions'][$ext]++;
875
+
876
+				// Preview
877
+				if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
878
+				{
879
+					$tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
880
+					if ($tmparray && $tmparray['url']) $tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>'.img_picto('','detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
881
+				}
882
+
883
+				// Download
884
+				$tmpout.= '<li><a class="pictopreview" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
885
+				$mime=dol_mimetype($relativepath,'',0);
886
+				if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
887
+				$tmpout.= '>';
888
+				$tmpout.=img_mime($relativepath, $file["name"]).' ';
889
+				$tmpout.= $langs->trans("Download").' '.$ext;
890
+				$tmpout.= '</a></li>'."\n";
891
+			}
892
+			$out.=$tmpout;
893
+			$out.='</ul></div></dd>
894 894
     			</dl>';
895
-    	}
896
-    	else
897
-    	{
898
-    	    // TODO Add link to regenerate doc ?
899
-    	    //$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
900
-    	}
901
-
902
-    	return $out;
903
-    }
904
-
905
-
906
-    /**
907
-     *  Show list of documents in $filearray (may be they are all in same directory but may not)
908
-     *  This also sync database if $upload_dir is defined.
909
-     *
910
-     *  @param	 array	$filearray          Array of files loaded by dol_dir_list('files') function before calling this.
911
-     * 	@param	 Object	$object				Object on which document is linked to.
912
-     * 	@param	 string	$modulepart			Value for modulepart used by download or viewimage wrapper.
913
-     * 	@param	 string	$param				Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd)
914
-     * 	@param	 int	$forcedownload		Force to open dialog box "Save As" when clicking on file.
915
-     * 	@param	 string	$relativepath		Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT.
916
-     * 	@param	 int	$permonobject		Permission on object (so permission to delete or crop document)
917
-     * 	@param	 int	$useinecm			Change output for use in ecm module
918
-     * 	@param	 string	$textifempty		Text to show if filearray is empty ('NoFileFound' if not defined)
919
-     *  @param   int	$maxlength          Maximum length of file name shown.
920
-     *  @param	 string	$title				Title before list
921
-     *  @param	 string $url				Full url to use for click links ('' = autodetect)
895
+		}
896
+		else
897
+		{
898
+			// TODO Add link to regenerate doc ?
899
+			//$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
900
+		}
901
+
902
+		return $out;
903
+	}
904
+
905
+
906
+	/**
907
+	 *  Show list of documents in $filearray (may be they are all in same directory but may not)
908
+	 *  This also sync database if $upload_dir is defined.
909
+	 *
910
+	 *  @param	 array	$filearray          Array of files loaded by dol_dir_list('files') function before calling this.
911
+	 * 	@param	 Object	$object				Object on which document is linked to.
912
+	 * 	@param	 string	$modulepart			Value for modulepart used by download or viewimage wrapper.
913
+	 * 	@param	 string	$param				Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd)
914
+	 * 	@param	 int	$forcedownload		Force to open dialog box "Save As" when clicking on file.
915
+	 * 	@param	 string	$relativepath		Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT.
916
+	 * 	@param	 int	$permonobject		Permission on object (so permission to delete or crop document)
917
+	 * 	@param	 int	$useinecm			Change output for use in ecm module
918
+	 * 	@param	 string	$textifempty		Text to show if filearray is empty ('NoFileFound' if not defined)
919
+	 *  @param   int	$maxlength          Maximum length of file name shown.
920
+	 *  @param	 string	$title				Title before list
921
+	 *  @param	 string $url				Full url to use for click links ('' = autodetect)
922 922
 	 *  @param	 int	$showrelpart		0=Show only filename (default), 1=Show first level 1 dir
923 923
 	 *  @param   int    $permtoeditline     Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more)
924
-     *  @param   string $upload_dir         Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes.
925
-     *  @param   string $sortfield          Sort field ('name', 'size', 'position', ...)
926
-     *  @param   string $sortorder          Sort order ('ASC' or 'DESC')
927
-     *  @param   int    $disablemove        1=Disable move button, 0=Position move is possible.
928
-     *  @param	 int	$addfilterfields	Add line with filters
929
-     * 	@return	 int						<0 if KO, nb of files shown if OK
930
-     */
924
+	 *  @param   string $upload_dir         Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes.
925
+	 *  @param   string $sortfield          Sort field ('name', 'size', 'position', ...)
926
+	 *  @param   string $sortorder          Sort order ('ASC' or 'DESC')
927
+	 *  @param   int    $disablemove        1=Disable move button, 0=Position move is possible.
928
+	 *  @param	 int	$addfilterfields	Add line with filters
929
+	 * 	@return	 int						<0 if KO, nb of files shown if OK
930
+	 */
931 931
 	function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0)
932 932
 	{
933 933
 		global $user, $conf, $langs, $hookmanager;
@@ -937,21 +937,21 @@  discard block
 block discarded – undo
937 937
 		// Define relative path used to store the file
938 938
 		if (empty($relativepath))
939 939
 		{
940
-		    $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
941
-		    if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
942
-		    if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
940
+			$relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
941
+			if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
942
+			if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
943 943
 		}
944 944
 		// For backward compatiblity, we detect file is stored into an old path
945 945
 		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos')
946 946
 		{
947
-		    $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/';
947
+			$relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/';
948 948
 		}
949 949
 		// Defined relative dir to DOL_DATA_ROOT
950 950
 		$relativedir = '';
951 951
 		if ($upload_dir)
952 952
 		{
953
-    		$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
954
-    		$relativedir = preg_replace('/^[\\/]/','',$relativedir);
953
+			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
954
+			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
955 955
 		}
956 956
 
957 957
 		$hookmanager->initHooks(array('formfile'));
@@ -981,17 +981,17 @@  discard block
 block discarded – undo
981 981
 
982 982
 			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
983 983
 			{
984
-			    $permtoeditline=0;
985
-			    if (in_array($modulepart, array('product','produit','service')))
986
-			    {
987
-			        if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
988
-			        if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
989
-			    }
984
+				$permtoeditline=0;
985
+				if (in_array($modulepart, array('product','produit','service')))
986
+				{
987
+					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
988
+					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
989
+				}
990 990
 			}
991 991
 			if (empty($conf->global->MAIN_UPLOAD_DOC))
992 992
 			{
993
-			    $permtoeditline=0;
994
-			    $permonobject=0;
993
+				$permtoeditline=0;
994
+				$permonobject=0;
995 995
 			}
996 996
 
997 997
 			// Show list of existing files
@@ -1001,10 +1001,10 @@  discard block
 block discarded – undo
1001 1001
 			print '<!-- html.formfile::list_of_documents -->'."\n";
1002 1002
 			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1003 1003
 			{
1004
-			    print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1005
-			    print '<input type="hidden" name="action" value="renamefile">';
1006
-			    print '<input type="hidden" name="id" value="'.$object->id.'">';
1007
-			    print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1004
+				print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1005
+				print '<input type="hidden" name="action" value="renamefile">';
1006
+				print '<input type="hidden" name="id" value="'.$object->id.'">';
1007
+				print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1008 1008
 			}
1009 1009
 
1010 1010
 			print '<div class="div-table-responsive-no-min">';
@@ -1038,11 +1038,11 @@  discard block
 block discarded – undo
1038 1038
 
1039 1039
 				/*var_dump($sortfield);
1040 1040
 				var_dump($sortorder);*/
1041
-    			if ($sortfield && $sortorder)
1042
-    			{
1043
-        			$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1044
-    			}
1045
-    			//var_dump($filearray);
1041
+				if ($sortfield && $sortorder)
1042
+				{
1043
+					$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1044
+				}
1045
+				//var_dump($filearray);
1046 1046
 			}
1047 1047
 
1048 1048
 			$nboffiles=count($filearray);
@@ -1059,9 +1059,9 @@  discard block
 block discarded – undo
1059 1059
 
1060 1060
 					$editline=0;
1061 1061
 					$nboflines++;
1062
-			        print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1063
-			        // Do we have entry into database ?
1064
-			        print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1062
+					print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1063
+					// Do we have entry into database ?
1064
+					print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1065 1065
 					print '<tr id="row-'.($filearray[$key]['rowid']>0?$filearray[$key]['rowid']:'-AFTER'.$lastrowid.'POS'.($i+1)).'" '.$bcdd[$var].'>';
1066 1066
 					print '<td class="tdoverflowmax300">';
1067 1067
 
@@ -1081,15 +1081,15 @@  discard block
 block discarded – undo
1081 1081
 					//print dol_trunc($file['name'],$maxlength,'middle');
1082 1082
 					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile')))
1083 1083
 					{
1084
-					    print '</a>';
1085
-					    print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1086
-					    print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1087
-					    $editline=1;
1084
+						print '</a>';
1085
+						print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1086
+						print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1087
+						$editline=1;
1088 1088
 					}
1089 1089
 					else
1090 1090
 					{
1091
-					    print $file['name'];
1092
-					    print '</a>';
1091
+						print $file['name'];
1092
+						print '</a>';
1093 1093
 					}
1094 1094
 
1095 1095
 					print "</td>\n";
@@ -1105,13 +1105,13 @@  discard block
 block discarded – undo
1105 1105
 						print '<td align="center">';
1106 1106
 						if (image_format_supported($file['name']) > 0)
1107 1107
 						{
1108
-						    $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1109
-						    if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1110
-						    //print $file['path'].'/'.$minifile.'<br>';
1108
+							$minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1109
+							if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1110
+							//print $file['path'].'/'.$minifile.'<br>';
1111 1111
 
1112
-						    $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1113
-						    if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1114
-						    print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1112
+							$urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1113
+							if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1114
+							print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1115 1115
 							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1116 1116
 							print '</a>';
1117 1117
 						}
@@ -1120,77 +1120,77 @@  discard block
 block discarded – undo
1120 1120
 					}
1121 1121
 					if (! $editline)
1122 1122
 					{
1123
-    					// Delete or view link
1124
-    					// ($param must start with &)
1125
-    					print '<td class="valignmiddle right"><!-- action on files -->';
1126
-    					if ($useinecm)
1127
-    					{
1128
-    					    print '<a href="'.DOL_URL_ROOT.'/ecm/docfile.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_view('default', 0, 'class="paddingrightonly"').'</a>';
1129
-    					}
1130
-    					else
1131
-    					{
1132
-        					$newmodulepart=$modulepart;
1133
-        					if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1134
-
1135
-        					$disablecrop=1;
1136
-        					if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0;
1137
-
1138
-    					    if (! $disablecrop && image_format_supported($file['name']) > 0)
1139
-    						{
1140
-    							if ($permtoeditline)
1141
-    							{
1142
-       								// Link to resize
1143
-       			               		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).'</a>';
1144
-    							}
1145
-    						}
1146
-
1147
-    						if ($permtoeditline)
1148
-    						{
1149
-    						    print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=editfile&urlfile='.urlencode($filepath).$param).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1150
-    						}
1151
-    					}
1152
-    					if ($permonobject)
1153
-    					{
1154
-    						/*
1123
+						// Delete or view link
1124
+						// ($param must start with &)
1125
+						print '<td class="valignmiddle right"><!-- action on files -->';
1126
+						if ($useinecm)
1127
+						{
1128
+							print '<a href="'.DOL_URL_ROOT.'/ecm/docfile.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_view('default', 0, 'class="paddingrightonly"').'</a>';
1129
+						}
1130
+						else
1131
+						{
1132
+							$newmodulepart=$modulepart;
1133
+							if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1134
+
1135
+							$disablecrop=1;
1136
+							if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0;
1137
+
1138
+							if (! $disablecrop && image_format_supported($file['name']) > 0)
1139
+							{
1140
+								if ($permtoeditline)
1141
+								{
1142
+	   								// Link to resize
1143
+	   						   		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).'</a>';
1144
+								}
1145
+							}
1146
+
1147
+							if ($permtoeditline)
1148
+							{
1149
+								print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=editfile&urlfile='.urlencode($filepath).$param).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1150
+							}
1151
+						}
1152
+						if ($permonobject)
1153
+						{
1154
+							/*
1155 1155
     						if ($file['level1name'] <> $object->id)
1156 1156
     							$filepath=$file['level1name'].'/'.$file['name'];
1157 1157
     						else
1158 1158
     							$filepath=$file['name'];
1159 1159
     						*/
1160
-    						$useajax=1;
1161
-    						if (! empty($conf->dol_use_jmobile)) $useajax=0;
1162
-    						if (empty($conf->use_javascript_ajax)) $useajax=0;
1163
-    						if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1164
-
1165
-    						print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1166
-    					}
1167
-					    print "</td>";
1168
-
1169
-					    if (empty($disablemove))
1170
-					    {
1171
-    					    if ($nboffiles > 1 && empty($conf->browser->phone)) {
1172
-    					    	print '<td align="center" class="linecolmove tdlineupdown">';
1173
-    					    	if ($i > 0) {
1174
-    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1175
-    					    	}
1176
-    					        if ($i < $nboffiles-1) {
1177
-    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1178
-    				    		}
1179
-    					    	print '</td>';
1180
-    					    }
1181
-    					    else {
1182
-    					       	print '<td align="center"'.((empty($conf->browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1183
-    					       	print '</td>';
1184
-    					    }
1160
+							$useajax=1;
1161
+							if (! empty($conf->dol_use_jmobile)) $useajax=0;
1162
+							if (empty($conf->use_javascript_ajax)) $useajax=0;
1163
+							if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1164
+
1165
+							print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1166
+						}
1167
+						print "</td>";
1168
+
1169
+						if (empty($disablemove))
1170
+						{
1171
+							if ($nboffiles > 1 && empty($conf->browser->phone)) {
1172
+								print '<td align="center" class="linecolmove tdlineupdown">';
1173
+								if ($i > 0) {
1174
+									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1175
+								}
1176
+								if ($i < $nboffiles-1) {
1177
+									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1178
+								}
1179
+								print '</td>';
1180
+							}
1181
+							else {
1182
+							   	print '<td align="center"'.((empty($conf->browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1183
+							   	print '</td>';
1184
+							}
1185 1185
 					   }
1186 1186
 					}
1187 1187
 					else
1188 1188
 					{
1189
-					    print '<td class="right">';
1190
-					    print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1191
-					    print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1192
-					    print '</td>';
1193
-					    if (empty($disablemove)) print '<td class="right"></td>';
1189
+						print '<td class="right">';
1190
+						print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1191
+						print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1192
+						print '</td>';
1193
+						if (empty($disablemove)) print '<td class="right"></td>';
1194 1194
 					}
1195 1195
 					print "</tr>\n";
1196 1196
 
@@ -1199,8 +1199,8 @@  discard block
 block discarded – undo
1199 1199
 			}
1200 1200
 			if ($nboffiles == 0)
1201 1201
 			{
1202
-			    $colspan=(empty($useinecm)?'5':'5');
1203
-			    if (empty($disablemove)) $colspan++;
1202
+				$colspan=(empty($useinecm)?'5':'5');
1203
+				if (empty($disablemove)) $colspan++;
1204 1204
 				print '<tr '.$bc[false].'><td colspan="'.$colspan.'" class="opacitymedium">';
1205 1205
 				if (empty($textifempty)) print $langs->trans("NoFileFound");
1206 1206
 				else print $textifempty;
@@ -1211,14 +1211,14 @@  discard block
 block discarded – undo
1211 1211
 
1212 1212
 			if (! $editline && $nboflines > 1) {
1213 1213
 				if (! empty($conf->use_javascript_ajax) && $permtoeditline) {
1214
-				    $table_element_line = 'ecm_files';
1215
-				    include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1214
+					$table_element_line = 'ecm_files';
1215
+					include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1216 1216
 				}
1217 1217
 			}
1218 1218
 
1219 1219
 			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1220 1220
 			{
1221
-			    print '</form>';
1221
+				print '</form>';
1222 1222
 			}
1223 1223
 
1224 1224
 			return $nboffiles;
@@ -1226,459 +1226,459 @@  discard block
 block discarded – undo
1226 1226
 	}
1227 1227
 
1228 1228
 
1229
-    /**
1230
-     *	Show list of documents in a directory
1231
-     *
1232
-     *  @param	string	$upload_dir         Directory that was scanned
1233
-     *  @param  array	$filearray          Array of files loaded by dol_dir_list function before calling this function
1234
-     *  @param  string	$modulepart         Value for modulepart used by download wrapper
1235
-     *  @param  string	$param              Parameters on sort links
1236
-     *  @param  int		$forcedownload      Force to open dialog box "Save As" when clicking on file
1237
-     *  @param  string	$relativepath       Relative path of docs (autodefined if not provided)
1238
-     *  @param  int		$permtodelete       Permission to delete
1239
-     *  @param  int		$useinecm           Change output for use in ecm module
1240
-     *  @param  int		$textifempty        Text to show if filearray is empty
1241
-     *  @param  int		$maxlength          Maximum length of file name shown
1242
-     *  @param	string 	$url				Full url to use for click links ('' = autodetect)
1243
-     *  @param	int		$addfilterfields	Add line with filters
1244
-     *  @return int                 		<0 if KO, nb of files shown if OK
1245
-     */
1246
-    function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0)
1247
-    {
1248
-        global $user, $conf, $langs, $form;
1249
-        global $bc;
1250
-        global $sortfield, $sortorder;
1229
+	/**
1230
+	 *	Show list of documents in a directory
1231
+	 *
1232
+	 *  @param	string	$upload_dir         Directory that was scanned
1233
+	 *  @param  array	$filearray          Array of files loaded by dol_dir_list function before calling this function
1234
+	 *  @param  string	$modulepart         Value for modulepart used by download wrapper
1235
+	 *  @param  string	$param              Parameters on sort links
1236
+	 *  @param  int		$forcedownload      Force to open dialog box "Save As" when clicking on file
1237
+	 *  @param  string	$relativepath       Relative path of docs (autodefined if not provided)
1238
+	 *  @param  int		$permtodelete       Permission to delete
1239
+	 *  @param  int		$useinecm           Change output for use in ecm module
1240
+	 *  @param  int		$textifempty        Text to show if filearray is empty
1241
+	 *  @param  int		$maxlength          Maximum length of file name shown
1242
+	 *  @param	string 	$url				Full url to use for click links ('' = autodetect)
1243
+	 *  @param	int		$addfilterfields	Add line with filters
1244
+	 *  @return int                 		<0 if KO, nb of files shown if OK
1245
+	 */
1246
+	function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0)
1247
+	{
1248
+		global $user, $conf, $langs, $form;
1249
+		global $bc;
1250
+		global $sortfield, $sortorder;
1251 1251
 		global $search_doc_ref;
1252 1252
 
1253
-        dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1253
+		dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1254 1254
 
1255
-        // Show list of documents
1256
-        if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1257
-        if (empty($url)) $url=$_SERVER["PHP_SELF"];
1255
+		// Show list of documents
1256
+		if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1257
+		if (empty($url)) $url=$_SERVER["PHP_SELF"];
1258 1258
 
1259
-        if (! empty($addfilterfields))
1260
-        {
1261
-        	print '<form action="'.$_SERVER['PHP_SELF'].'">';
1262
-        	print '<input type="hidden" name="module" value="'.$modulepart.'">';
1263
-        }
1259
+		if (! empty($addfilterfields))
1260
+		{
1261
+			print '<form action="'.$_SERVER['PHP_SELF'].'">';
1262
+			print '<input type="hidden" name="module" value="'.$modulepart.'">';
1263
+		}
1264 1264
 
1265 1265
 		print '<div class="div-table-responsive-no-min">';
1266
-        print '<table width="100%" class="noborder">'."\n";
1267
-
1268
-        if (! empty($addfilterfields))
1269
-        {
1270
-        	print '<tr class="liste_titre nodrag nodrop">';
1271
-        	print '<td><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
1272
-        	print '<td></td>';
1273
-        	print '<td></td>';
1274
-        	print '<td></td>';
1266
+		print '<table width="100%" class="noborder">'."\n";
1267
+
1268
+		if (! empty($addfilterfields))
1269
+		{
1270
+			print '<tr class="liste_titre nodrag nodrop">';
1271
+			print '<td><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
1272
+			print '<td></td>';
1273
+			print '<td></td>';
1274
+			print '<td></td>';
1275 1275
 			// Action column
1276 1276
 			print '<td class="liste_titre" align="middle">';
1277 1277
 			$searchpicto=$form->showFilterButtons();
1278 1278
 			print $searchpicto;
1279 1279
 			print '</td>';
1280
-        	print "</tr>\n";
1281
-        }
1282
-
1283
-        print '<tr class="liste_titre">';
1284
-        $sortref="fullname";
1285
-        if ($modulepart == 'invoice_supplier') $sortref='level1name';
1286
-        print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1287
-        print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1288
-        print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1289
-        print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1290
-        print_liste_field_titre('','','');
1291
-        print '</tr>'."\n";
1292
-
1293
-        // To show ref or specific information according to view to show (defined by $module)
1294
-        if ($modulepart == 'company')
1295
-        {
1296
-            include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1297
-            $object_instance=new Societe($this->db);
1298
-        }
1299
-        else if ($modulepart == 'invoice')
1300
-        {
1301
-            include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1302
-            $object_instance=new Facture($this->db);
1303
-        }
1304
-        else if ($modulepart == 'invoice_supplier')
1305
-        {
1306
-            include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1307
-            $object_instance=new FactureFournisseur($this->db);
1308
-        }
1309
-        else if ($modulepart == 'propal')
1310
-        {
1311
-            include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1312
-            $object_instance=new Propal($this->db);
1313
-        }
1314
-        else if ($modulepart == 'supplier_proposal')
1315
-        {
1316
-            include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1317
-            $object_instance=new SupplierProposal($this->db);
1318
-        }
1319
-        else if ($modulepart == 'order')
1320
-        {
1321
-            include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1322
-            $object_instance=new Commande($this->db);
1323
-        }
1324
-        else if ($modulepart == 'order_supplier')
1325
-        {
1326
-            include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1327
-            $object_instance=new CommandeFournisseur($this->db);
1328
-        }
1329
-        else if ($modulepart == 'contract')
1330
-        {
1331
-            include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1332
-            $object_instance=new Contrat($this->db);
1333
-        }
1334
-        else if ($modulepart == 'product')
1335
-        {
1336
-            include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1337
-            $object_instance=new Product($this->db);
1338
-        }
1339
-        else if ($modulepart == 'tax')
1340
-        {
1341
-            include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1342
-            $object_instance=new ChargeSociales($this->db);
1343
-        }
1344
-        else if ($modulepart == 'project')
1345
-        {
1346
-        	include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1347
-        	$object_instance=new Project($this->db);
1348
-        }
1349
-        else if ($modulepart == 'fichinter')
1350
-        {
1351
-        	include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1352
-        	$object_instance=new Fichinter($this->db);
1353
-        }
1354
-        else if ($modulepart == 'user')
1355
-        {
1356
-        	include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1357
-        	$object_instance=new User($this->db);
1358
-        }
1359
-        else if ($modulepart == 'expensereport')
1360
-        {
1361
-        	include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1362
-        	$object_instance=new ExpenseReport($this->db);
1363
-        }
1364
-
1365
-        $var=true;
1366
-        foreach($filearray as $key => $file)
1367
-        {
1368
-        	if (!is_dir($file['name'])
1369
-            && $file['name'] != '.'
1370
-            && $file['name'] != '..'
1371
-            && $file['name'] != 'CVS'
1372
-            && ! preg_match('/\.meta$/i',$file['name']))
1373
-            {
1374
-                // Define relative path used to store the file
1375
-                $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1376
-
1377
-                //var_dump($file);
1378
-                $id=0; $ref=''; $label='';
1379
-
1380
-                // To show ref or specific information according to view to show (defined by $module)
1381
-                if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1382
-                if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1383
-                if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1384
-                if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1280
+			print "</tr>\n";
1281
+		}
1282
+
1283
+		print '<tr class="liste_titre">';
1284
+		$sortref="fullname";
1285
+		if ($modulepart == 'invoice_supplier') $sortref='level1name';
1286
+		print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1287
+		print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1288
+		print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1289
+		print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1290
+		print_liste_field_titre('','','');
1291
+		print '</tr>'."\n";
1292
+
1293
+		// To show ref or specific information according to view to show (defined by $module)
1294
+		if ($modulepart == 'company')
1295
+		{
1296
+			include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1297
+			$object_instance=new Societe($this->db);
1298
+		}
1299
+		else if ($modulepart == 'invoice')
1300
+		{
1301
+			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1302
+			$object_instance=new Facture($this->db);
1303
+		}
1304
+		else if ($modulepart == 'invoice_supplier')
1305
+		{
1306
+			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1307
+			$object_instance=new FactureFournisseur($this->db);
1308
+		}
1309
+		else if ($modulepart == 'propal')
1310
+		{
1311
+			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1312
+			$object_instance=new Propal($this->db);
1313
+		}
1314
+		else if ($modulepart == 'supplier_proposal')
1315
+		{
1316
+			include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1317
+			$object_instance=new SupplierProposal($this->db);
1318
+		}
1319
+		else if ($modulepart == 'order')
1320
+		{
1321
+			include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1322
+			$object_instance=new Commande($this->db);
1323
+		}
1324
+		else if ($modulepart == 'order_supplier')
1325
+		{
1326
+			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1327
+			$object_instance=new CommandeFournisseur($this->db);
1328
+		}
1329
+		else if ($modulepart == 'contract')
1330
+		{
1331
+			include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1332
+			$object_instance=new Contrat($this->db);
1333
+		}
1334
+		else if ($modulepart == 'product')
1335
+		{
1336
+			include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1337
+			$object_instance=new Product($this->db);
1338
+		}
1339
+		else if ($modulepart == 'tax')
1340
+		{
1341
+			include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1342
+			$object_instance=new ChargeSociales($this->db);
1343
+		}
1344
+		else if ($modulepart == 'project')
1345
+		{
1346
+			include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1347
+			$object_instance=new Project($this->db);
1348
+		}
1349
+		else if ($modulepart == 'fichinter')
1350
+		{
1351
+			include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1352
+			$object_instance=new Fichinter($this->db);
1353
+		}
1354
+		else if ($modulepart == 'user')
1355
+		{
1356
+			include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1357
+			$object_instance=new User($this->db);
1358
+		}
1359
+		else if ($modulepart == 'expensereport')
1360
+		{
1361
+			include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1362
+			$object_instance=new ExpenseReport($this->db);
1363
+		}
1364
+
1365
+		$var=true;
1366
+		foreach($filearray as $key => $file)
1367
+		{
1368
+			if (!is_dir($file['name'])
1369
+			&& $file['name'] != '.'
1370
+			&& $file['name'] != '..'
1371
+			&& $file['name'] != 'CVS'
1372
+			&& ! preg_match('/\.meta$/i',$file['name']))
1373
+			{
1374
+				// Define relative path used to store the file
1375
+				$relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1376
+
1377
+				//var_dump($file);
1378
+				$id=0; $ref=''; $label='';
1379
+
1380
+				// To show ref or specific information according to view to show (defined by $module)
1381
+				if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1382
+				if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1383
+				if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1384
+				if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1385 1385
 				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1386
-                if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1387
-                if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1388
-                if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1389
-                if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1390
-                if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1391
-                if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1392
-                if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1393
-                if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1394
-                if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1395
-
1396
-                if (! $id && ! $ref) continue;
1397
-                $found=0;
1398
-                if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1399
-                {
1400
-                    $found=1;
1401
-                }
1402
-                else
1403
-                {
1404
-                    //print 'Fetch '.$id." - ".$ref.'<br>';
1405
-
1406
-                    if ($id) {
1407
-                        $result = $object_instance->fetch($id);
1408
-                    } else {
1409
-                        //fetchOneLike looks for objects with wildcards in its reference.
1410
-                        //It is useful for those masks who get underscores instead of their actual symbols
1411
-                        //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned
1412
-                        //that's why we look only look fetchOneLike when fetch returns 0
1413
-                        if (!$result = $object_instance->fetch('', $ref)) {
1414
-                            $result = $object_instance->fetchOneLike($ref);
1415
-                        }
1416
-                    }
1386
+				if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1387
+				if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1388
+				if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1389
+				if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1390
+				if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1391
+				if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1392
+				if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1393
+				if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1394
+				if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1395
+
1396
+				if (! $id && ! $ref) continue;
1397
+				$found=0;
1398
+				if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1399
+				{
1400
+					$found=1;
1401
+				}
1402
+				else
1403
+				{
1404
+					//print 'Fetch '.$id." - ".$ref.'<br>';
1405
+
1406
+					if ($id) {
1407
+						$result = $object_instance->fetch($id);
1408
+					} else {
1409
+						//fetchOneLike looks for objects with wildcards in its reference.
1410
+						//It is useful for those masks who get underscores instead of their actual symbols
1411
+						//fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned
1412
+						//that's why we look only look fetchOneLike when fetch returns 0
1413
+						if (!$result = $object_instance->fetch('', $ref)) {
1414
+							$result = $object_instance->fetchOneLike($ref);
1415
+						}
1416
+					}
1417 1417
 
1418 1418
 					if ($result > 0) {  // Save object into a cache
1419 1419
 						$found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1420 1420
 					}
1421
-                    if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1422
-                }
1423
-
1424
-                if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1425
-
1426
-                print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1427
-                print '<tr class="oddeven">';
1428
-                print '<td>';
1429
-                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1430
-                else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1431
-
1432
-                //$modulesubdir=dol_sanitizeFileName($ref);
1433
-                $modulesubdir=dirname($relativefile);
1434
-
1435
-                //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1436
-                $filedir=$file['path'];
1437
-                //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1438
-                //print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1439
-
1440
-                print '</td>';
1441
-
1442
-                // File
1443
-                print '<td>';
1444
-                //print "XX".$file['name']; //$file['name'] must be utf8
1445
-                print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1446
-                if ($forcedownload) print '&attachment=1';
1447
-                print '&file='.urlencode($relativefile).'">';
1448
-                print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1449
-                print dol_trunc($file['name'],$maxlength,'middle');
1450
-                print '</a>';
1451
-
1452
-                print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1453
-
1454
-                print "</td>\n";
1455
-                print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1456
-                print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1457
-                print '<td align="right">';
1458
-                //if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1459
-                //if ($forcedownload) print '&attachment=1';
1460
-                //print '&file='.urlencode($relativefile).'">';
1461
-                //print img_view().'</a> &nbsp; ';
1462
-                //if ($permtodelete) print '<a href="'.$url.'?id='.$object->id.'&section='.$_REQUEST["section"].'&action=delete&urlfile='.urlencode($file['name']).'">'.img_delete().'</a>';
1463
-                //else print '&nbsp;';
1464
-                print "</td></tr>\n";
1465
-            }
1466
-        }
1467
-
1468
-        if (count($filearray) == 0)
1469
-        {
1470
-            print '<tr '.$bc[false].'><td colspan="5">';
1471
-            if (empty($textifempty)) print $langs->trans("NoFileFound");
1472
-            else print $textifempty;
1473
-            print '</td></tr>';
1474
-        }
1475
-        print "</table>";
1476
-        print '</div>';
1477
-
1478
-        if (! empty($addfilterfields)) print '</form>';
1479
-        // Fin de zone
1480
-    }
1481
-
1482
-    /**
1483
-     *    Show form to upload a new file with jquery fileupload.
1484
-     *    This form use the fileupload.php file.
1485
-     *
1486
-     *    @param	Object	$object		Object to use
1487
-     *    @return	void
1488
-     */
1489
-    private function _formAjaxFileUpload($object)
1490
-    {
1491
-        global $langs;
1492
-
1493
-        // PHP post_max_size
1494
-        $post_max_size				= ini_get('post_max_size');
1495
-        $mul_post_max_size			= substr($post_max_size, -1);
1496
-        $mul_post_max_size			= ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1)));
1497
-        $post_max_size				= $mul_post_max_size * (int) $post_max_size;
1498
-        // PHP upload_max_filesize
1499
-        $upload_max_filesize		= ini_get('upload_max_filesize');
1500
-        $mul_upload_max_filesize	= substr($upload_max_filesize, -1);
1501
-        $mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1502
-        $upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1503
-        // Max file size
1504
-        $max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1505
-
1506
-        // Include main
1507
-        include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
1508
-
1509
-        // Include template
1510
-        include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php';
1511
-
1512
-    }
1513
-
1514
-    /**
1515
-     * Show array with linked files
1516
-     *
1517
-     * @param 	Object		$object			Object
1518
-     * @param 	int			$permtodelete	Deletion is allowed
1519
-     * @param 	string		$action			Action
1520
-     * @param 	string		$selected		???
1521
-     * @param	string		$param			More param to add into URL
1522
-     * @return 	int							Number of links
1523
-     */
1524
-    public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1525
-    {
1526
-        global $user, $conf, $langs, $user;
1527
-        global $bc;
1528
-        global $sortfield, $sortorder;
1529
-
1530
-        $langs->load("link");
1531
-
1532
-        require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1533
-        $link = new Link($this->db);
1534
-        $links = array();
1535
-        if ($sortfield == "name") {
1536
-            $sortfield = "label";
1537
-        } elseif ($sortfield == "date") {
1538
-            $sortfield = "datea";
1539
-        } else {
1540
-            $sortfield = null;
1541
-        }
1542
-        $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1543
-        $param .= (isset($object->id)?'&id=' . $object->id : '');
1544
-
1545
-        // Show list of associated links
1546
-        print load_fiche_titre($langs->trans("LinkedFiles"));
1547
-
1548
-        print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1549
-
1550
-        print '<table width="100%" class="liste">';
1551
-        print '<tr class="liste_titre">';
1552
-        print_liste_field_titre(
1553
-            $langs->trans("Links"),
1554
-            $_SERVER['PHP_SELF'],
1555
-            "name",
1556
-            "",
1557
-            $param,
1558
-            'align="left"',
1559
-            $sortfield,
1560
-            $sortorder
1561
-        );
1562
-        print_liste_field_titre(
1563
-            "",
1564
-            "",
1565
-            "",
1566
-            "",
1567
-            "",
1568
-            'align="right"'
1569
-        );
1570
-        print_liste_field_titre(
1571
-            $langs->trans("Date"),
1572
-            $_SERVER['PHP_SELF'],
1573
-            "date",
1574
-            "",
1575
-            $param,
1576
-            'align="center"',
1577
-            $sortfield,
1578
-            $sortorder
1579
-        );
1580
-        print_liste_field_titre(
1581
-            '',
1582
-            $_SERVER['PHP_SELF'],
1583
-            "",
1584
-            "",
1585
-            $param,
1586
-            'align="center"'
1587
-        );
1588
-        print_liste_field_titre('','','');
1589
-        print '</tr>';
1590
-        $nboflinks = count($links);
1591
-        if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1592
-
1593
-        $var = true;
1594
-        foreach ($links as $link)
1595
-        {
1596
-            $var =! $var;
1597
-            print '<tr ' . $bc[$var] . '>';
1598
-            //edit mode
1599
-            if ($action == 'update' && $selected === $link->id)
1600
-            {
1601
-                print '<td>';
1602
-                print '<input type="hidden" name="id" value="' . $object->id . '">';
1603
-                print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1604
-                print '<input type="hidden" name="action" value="confirm_updateline">';
1605
-                print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1606
-                print '</td>';
1607
-                print '<td>';
1608
-                print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1609
-                print '</td>';
1610
-                print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1611
-                print '<td align="right"></td>';
1612
-                print '<td align="right">';
1613
-                print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1614
-                print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1615
-                print '</td>';
1616
-            }
1617
-            else
1421
+					if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1422
+				}
1423
+
1424
+				if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1425
+
1426
+				print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1427
+				print '<tr class="oddeven">';
1428
+				print '<td>';
1429
+				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1430
+				else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1431
+
1432
+				//$modulesubdir=dol_sanitizeFileName($ref);
1433
+				$modulesubdir=dirname($relativefile);
1434
+
1435
+				//$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1436
+				$filedir=$file['path'];
1437
+				//$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1438
+				//print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1439
+
1440
+				print '</td>';
1441
+
1442
+				// File
1443
+				print '<td>';
1444
+				//print "XX".$file['name']; //$file['name'] must be utf8
1445
+				print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1446
+				if ($forcedownload) print '&attachment=1';
1447
+				print '&file='.urlencode($relativefile).'">';
1448
+				print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1449
+				print dol_trunc($file['name'],$maxlength,'middle');
1450
+				print '</a>';
1451
+
1452
+				print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1453
+
1454
+				print "</td>\n";
1455
+				print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1456
+				print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1457
+				print '<td align="right">';
1458
+				//if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1459
+				//if ($forcedownload) print '&attachment=1';
1460
+				//print '&file='.urlencode($relativefile).'">';
1461
+				//print img_view().'</a> &nbsp; ';
1462
+				//if ($permtodelete) print '<a href="'.$url.'?id='.$object->id.'&section='.$_REQUEST["section"].'&action=delete&urlfile='.urlencode($file['name']).'">'.img_delete().'</a>';
1463
+				//else print '&nbsp;';
1464
+				print "</td></tr>\n";
1465
+			}
1466
+		}
1467
+
1468
+		if (count($filearray) == 0)
1469
+		{
1470
+			print '<tr '.$bc[false].'><td colspan="5">';
1471
+			if (empty($textifempty)) print $langs->trans("NoFileFound");
1472
+			else print $textifempty;
1473
+			print '</td></tr>';
1474
+		}
1475
+		print "</table>";
1476
+		print '</div>';
1477
+
1478
+		if (! empty($addfilterfields)) print '</form>';
1479
+		// Fin de zone
1480
+	}
1481
+
1482
+	/**
1483
+	 *    Show form to upload a new file with jquery fileupload.
1484
+	 *    This form use the fileupload.php file.
1485
+	 *
1486
+	 *    @param	Object	$object		Object to use
1487
+	 *    @return	void
1488
+	 */
1489
+	private function _formAjaxFileUpload($object)
1490
+	{
1491
+		global $langs;
1492
+
1493
+		// PHP post_max_size
1494
+		$post_max_size				= ini_get('post_max_size');
1495
+		$mul_post_max_size			= substr($post_max_size, -1);
1496
+		$mul_post_max_size			= ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1)));
1497
+		$post_max_size				= $mul_post_max_size * (int) $post_max_size;
1498
+		// PHP upload_max_filesize
1499
+		$upload_max_filesize		= ini_get('upload_max_filesize');
1500
+		$mul_upload_max_filesize	= substr($upload_max_filesize, -1);
1501
+		$mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1502
+		$upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1503
+		// Max file size
1504
+		$max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1505
+
1506
+		// Include main
1507
+		include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
1508
+
1509
+		// Include template
1510
+		include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php';
1511
+
1512
+	}
1513
+
1514
+	/**
1515
+	 * Show array with linked files
1516
+	 *
1517
+	 * @param 	Object		$object			Object
1518
+	 * @param 	int			$permtodelete	Deletion is allowed
1519
+	 * @param 	string		$action			Action
1520
+	 * @param 	string		$selected		???
1521
+	 * @param	string		$param			More param to add into URL
1522
+	 * @return 	int							Number of links
1523
+	 */
1524
+	public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1525
+	{
1526
+		global $user, $conf, $langs, $user;
1527
+		global $bc;
1528
+		global $sortfield, $sortorder;
1529
+
1530
+		$langs->load("link");
1531
+
1532
+		require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1533
+		$link = new Link($this->db);
1534
+		$links = array();
1535
+		if ($sortfield == "name") {
1536
+			$sortfield = "label";
1537
+		} elseif ($sortfield == "date") {
1538
+			$sortfield = "datea";
1539
+		} else {
1540
+			$sortfield = null;
1541
+		}
1542
+		$res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1543
+		$param .= (isset($object->id)?'&id=' . $object->id : '');
1544
+
1545
+		// Show list of associated links
1546
+		print load_fiche_titre($langs->trans("LinkedFiles"));
1547
+
1548
+		print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1549
+
1550
+		print '<table width="100%" class="liste">';
1551
+		print '<tr class="liste_titre">';
1552
+		print_liste_field_titre(
1553
+			$langs->trans("Links"),
1554
+			$_SERVER['PHP_SELF'],
1555
+			"name",
1556
+			"",
1557
+			$param,
1558
+			'align="left"',
1559
+			$sortfield,
1560
+			$sortorder
1561
+		);
1562
+		print_liste_field_titre(
1563
+			"",
1564
+			"",
1565
+			"",
1566
+			"",
1567
+			"",
1568
+			'align="right"'
1569
+		);
1570
+		print_liste_field_titre(
1571
+			$langs->trans("Date"),
1572
+			$_SERVER['PHP_SELF'],
1573
+			"date",
1574
+			"",
1575
+			$param,
1576
+			'align="center"',
1577
+			$sortfield,
1578
+			$sortorder
1579
+		);
1580
+		print_liste_field_titre(
1581
+			'',
1582
+			$_SERVER['PHP_SELF'],
1583
+			"",
1584
+			"",
1585
+			$param,
1586
+			'align="center"'
1587
+		);
1588
+		print_liste_field_titre('','','');
1589
+		print '</tr>';
1590
+		$nboflinks = count($links);
1591
+		if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1592
+
1593
+		$var = true;
1594
+		foreach ($links as $link)
1595
+		{
1596
+			$var =! $var;
1597
+			print '<tr ' . $bc[$var] . '>';
1598
+			//edit mode
1599
+			if ($action == 'update' && $selected === $link->id)
1600
+			{
1601
+				print '<td>';
1602
+				print '<input type="hidden" name="id" value="' . $object->id . '">';
1603
+				print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1604
+				print '<input type="hidden" name="action" value="confirm_updateline">';
1605
+				print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1606
+				print '</td>';
1607
+				print '<td>';
1608
+				print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1609
+				print '</td>';
1610
+				print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1611
+				print '<td align="right"></td>';
1612
+				print '<td align="right">';
1613
+				print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1614
+				print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1615
+				print '</td>';
1616
+			}
1617
+			else
1618
+			{
1619
+				print '<td>';
1620
+				print img_picto('', 'object_globe').' ';
1621
+				print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1622
+				print $link->label;
1623
+				print '</a>';
1624
+				print '</td>'."\n";
1625
+				print '<td align="right"></td>';
1626
+				print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1627
+				print '<td align="center"></td>';
1628
+				print '<td align="right">';
1629
+				print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1630
+				if ($permtodelete) {
1631
+					print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1632
+				} else {
1633
+					print '&nbsp;';
1634
+				}
1635
+				print '</td>';
1636
+			}
1637
+			print "</tr>\n";
1638
+		}
1639
+		if ($nboflinks == 0)
1640
+		{
1641
+			print '<tr ' . $bc[false] . '><td colspan="5" class="opacitymedium">';
1642
+			print $langs->trans("NoLinkFound");
1643
+			print '</td></tr>';
1644
+		}
1645
+		print "</table>";
1646
+
1647
+		print '</form>';
1648
+
1649
+		return $nboflinks;
1650
+	}
1651
+
1652
+
1653
+	/**
1654
+	 * Show detail icon with link for preview
1655
+	 *
1656
+	 * @param   array     $file           File
1657
+	 * @param   string    $modulepart     propal, facture, facture_fourn, ...
1658
+	 * @param   string    $relativepath   Relative path of docs
1659
+	 * @param   string    $ruleforpicto   Rule for picto: 0=Preview picto, 1=Use picto of mime type of file)
1660
+	 * @param	string	  $param		  More param on http links
1661
+	 * @return  string    $out            Output string with HTML
1662
+	 */
1663
+	public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1664
+	{
1665
+		global $langs, $conf;
1666
+
1667
+		$out='';
1668
+		if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1669
+		{
1670
+			$urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1671
+			if (count($urladvancedpreview))
1618 1672
 			{
1619
-                print '<td>';
1620
-                print img_picto('', 'object_globe').' ';
1621
-                print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1622
-                print $link->label;
1623
-                print '</a>';
1624
-                print '</td>'."\n";
1625
-                print '<td align="right"></td>';
1626
-                print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1627
-                print '<td align="center"></td>';
1628
-                print '<td align="right">';
1629
-                print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1630
-                if ($permtodelete) {
1631
-                    print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1632
-                } else {
1633
-                    print '&nbsp;';
1634
-                }
1635
-                print '</td>';
1636
-            }
1637
-            print "</tr>\n";
1638
-        }
1639
-        if ($nboflinks == 0)
1640
-        {
1641
-            print '<tr ' . $bc[false] . '><td colspan="5" class="opacitymedium">';
1642
-            print $langs->trans("NoLinkFound");
1643
-            print '</td></tr>';
1644
-        }
1645
-        print "</table>";
1646
-
1647
-        print '</form>';
1648
-
1649
-        return $nboflinks;
1650
-    }
1651
-
1652
-
1653
-    /**
1654
-     * Show detail icon with link for preview
1655
-     *
1656
-     * @param   array     $file           File
1657
-     * @param   string    $modulepart     propal, facture, facture_fourn, ...
1658
-     * @param   string    $relativepath   Relative path of docs
1659
-     * @param   string    $ruleforpicto   Rule for picto: 0=Preview picto, 1=Use picto of mime type of file)
1660
-     * @param	string	  $param		  More param on http links
1661
-     * @return  string    $out            Output string with HTML
1662
-     */
1663
-    public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1664
-    {
1665
-        global $langs, $conf;
1666
-
1667
-        $out='';
1668
-        if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1669
-        {
1670
-            $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1671
-            if (count($urladvancedpreview))
1672
-            {
1673
-                $out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1674
-                //$out.= '<a class="pictopreview">';
1675
-            	if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1676
-                else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1677
-                $out.= '</a>';
1678
-            }
1679
-        }
1680
-        return $out;
1681
-    }
1673
+				$out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1674
+				//$out.= '<a class="pictopreview">';
1675
+				if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1676
+				else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1677
+				$out.= '</a>';
1678
+			}
1679
+		}
1680
+		return $out;
1681
+	}
1682 1682
 
1683 1683
 }
1684 1684
 
Please login to merge, or discard this patch.
Spacing   +408 added lines, -408 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 
39 39
     public $error;
40 40
     public $numoffiles;
41
-    public $infofiles;			// Used to return informations by function getDocumentsLink
41
+    public $infofiles; // Used to return informations by function getDocumentsLink
42 42
 
43 43
 
44 44
     /**
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
     function __construct($db)
50 50
     {
51 51
         $this->db = $db;
52
-        $this->numoffiles=0;
52
+        $this->numoffiles = 0;
53 53
         return 1;
54 54
     }
55 55
 
@@ -72,15 +72,15 @@  discard block
 block discarded – undo
72 72
      *  @param	string		$accept			Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
73 73
      * 	@return	int						<0 if KO, >0 if OK
74 74
      */
75
-    function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='')
75
+    function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '')
76 76
     {
77
-        global $conf,$langs, $hookmanager;
77
+        global $conf, $langs, $hookmanager;
78 78
         $hookmanager->initHooks(array('formfile'));
79 79
 
80 80
 
81
-        if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
81
+        if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax = 0;
82 82
 
83
-		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
83
+		if ((!empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax == 2))
84 84
         {
85 85
         	// TODO: Check this works with 2 forms on same page
86 86
         	// TODO: Check this works with GED module, otherwise, force useajax to 0
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
 		        return 1;
96 96
 	        }
97 97
 
98
-            $maxlength=$size;
98
+            $maxlength = $size;
99 99
 
100 100
             $out = "\n\n<!-- Start form attach new file -->\n";
101 101
 
102
-            if (empty($title)) $title=$langs->trans("AttachANewFile");
103
-            if ($title != 'none') $out.=load_fiche_titre($title, null, null);
102
+            if (empty($title)) $title = $langs->trans("AttachANewFile");
103
+            if ($title != 'none') $out .= load_fiche_titre($title, null, null);
104 104
 
105 105
             $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
106 106
             $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="">';
@@ -110,32 +110,32 @@  discard block
 block discarded – undo
110 110
             $out .= '<table width="100%" class="nobordernopadding">';
111 111
             $out .= '<tr>';
112 112
 
113
-            if (! empty($options)) $out .= '<td>'.$options.'</td>';
113
+            if (!empty($options)) $out .= '<td>'.$options.'</td>';
114 114
 
115 115
             $out .= '<td valign="middle">';
116 116
 
117
-            $max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
118
-            $maxphp=@ini_get('upload_max_filesize');	// En inconnu
119
-            if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
120
-            if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
121
-            if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
122
-            if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
117
+            $max = $conf->global->MAIN_UPLOAD_DOC; // En Kb
118
+            $maxphp = @ini_get('upload_max_filesize'); // En inconnu
119
+            if (preg_match('/k$/i', $maxphp)) $maxphp = $maxphp * 1;
120
+            if (preg_match('/m$/i', $maxphp)) $maxphp = $maxphp * 1024;
121
+            if (preg_match('/g$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024;
122
+            if (preg_match('/t$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024 * 1024;
123 123
             // Now $max and $maxphp are in Kb
124
-            if ($maxphp > 0) $max=min($max,$maxphp);
124
+            if ($maxphp > 0) $max = min($max, $maxphp);
125 125
 
126 126
             if ($max > 0)
127 127
             {
128
-                $out .= '<input type="hidden" name="max_file_size" value="'.($max*1024).'">';
128
+                $out .= '<input type="hidden" name="max_file_size" value="'.($max * 1024).'">';
129 129
             }
130 130
 
131 131
             $out .= '<input class="flat minwidth400" type="file"';
132
-            $out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
133
-            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
134
-            $out .= (!empty($accept)?' accept="'.$accept.'"':'accept=""');
132
+            $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic') ? ' name="userfile"' : ' name="userfile[]" multiple');
133
+            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
134
+            $out .= (!empty($accept) ? ' accept="'.$accept.'"' : 'accept=""');
135 135
             $out .= '>';
136 136
             $out .= ' ';
137 137
             $out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
138
-            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
138
+            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
139 139
             $out .= '>';
140 140
 
141 141
             if ($addcancel)
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
                 $out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
145 145
             }
146 146
 
147
-            if (! empty($conf->global->MAIN_UPLOAD_DOC))
147
+            if (!empty($conf->global->MAIN_UPLOAD_DOC))
148 148
             {
149 149
                 if ($perm)
150 150
                 {
151 151
                 	$langs->load('other');
152 152
                     $out .= ' ';
153
-                    $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
153
+                    $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphp), 1);
154 154
                 }
155 155
             }
156 156
             else
@@ -162,9 +162,9 @@  discard block
 block discarded – undo
162 162
             if ($savingdocmask)
163 163
             {
164 164
             	$out .= '<tr>';
165
-   	            if (! empty($options)) $out .= '<td>'.$options.'</td>';
165
+   	            if (!empty($options)) $out .= '<td>'.$options.'</td>';
166 166
 	            $out .= '<td valign="middle" class="nowrap">';
167
-				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
167
+				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/', $langs->transnoentitiesnoconv("OriginFileName"), $savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
168 168
             	$out .= '</td>';
169 169
             	$out .= '</tr>';
170 170
             }
@@ -189,25 +189,25 @@  discard block
 block discarded – undo
189 189
 
190 190
 	            $out .= '<div class="valignmiddle" >';
191 191
 	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
192
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
192
+	            if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink").':</label> ';
193 193
 	            $out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
194 194
 	            $out .= '</div>';
195 195
 	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
196
-	            if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
196
+	            if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label").':</label> ';
197 197
 	            $out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
198
-	            $out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
199
-	            $out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
198
+	            $out .= '<input type="hidden" name="objecttype" value="'.$object->element.'">';
199
+	            $out .= '<input type="hidden" name="objectid" value="'.$object->id.'">';
200 200
 	            $out .= '</div>';
201 201
 	            $out .= '<div class="inline-block" style="padding-right: 10px;">';
202 202
 	            $out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
203
-	            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
203
+	            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
204 204
 	            $out .= '>';
205 205
 	            $out .= '</div>';
206 206
                 $out .= '</div>';
207 207
                 $out .= '<div class="clearboth"></div>';
208 208
 	            $out .= '</form><br>';
209
-	            $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
210
-	            $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
209
+	            $parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'url'=>$url, 'perm'=>$perm);
210
+	            $res = $hookmanager->executeHooks('formattachOptions', $parameters, $object);
211 211
 
212 212
 	            $out .= "\n<!-- End form attach new file -->\n";
213 213
             }
@@ -247,10 +247,10 @@  discard block
 block discarded – undo
247 247
      * 		@return		int										<0 if KO, number of shown files if OK
248 248
      *      @deprecated                                         Use print xxx->showdocuments() instead.
249 249
      */
250
-    function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
250
+    function show_documents($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '')
251 251
     {
252
-        $this->numoffiles=0;
253
-        print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
252
+        $this->numoffiles = 0;
253
+        print $this->showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed, $modelselected, $allowgenifempty, $forcenomultilang, $iconPDF, $notused, $noform, $param, $title, $buttonlabel, $codelang);
254 254
         return $this->numoffiles;
255 255
     }
256 256
 
@@ -278,47 +278,47 @@  discard block
 block discarded – undo
278 278
      *      @param      Object              $object             Object when method is called from an object card.
279 279
      * 		@return		string              					Output string with HTML array of documents (might be empty string)
280 280
      */
281
-    function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null)
281
+    function showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '', $morepicto = '', $object = null)
282 282
     {
283 283
 		// Deprecation warning
284 284
 		if (0 !== $iconPDF) {
285
-			dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
285
+			dol_syslog(__METHOD__.": passing iconPDF parameter is deprecated", LOG_WARNING);
286 286
 		}
287 287
 
288 288
         global $langs, $conf, $user, $hookmanager;
289 289
         global $form, $bc;
290 290
 
291
-        if (! is_object($form)) $form=new Form($this->db);
291
+        if (!is_object($form)) $form = new Form($this->db);
292 292
 
293 293
         include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
294 294
 
295 295
         // For backward compatibility
296
-        if (! empty($iconPDF)) {
296
+        if (!empty($iconPDF)) {
297 297
         	return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
298 298
         }
299 299
 
300
-        $printer=0;
301
-        if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport')))	// The direct print feature is implemented only for such elements
300
+        $printer = 0;
301
+        if (in_array($modulepart, array('facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur', 'expensereport')))	// The direct print feature is implemented only for such elements
302 302
         {
303
-            $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
303
+            $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled)) ?true:false;
304 304
         }
305 305
 
306 306
         $hookmanager->initHooks(array('formfile'));
307
-        $forname='builddoc';
308
-        $out='';
307
+        $forname = 'builddoc';
308
+        $out = '';
309 309
 
310
-        $headershown=0;
311
-        $showempty=0;
312
-        $i=0;
310
+        $headershown = 0;
311
+        $showempty = 0;
312
+        $i = 0;
313 313
 
314
-        $out.= "\n".'<!-- Start show_document -->'."\n";
314
+        $out .= "\n".'<!-- Start show_document -->'."\n";
315 315
         //print 'filedir='.$filedir;
316 316
 
317 317
         if (preg_match('/massfilesarea_/', $modulepart))
318 318
         {
319
-	        $out.='<div id="show_files"><br></div>'."\n";
320
-			$title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
321
-			$title.='<script type="text/javascript" language="javascript">
319
+	        $out .= '<div id="show_files"><br></div>'."\n";
320
+			$title = $langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
321
+			$title .= '<script type="text/javascript" language="javascript">
322 322
 				jQuery(document).ready(function() {
323 323
 					jQuery(\'#togglemassfilesarea\').click(function() {
324 324
 						if (jQuery(\'#togglemassfilesarea\').attr(\'ref\') == "shown")
@@ -339,435 +339,435 @@  discard block
 block discarded – undo
339 339
 				</script>';
340 340
         }
341 341
 
342
-        $titletoshow=$langs->trans("Documents");
343
-        if (! empty($title)) $titletoshow=$title;
342
+        $titletoshow = $langs->trans("Documents");
343
+        if (!empty($title)) $titletoshow = $title;
344 344
 
345 345
         // Show table
346 346
         if ($genallowed)
347 347
         {
348
-            $modellist=array();
348
+            $modellist = array();
349 349
 
350 350
             if ($modulepart == 'company')
351 351
             {
352
-                $showempty=1;
353
-                if (is_array($genallowed)) $modellist=$genallowed;
352
+                $showempty = 1;
353
+                if (is_array($genallowed)) $modellist = $genallowed;
354 354
                 else
355 355
                 {
356 356
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
357
-                    $modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
357
+                    $modellist = ModeleThirdPartyDoc::liste_modeles($this->db);
358 358
                 }
359 359
             }
360 360
             else if ($modulepart == 'propal')
361 361
             {
362
-                if (is_array($genallowed)) $modellist=$genallowed;
362
+                if (is_array($genallowed)) $modellist = $genallowed;
363 363
                 else
364 364
                 {
365 365
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
366
-                    $modellist=ModelePDFPropales::liste_modeles($this->db);
366
+                    $modellist = ModelePDFPropales::liste_modeles($this->db);
367 367
                 }
368 368
             }
369 369
 			else if ($modulepart == 'supplier_proposal')
370 370
             {
371
-                if (is_array($genallowed)) $modellist=$genallowed;
371
+                if (is_array($genallowed)) $modellist = $genallowed;
372 372
                 else
373 373
                 {
374 374
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
375
-                    $modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
375
+                    $modellist = ModelePDFSupplierProposal::liste_modeles($this->db);
376 376
                 }
377 377
             }
378 378
             else if ($modulepart == 'commande')
379 379
             {
380
-                if (is_array($genallowed)) $modellist=$genallowed;
380
+                if (is_array($genallowed)) $modellist = $genallowed;
381 381
                 else
382 382
                 {
383 383
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
384
-                    $modellist=ModelePDFCommandes::liste_modeles($this->db);
384
+                    $modellist = ModelePDFCommandes::liste_modeles($this->db);
385 385
                 }
386 386
             }
387 387
             elseif ($modulepart == 'expedition')
388 388
             {
389
-                if (is_array($genallowed)) $modellist=$genallowed;
389
+                if (is_array($genallowed)) $modellist = $genallowed;
390 390
                 else
391 391
                 {
392 392
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
393
-                    $modellist=ModelePDFExpedition::liste_modeles($this->db);
393
+                    $modellist = ModelePDFExpedition::liste_modeles($this->db);
394 394
                 }
395 395
             }
396 396
             elseif ($modulepart == 'livraison')
397 397
             {
398
-                if (is_array($genallowed)) $modellist=$genallowed;
398
+                if (is_array($genallowed)) $modellist = $genallowed;
399 399
                 else
400 400
                 {
401 401
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
402
-                    $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
402
+                    $modellist = ModelePDFDeliveryOrder::liste_modeles($this->db);
403 403
                 }
404 404
             }
405 405
             else if ($modulepart == 'ficheinter')
406 406
             {
407
-                if (is_array($genallowed)) $modellist=$genallowed;
407
+                if (is_array($genallowed)) $modellist = $genallowed;
408 408
                 else
409 409
                 {
410 410
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
411
-                    $modellist=ModelePDFFicheinter::liste_modeles($this->db);
411
+                    $modellist = ModelePDFFicheinter::liste_modeles($this->db);
412 412
                 }
413 413
             }
414 414
             elseif ($modulepart == 'facture')
415 415
             {
416
-                if (is_array($genallowed)) $modellist=$genallowed;
416
+                if (is_array($genallowed)) $modellist = $genallowed;
417 417
                 else
418 418
                 {
419 419
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
420
-                    $modellist=ModelePDFFactures::liste_modeles($this->db);
420
+                    $modellist = ModelePDFFactures::liste_modeles($this->db);
421 421
                 }
422 422
             }
423 423
             elseif ($modulepart == 'contract')
424 424
             {
425
-            	if (is_array($genallowed)) $modellist=$genallowed;
425
+            	if (is_array($genallowed)) $modellist = $genallowed;
426 426
             	else
427 427
             	{
428 428
             		include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
429
-            		$modellist=ModelePDFContract::liste_modeles($this->db);
429
+            		$modellist = ModelePDFContract::liste_modeles($this->db);
430 430
             	}
431 431
             }
432 432
             elseif ($modulepart == 'project')
433 433
             {
434
-                if (is_array($genallowed)) $modellist=$genallowed;
434
+                if (is_array($genallowed)) $modellist = $genallowed;
435 435
                 else
436 436
                 {
437 437
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
438
-                    $modellist=ModelePDFProjects::liste_modeles($this->db);
438
+                    $modellist = ModelePDFProjects::liste_modeles($this->db);
439 439
                 }
440 440
             }
441 441
             elseif ($modulepart == 'project_task')
442 442
             {
443
-            	if (is_array($genallowed)) $modellist=$genallowed;
443
+            	if (is_array($genallowed)) $modellist = $genallowed;
444 444
             	else
445 445
             	{
446 446
             		include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
447
-            		$modellist=ModelePDFTask::liste_modeles($this->db);
447
+            		$modellist = ModelePDFTask::liste_modeles($this->db);
448 448
             	}
449 449
             }
450 450
             elseif ($modulepart == 'product')
451 451
             {
452
-                if (is_array($genallowed)) $modellist=$genallowed;
452
+                if (is_array($genallowed)) $modellist = $genallowed;
453 453
                 else
454 454
                 {
455 455
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
456
-                    $modellist=ModelePDFProduct::liste_modeles($this->db);
456
+                    $modellist = ModelePDFProduct::liste_modeles($this->db);
457 457
                 }
458 458
             }
459 459
             elseif ($modulepart == 'export')
460 460
             {
461
-                if (is_array($genallowed)) $modellist=$genallowed;
461
+                if (is_array($genallowed)) $modellist = $genallowed;
462 462
                 else
463 463
                 {
464 464
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
465
-                    $modellist=ModeleExports::liste_modeles($this->db);
465
+                    $modellist = ModeleExports::liste_modeles($this->db);
466 466
                 }
467 467
             }
468 468
             else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
469 469
             {
470
-                if (is_array($genallowed)) $modellist=$genallowed;
470
+                if (is_array($genallowed)) $modellist = $genallowed;
471 471
                 else
472 472
                 {
473 473
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
474
-                    $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
474
+                    $modellist = ModelePDFSuppliersOrders::liste_modeles($this->db);
475 475
                 }
476 476
             }
477 477
             else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
478 478
             {
479
-                if (is_array($genallowed)) $modellist=$genallowed;
479
+                if (is_array($genallowed)) $modellist = $genallowed;
480 480
                 else
481 481
                 {
482 482
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
483
-                    $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
483
+                    $modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db);
484 484
                 }
485 485
             }
486 486
 			else if ($modulepart == 'supplier_payment')
487 487
 			{
488
-                if (is_array($genallowed)) $modellist=$genallowed;
488
+                if (is_array($genallowed)) $modellist = $genallowed;
489 489
                 else
490 490
                 {
491 491
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
492
-                    $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
492
+                    $modellist = ModelePDFSuppliersPayments::liste_modeles($this->db);
493 493
                 }
494 494
 			}
495 495
             else if ($modulepart == 'remisecheque')
496 496
             {
497
-                if (is_array($genallowed)) $modellist=$genallowed;
497
+                if (is_array($genallowed)) $modellist = $genallowed;
498 498
                 else
499 499
                 {
500 500
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
501
-                    $modellist=ModeleChequeReceipts::liste_modeles($this->db);
501
+                    $modellist = ModeleChequeReceipts::liste_modeles($this->db);
502 502
                 }
503 503
             }
504 504
             elseif ($modulepart == 'donation')
505 505
             {
506
-                if (is_array($genallowed)) $modellist=$genallowed;
506
+                if (is_array($genallowed)) $modellist = $genallowed;
507 507
                 else
508 508
                 {
509 509
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
510
-                    $modellist=ModeleDon::liste_modeles($this->db);
510
+                    $modellist = ModeleDon::liste_modeles($this->db);
511 511
                 }
512 512
             }
513 513
             elseif ($modulepart == 'member')
514 514
             {
515
-                if (is_array($genallowed)) $modellist=$genallowed;
515
+                if (is_array($genallowed)) $modellist = $genallowed;
516 516
                 else
517 517
                 {
518 518
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
519
-                    $modellist=ModelePDFCards::liste_modeles($this->db);
519
+                    $modellist = ModelePDFCards::liste_modeles($this->db);
520 520
                 }
521 521
             }
522 522
             elseif ($modulepart == 'agenda')
523 523
             {
524
-                if (is_array($genallowed)) $modellist=$genallowed;
524
+                if (is_array($genallowed)) $modellist = $genallowed;
525 525
                 else
526 526
                 {
527 527
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
528
-                    $modellist=ModeleAction::liste_modeles($this->db);
528
+                    $modellist = ModeleAction::liste_modeles($this->db);
529 529
                 }
530 530
             }
531 531
             else if ($modulepart == 'expensereport')
532 532
             {
533
-                if (is_array($genallowed)) $modellist=$genallowed;
533
+                if (is_array($genallowed)) $modellist = $genallowed;
534 534
                 else
535 535
                 {
536 536
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
537
-                    $modellist=ModeleExpenseReport::liste_modeles($this->db);
537
+                    $modellist = ModeleExpenseReport::liste_modeles($this->db);
538 538
                 }
539 539
             }
540 540
             else if ($modulepart == 'unpaid')
541 541
             {
542
-                $modellist='';
542
+                $modellist = '';
543 543
             }
544 544
             elseif ($modulepart == 'user')
545 545
             {
546
-                if (is_array($genallowed)) $modellist=$genallowed;
546
+                if (is_array($genallowed)) $modellist = $genallowed;
547 547
                 else
548 548
                 {
549 549
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
550
-                    $modellist=ModelePDFUser::liste_modeles($this->db);
550
+                    $modellist = ModelePDFUser::liste_modeles($this->db);
551 551
                 }
552 552
             }
553 553
             elseif ($modulepart == 'usergroup')
554 554
             {
555
-                if (is_array($genallowed)) $modellist=$genallowed;
555
+                if (is_array($genallowed)) $modellist = $genallowed;
556 556
                 else
557 557
                 {
558 558
                     include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
559
-                    $modellist=ModelePDFUserGroup::liste_modeles($this->db);
559
+                    $modellist = ModelePDFUserGroup::liste_modeles($this->db);
560 560
                 }
561 561
             }
562 562
             else //if ($modulepart != 'agenda')
563 563
             {
564 564
             	// For normalized standard modules
565
-            	$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
565
+            	$file = dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php', 0);
566 566
                 if (file_exists($file))
567 567
                 {
568
-                	$res=include_once $file;
568
+                	$res = include_once $file;
569 569
                 }
570 570
                 // For normalized external modules
571 571
                 else
572 572
 				{
573
-                	$file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
574
-                	$res=include_once $file;
573
+                	$file = dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php', 0);
574
+                	$res = include_once $file;
575 575
                 }
576
-                $class='Modele'.ucfirst($modulepart);
576
+                $class = 'Modele'.ucfirst($modulepart);
577 577
                 if (class_exists($class))
578 578
                 {
579
-                    $modellist=call_user_func($class.'::liste_modeles',$this->db);
579
+                    $modellist = call_user_func($class.'::liste_modeles', $this->db);
580 580
                 }
581 581
                 else
582 582
               {
583
-                    dol_print_error($this->db,'Bad value for modulepart');
583
+                    dol_print_error($this->db, 'Bad value for modulepart');
584 584
                     return -1;
585 585
                 }
586 586
             }
587 587
 
588 588
             // Set headershown to avoit to have table opened a second time later
589
-            $headershown=1;
589
+            $headershown = 1;
590 590
 
591
-            $buttonlabeltoshow=$buttonlabel;
592
-            if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
591
+            $buttonlabeltoshow = $buttonlabel;
592
+            if (empty($buttonlabel)) $buttonlabel = $langs->trans('Generate');
593 593
 
594
-            if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
595
-            if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
596
-            $out.= '<input type="hidden" name="action" value="builddoc">';
597
-            $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
594
+            if ($conf->browser->layout == 'phone') $urlsource .= '#'.$forname.'_form'; // So we switch to form after a generation
595
+            if (empty($noform)) $out .= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc').'" id="'.$forname.'_form" method="post">';
596
+            $out .= '<input type="hidden" name="action" value="builddoc">';
597
+            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
598 598
 
599
-            $out.= load_fiche_titre($titletoshow, '', '');
600
-            $out.= '<div class="div-table-responsive-no-min">';
601
-            $out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
599
+            $out .= load_fiche_titre($titletoshow, '', '');
600
+            $out .= '<div class="div-table-responsive-no-min">';
601
+            $out .= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
602 602
 
603
-            $out.= '<tr class="liste_titre">';
603
+            $out .= '<tr class="liste_titre">';
604 604
 
605
-            $addcolumforpicto=($delallowed || $printer || $morepicto);
606
-            $out.= '<th align="center" colspan="'.(3+($addcolumforpicto?'2':'1')).'" class="formdoc liste_titre maxwidthonsmartphone">';
605
+            $addcolumforpicto = ($delallowed || $printer || $morepicto);
606
+            $out .= '<th align="center" colspan="'.(3 + ($addcolumforpicto ? '2' : '1')).'" class="formdoc liste_titre maxwidthonsmartphone">';
607 607
 
608 608
             // Model
609
-            if (! empty($modellist))
609
+            if (!empty($modellist))
610 610
             {
611
-                $out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
611
+                $out .= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
612 612
                 if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
613 613
                 {
614
-                    $arraykeys=array_keys($modellist);
615
-                    $modelselected=$arraykeys[0];
614
+                    $arraykeys = array_keys($modellist);
615
+                    $modelselected = $arraykeys[0];
616 616
                 }
617
-                $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
618
-                $out.= ajax_combobox('model');
617
+                $out .= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
618
+                $out .= ajax_combobox('model');
619 619
             }
620 620
             else
621 621
             {
622
-                $out.= '<div class="float">'.$langs->trans("Files").'</div>';
622
+                $out .= '<div class="float">'.$langs->trans("Files").'</div>';
623 623
             }
624 624
 
625 625
             // Language code (if multilang)
626
-            if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
626
+            if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && !$forcenomultilang && (!empty($modellist) || $showempty))
627 627
             {
628 628
                 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
629
-                $formadmin=new FormAdmin($this->db);
630
-                $defaultlang=$codelang?$codelang:$langs->getDefaultLang();
631
-                $morecss='maxwidth150';
632
-                if (! empty($conf->browser->phone)) $morecss='maxwidth100';
633
-                $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
629
+                $formadmin = new FormAdmin($this->db);
630
+                $defaultlang = $codelang ? $codelang : $langs->getDefaultLang();
631
+                $morecss = 'maxwidth150';
632
+                if (!empty($conf->browser->phone)) $morecss = 'maxwidth100';
633
+                $out .= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
634 634
             }
635 635
             else
636 636
             {
637
-                $out.= '&nbsp;';
637
+                $out .= '&nbsp;';
638 638
             }
639 639
 
640 640
             // Button
641 641
             $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
642
-            $genbutton.= ' type="submit" value="'.$buttonlabel.'"';
643
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
644
-            $genbutton.= '>';
645
-            if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
642
+            $genbutton .= ' type="submit" value="'.$buttonlabel.'"';
643
+            if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) $genbutton .= ' disabled';
644
+            $genbutton .= '>';
645
+            if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
646 646
             {
647 647
                	$langs->load("errors");
648
-               	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
648
+               	$genbutton .= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
649 649
             }
650
-            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
651
-            if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
652
-            $out.= $genbutton;
653
-            $out.= '</th>';
650
+            if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton = '';
651
+            if (empty($modellist) && !$showempty && $modulepart != 'unpaid') $genbutton = '';
652
+            $out .= $genbutton;
653
+            $out .= '</th>';
654 654
 
655 655
             if (!empty($hookmanager->hooks['formfile']))
656 656
             {
657
-                foreach($hookmanager->hooks['formfile'] as $module)
657
+                foreach ($hookmanager->hooks['formfile'] as $module)
658 658
                 {
659 659
                     if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
660 660
                 }
661 661
             }
662
-            $out.= '</tr>';
662
+            $out .= '</tr>';
663 663
 
664 664
             // Execute hooks
665
-            $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
665
+            $parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart);
666 666
             if (is_object($hookmanager))
667 667
             {
668
-            	$reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
669
-            	$out.= $hookmanager->resPrint;
668
+            	$reshook = $hookmanager->executeHooks('formBuilddocOptions', $parameters, $GLOBALS['object']);
669
+            	$out .= $hookmanager->resPrint;
670 670
             }
671 671
 
672 672
         }
673 673
 
674 674
         // Get list of files
675
-        if (! empty($filedir))
675
+        if (!empty($filedir))
676 676
         {
677
-            $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
677
+            $file_list = dol_dir_list($filedir, 'files', 0, '', '(\.meta|_preview.*.*\.png)$', 'date', SORT_DESC);
678 678
 
679 679
             $link_list = array();
680 680
             if (is_object($object))
681 681
             {
682
-                require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
682
+                require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
683 683
                 $link = new Link($this->db);
684 684
                 $sortfield = $sortorder = null;
685 685
                 $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
686 686
             }
687 687
 
688
-            $out.= '<!-- html.formfile::showdocuments -->'."\n";
688
+            $out .= '<!-- html.formfile::showdocuments -->'."\n";
689 689
 
690 690
             // Show title of array if not already shown
691
-            if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown)
691
+            if ((!empty($file_list) || !empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && !$headershown)
692 692
             {
693
-                $headershown=1;
694
-                $out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
695
-                $out.= '<div class="div-table-responsive-no-min">';
696
-                $out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
693
+                $headershown = 1;
694
+                $out .= '<div class="titre">'.$titletoshow.'</div>'."\n";
695
+                $out .= '<div class="div-table-responsive-no-min">';
696
+                $out .= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
697 697
             }
698 698
 
699 699
             // Loop on each file found
700 700
 			if (is_array($file_list))
701 701
 			{
702
-				foreach($file_list as $file)
702
+				foreach ($file_list as $file)
703 703
 				{
704 704
 					// Define relative path for download link (depends on module)
705
-					$relativepath=$file["name"];										// Cas general
706
-                    if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
707
-					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
705
+					$relativepath = $file["name"]; // Cas general
706
+                    if ($modulesubdir) $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
707
+					if ($modulepart == 'export') $relativepath = $file["name"]; // Other case
708 708
 
709
-					$out.= '<tr class="oddeven">';
709
+					$out .= '<tr class="oddeven">';
710 710
 
711 711
 					$documenturl = DOL_URL_ROOT.'/document.php';
712
-					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
712
+					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP; // To use another wrapper
713 713
 
714 714
 					// Show file name with link to download
715
-					$out.= '<td class="tdoverflowmax300">';
716
-                    $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param);
717
-                    $out.= ($tmp?$tmp.' ':'');
718
-					$out.= '<a class="documentdownload" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
719
-					$mime=dol_mimetype($relativepath,'',0);
720
-					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
721
-					$out.= ' target="_blank">';
722
-					$out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]).' '.$file["name"];
723
-					$out.= '</a>'."\n";
724
-					$out.= '</td>';
715
+					$out .= '<td class="tdoverflowmax300">';
716
+                    $tmp = $this->showPreview($file, $modulepart, $relativepath, 0, $param);
717
+                    $out .= ($tmp ? $tmp.' ' : '');
718
+					$out .= '<a class="documentdownload" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param ? '&'.$param : '').'"';
719
+					$mime = dol_mimetype($relativepath, '', 0);
720
+					if (preg_match('/text/', $mime)) $out .= ' target="_blank"';
721
+					$out .= ' target="_blank">';
722
+					$out .= img_mime($file["name"], $langs->trans("File").': '.$file["name"]).' '.$file["name"];
723
+					$out .= '</a>'."\n";
724
+					$out .= '</td>';
725 725
 
726 726
 					// Show file size
727
-					$size=(! empty($file['size'])?$file['size']:dol_filesize($filedir."/".$file["name"]));
728
-					$out.= '<td align="right" class="nowrap">'.dol_print_size($size).'</td>';
727
+					$size = (!empty($file['size']) ? $file['size'] : dol_filesize($filedir."/".$file["name"]));
728
+					$out .= '<td align="right" class="nowrap">'.dol_print_size($size).'</td>';
729 729
 
730 730
 					// Show file date
731
-					$date=(! empty($file['date'])?$file['date']:dol_filemtime($filedir."/".$file["name"]));
732
-					$out.= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
731
+					$date = (!empty($file['date']) ? $file['date'] : dol_filemtime($filedir."/".$file["name"]));
732
+					$out .= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
733 733
 
734 734
 					if ($delallowed || $printer || $morepicto)
735 735
 					{
736
-						$out.= '<td align="right">';
736
+						$out .= '<td align="right">';
737 737
 						if ($delallowed)
738 738
 						{
739
-							$out.= '<a href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=remove_file&amp;file='.urlencode($relativepath);
740
-							$out.= ($param?'&amp;'.$param:'');
739
+							$out .= '<a href="'.$urlsource.(strpos($urlsource, '?') ? '&amp;' : '?').'action=remove_file&amp;file='.urlencode($relativepath);
740
+							$out .= ($param ? '&amp;'.$param : '');
741 741
 							//$out.= '&modulepart='.$modulepart; // TODO obsolete ?
742 742
 							//$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
743
-							$out.= '">'.img_picto($langs->trans("Delete"), 'delete.png').'</a>';
743
+							$out .= '">'.img_picto($langs->trans("Delete"), 'delete.png').'</a>';
744 744
 							//$out.='</td>';
745 745
 						}
746 746
 						if ($printer)
747 747
 						{
748 748
 							//$out.= '<td align="right">';
749
-                            $out.= '&nbsp;<a href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
750
-                            $out.= ($param?'&amp;'.$param:'');
751
-                            $out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
749
+                            $out .= '&nbsp;<a href="'.$urlsource.(strpos($urlsource, '?') ? '&amp;' : '?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
750
+                            $out .= ($param ? '&amp;'.$param : '');
751
+                            $out .= '">'.img_picto($langs->trans("PrintFile", $relativepath), 'printer.png').'</a>';
752 752
 						}
753 753
 						if ($morepicto)
754 754
 						{
755
-							$morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto);
756
-                        	$out.=$morepicto;
755
+							$morepicto = preg_replace('/__FILENAMEURLENCODED__/', urlencode($relativepath), $morepicto);
756
+                        	$out .= $morepicto;
757 757
 						}
758
-                        $out.='</td>';
758
+                        $out .= '</td>';
759 759
                     }
760 760
 
761 761
                     if (is_object($hookmanager))
762 762
                     {
763
-            			$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
764
-                    	$res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
763
+            			$parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart, 'relativepath'=>$relativepath);
764
+                    	$res = $hookmanager->executeHooks('formBuilddocLineOptions', $parameters, $file);
765 765
                         if (empty($res))
766 766
                         {
767
-                            $out .= $hookmanager->resPrint;		// Complete line
768
-                            $out.= '</tr>';
767
+                            $out .= $hookmanager->resPrint; // Complete line
768
+                            $out .= '</tr>';
769 769
                         }
770
-                        else $out = $hookmanager->resPrint;		// Replace line
770
+                        else $out = $hookmanager->resPrint; // Replace line
771 771
               		}
772 772
 				}
773 773
 
@@ -776,28 +776,28 @@  discard block
 block discarded – undo
776 776
             // Loop on each file found
777 777
             if (is_array($link_list))
778 778
             {
779
-                $colspan=2;
779
+                $colspan = 2;
780 780
 
781
-                foreach($link_list as $file)
781
+                foreach ($link_list as $file)
782 782
                 {
783
-                    $out.='<tr class="oddeven">';
784
-                    $out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
785
-                    $out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
786
-                    $out.=$file->label;
787
-                    $out.='</a>';
788
-                    $out.='</td>';
789
-                    $out.='<td align="right">';
790
-                    $out.=dol_print_date($file->datea,'dayhour');
791
-                    $out.='</td>';
792
-                    if ($delallowed || $printer || $morepicto) $out.='<td></td>';
793
-                    $out.='</tr>'."\n";
783
+                    $out .= '<tr class="oddeven">';
784
+                    $out .= '<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
785
+                    $out .= '<a data-ajax="false" href="'.$link->url.'" target="_blank">';
786
+                    $out .= $file->label;
787
+                    $out .= '</a>';
788
+                    $out .= '</td>';
789
+                    $out .= '<td align="right">';
790
+                    $out .= dol_print_date($file->datea, 'dayhour');
791
+                    $out .= '</td>';
792
+                    if ($delallowed || $printer || $morepicto) $out .= '<td></td>';
793
+                    $out .= '</tr>'."\n";
794 794
                 }
795 795
                 $this->numoffiles++;
796 796
             }
797 797
 
798 798
 		 	if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
799 799
             {
800
-	        	$out.='<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
800
+	        	$out .= '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
801 801
     	    }
802 802
 
803 803
         }
@@ -805,14 +805,14 @@  discard block
 block discarded – undo
805 805
         if ($headershown)
806 806
         {
807 807
             // Affiche pied du tableau
808
-            $out.= "</table>\n";
809
-            $out.= "</div>\n";
808
+            $out .= "</table>\n";
809
+            $out .= "</div>\n";
810 810
             if ($genallowed)
811 811
             {
812
-                if (empty($noform)) $out.= '</form>'."\n";
812
+                if (empty($noform)) $out .= '</form>'."\n";
813 813
             }
814 814
         }
815
-        $out.= '<!-- End show_document -->'."\n";
815
+        $out .= '<!-- End show_document -->'."\n";
816 816
         //return ($i?$i:$headershown);
817 817
         return $out;
818 818
     }
@@ -828,69 +828,69 @@  discard block
 block discarded – undo
828 828
      *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
829 829
      *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
830 830
      */
831
-    function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
831
+    function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter = '')
832 832
     {
833 833
         global $conf, $langs;
834 834
 
835 835
     	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
836 836
 
837
-    	$out='';
838
-    	$this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
837
+    	$out = '';
838
+    	$this->infofiles = array('nboffiles'=>0, 'extensions'=>array(), 'files'=>array());
839 839
 
840
-    	$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
840
+    	$filterforfilesearch = preg_quote(basename($modulesubdir), '/').'[^\-]+';
841 841
 
842
-    	$file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// Get list of files starting with name of ref (but not followed by "-" to discard uploaded files)
842
+    	$file_list = dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files)
843 843
 
844 844
     	// For ajax treatment
845
-		$out.= '<!-- html.formfile::getDocumentsLink -->'."\n";
846
-    	if (! empty($file_list))
845
+		$out .= '<!-- html.formfile::getDocumentsLink -->'."\n";
846
+    	if (!empty($file_list))
847 847
     	{
848
-    	    $out='<dl class="dropdown inline-block">
848
+    	    $out = '<dl class="dropdown inline-block">
849 849
     			<dt><a data-ajax="false" href="#" onClick="return false;">'.img_picto('', 'listlight').'</a></dt>
850 850
     			<dd><div class="multichoicedoc" style="position:absolute;left:100px;" ><ul class="ulselectedfields" style="display: none;">';
851
-    	    $tmpout='';
851
+    	    $tmpout = '';
852 852
 
853 853
     		// Loop on each file found
854
-    		foreach($file_list as $file)
854
+    		foreach ($file_list as $file)
855 855
     		{
856 856
     		    $i++;
857
-    			if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
857
+    			if ($filter && !preg_match('/'.$filter.'/i', $file["name"])) continue; // Discard this. It does not match provided filter.
858 858
 
859 859
     			// Define relative path for download link (depends on module)
860
-    			$relativepath=$file["name"];								// Cas general
861
-    			if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
860
+    			$relativepath = $file["name"]; // Cas general
861
+    			if ($modulesubdir) $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
862 862
     			// Autre cas
863
-    			if ($modulepart == 'donation')            {
864
-    				$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
863
+    			if ($modulepart == 'donation') {
864
+    				$relativepath = get_exdir($modulesubdir, 2, 0, 0, null, 'donation').$file["name"];
865 865
     			}
866
-    			if ($modulepart == 'export')              {
866
+    			if ($modulepart == 'export') {
867 867
     				$relativepath = $file["name"];
868 868
     			}
869 869
 
870 870
     			$this->infofiles['nboffiles']++;
871
-    			$this->infofiles['files'][]=$file['fullname'];
872
-    			$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
873
-    			if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
871
+    			$this->infofiles['files'][] = $file['fullname'];
872
+    			$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
873
+    			if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext] = 1;
874 874
     			else $this->infofiles['extensions'][$ext]++;
875 875
 
876 876
     			// Preview
877
-    			if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
877
+    			if (!empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
878 878
     			{
879 879
                     $tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
880
-                    if ($tmparray && $tmparray['url']) $tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>'.img_picto('','detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
880
+                    if ($tmparray && $tmparray['url']) $tmpout .= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css'] ? ' class="'.$tmparray['css'].'"' : '').($tmparray['mime'] ? ' mime="'.$tmparray['mime'].'"' : '').($tmparray['target'] ? ' target="'.$tmparray['target'].'"' : '').'>'.img_picto('', 'detail').' '.$langs->trans("Preview").' '.$ext.'</a></li>';
881 881
     			}
882 882
 
883 883
     			// Download
884
-    		    $tmpout.= '<li><a class="pictopreview" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
885
-    			$mime=dol_mimetype($relativepath,'',0);
886
-    			if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
887
-    			$tmpout.= '>';
888
-    			$tmpout.=img_mime($relativepath, $file["name"]).' ';
889
-    			$tmpout.= $langs->trans("Download").' '.$ext;
890
-    			$tmpout.= '</a></li>'."\n";
884
+    		    $tmpout .= '<li><a class="pictopreview" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
885
+    			$mime = dol_mimetype($relativepath, '', 0);
886
+    			if (preg_match('/text/', $mime)) $tmpout .= ' target="_blank"';
887
+    			$tmpout .= '>';
888
+    			$tmpout .= img_mime($relativepath, $file["name"]).' ';
889
+    			$tmpout .= $langs->trans("Download").' '.$ext;
890
+    			$tmpout .= '</a></li>'."\n";
891 891
     		}
892
-    		$out.=$tmpout;
893
-    		$out.='</ul></div></dd>
892
+    		$out .= $tmpout;
893
+    		$out .= '</ul></div></dd>
894 894
     			</dl>';
895 895
     	}
896 896
     	else
@@ -928,40 +928,40 @@  discard block
 block discarded – undo
928 928
      *  @param	 int	$addfilterfields	Add line with filters
929 929
      * 	@return	 int						<0 if KO, nb of files shown if OK
930 930
      */
931
-	function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0)
931
+	function list_of_documents($filearray, $object, $modulepart, $param = '', $forcedownload = 0, $relativepath = '', $permonobject = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $title = '', $url = '', $showrelpart = 0, $permtoeditline = -1, $upload_dir = '', $sortfield = '', $sortorder = 'ASC', $disablemove = 1, $addfilterfields = 0)
932 932
 	{
933 933
 		global $user, $conf, $langs, $hookmanager;
934
-		global $bc,$bcdd;
934
+		global $bc, $bcdd;
935 935
 		global $sortfield, $sortorder, $maxheightmini;
936 936
 
937 937
 		// Define relative path used to store the file
938 938
 		if (empty($relativepath))
939 939
 		{
940
-		    $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
941
-		    if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
942
-		    if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
940
+		    $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/';
941
+		    if ($object->element == 'invoice_supplier') $relativepath = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath
942
+		    if ($object->element == 'project_task') $relativepath = 'Call_not_supported_._Call_function_using_a_defined_relative_path_.';
943 943
 		}
944 944
 		// For backward compatiblity, we detect file is stored into an old path
945
-		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos')
945
+		if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos')
946 946
 		{
947
-		    $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/';
947
+		    $relativepath = preg_replace('/^.*\/produit\//', '', $file['path']).'/';
948 948
 		}
949 949
 		// Defined relative dir to DOL_DATA_ROOT
950 950
 		$relativedir = '';
951 951
 		if ($upload_dir)
952 952
 		{
953
-    		$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
954
-    		$relativedir = preg_replace('/^[\\/]/','',$relativedir);
953
+    		$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
954
+    		$relativedir = preg_replace('/^[\\/]/', '', $relativedir);
955 955
 		}
956 956
 
957 957
 		$hookmanager->initHooks(array('formfile'));
958
-		$parameters=array(
958
+		$parameters = array(
959 959
 				'filearray' => $filearray,
960 960
 				'modulepart'=> $modulepart,
961 961
 				'param' => $param,
962 962
 				'forcedownload' => $forcedownload,
963
-				'relativepath' => $relativepath,    // relative filename to module dir
964
-				'relativedir' => $relativedir,      // relative dirname to DOL_DATA_ROOT
963
+				'relativepath' => $relativepath, // relative filename to module dir
964
+				'relativedir' => $relativedir, // relative dirname to DOL_DATA_ROOT
965 965
 				'permtodelete' => $permonobject,
966 966
 				'useinecm' => $useinecm,
967 967
 				'textifempty' => $textifempty,
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
 				'title' => $title,
970 970
 				'url' => $url
971 971
 		);
972
-		$reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
972
+		$reshook = $hookmanager->executeHooks('showFilesList', $parameters, $object);
973 973
 
974 974
 		if (isset($reshook) && $reshook != '') // null or '' for bypass
975 975
 		{
@@ -977,29 +977,29 @@  discard block
 block discarded – undo
977 977
 		}
978 978
 		else
979 979
 		{
980
-			$param = (isset($object->id)?'&id='.$object->id:'').$param;
980
+			$param = (isset($object->id) ? '&id='.$object->id : '').$param;
981 981
 
982 982
 			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
983 983
 			{
984
-			    $permtoeditline=0;
985
-			    if (in_array($modulepart, array('product','produit','service')))
984
+			    $permtoeditline = 0;
985
+			    if (in_array($modulepart, array('product', 'produit', 'service')))
986 986
 			    {
987
-			        if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
988
-			        if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
987
+			        if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline = 1;
988
+			        if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline = 1;
989 989
 			    }
990 990
 			}
991 991
 			if (empty($conf->global->MAIN_UPLOAD_DOC))
992 992
 			{
993
-			    $permtoeditline=0;
994
-			    $permonobject=0;
993
+			    $permtoeditline = 0;
994
+			    $permonobject = 0;
995 995
 			}
996 996
 
997 997
 			// Show list of existing files
998
-			if (empty($useinecm)) print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
999
-			if (empty($url)) $url=$_SERVER["PHP_SELF"];
998
+			if (empty($useinecm)) print load_fiche_titre($title ? $title : $langs->trans("AttachedFiles"));
999
+			if (empty($url)) $url = $_SERVER["PHP_SELF"];
1000 1000
 
1001 1001
 			print '<!-- html.formfile::list_of_documents -->'."\n";
1002
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1002
+			if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline)
1003 1003
 			{
1004 1004
 			    print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1005 1005
 			    print '<input type="hidden" name="action" value="renamefile">';
@@ -1008,27 +1008,27 @@  discard block
 block discarded – undo
1008 1008
 			}
1009 1009
 
1010 1010
 			print '<div class="div-table-responsive-no-min">';
1011
-			print '<table width="100%" id="tablelines" class="'.($useinecm?'liste noborder':'liste').'">'."\n";
1011
+			print '<table width="100%" id="tablelines" class="'.($useinecm ? 'liste noborder' : 'liste').'">'."\n";
1012 1012
 
1013
-			if (! empty($addfilterfields))
1013
+			if (!empty($addfilterfields))
1014 1014
 			{
1015 1015
 				print '<tr class="liste_titre nodrag nodrop">';
1016
-				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1016
+				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref', 'alpha')).'"></td>';
1017 1017
 				print '<td></td>';
1018 1018
 				print '<td></td>';
1019 1019
 				if (empty($useinecm)) print '<td></td>';
1020 1020
 				print '<td></td>';
1021
-				if (! $disablemove) print '<td></td>';
1021
+				if (!$disablemove) print '<td></td>';
1022 1022
 				print "</tr>\n";
1023 1023
 			}
1024 1024
 
1025 1025
 			print '<tr class="liste_titre nodrag nodrop">';
1026
-			print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1027
-			print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1028
-			print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1029
-			if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');
1026
+			print_liste_field_titre('Documents2', $url, "name", "", $param, 'align="left"', $sortfield, $sortorder);
1027
+			print_liste_field_titre('Size', $url, "size", "", $param, 'align="right"', $sortfield, $sortorder);
1028
+			print_liste_field_titre('Date', $url, "date", "", $param, 'align="center"', $sortfield, $sortorder);
1029
+			if (empty($useinecm)) print_liste_field_titre('', $url, "", "", $param, 'align="center"');
1030 1030
 			print_liste_field_titre('');
1031
-			if (! $disablemove) print_liste_field_titre('');
1031
+			if (!$disablemove) print_liste_field_titre('');
1032 1032
 			print "</tr>\n";
1033 1033
 
1034 1034
 			// Get list of files stored into database for same relative directory
@@ -1040,51 +1040,51 @@  discard block
 block discarded – undo
1040 1040
 				var_dump($sortorder);*/
1041 1041
     			if ($sortfield && $sortorder)
1042 1042
     			{
1043
-        			$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1043
+        			$filearray = dol_sort_array($filearray, $sortfield, $sortorder);
1044 1044
     			}
1045 1045
     			//var_dump($filearray);
1046 1046
 			}
1047 1047
 
1048
-			$nboffiles=count($filearray);
1048
+			$nboffiles = count($filearray);
1049 1049
 			if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1050 1050
 
1051
-			$var=true; $i=0; $nboflines = 0; $lastrowid=0;
1052
-			foreach($filearray as $key => $file)      // filearray must be only files here
1051
+			$var = true; $i = 0; $nboflines = 0; $lastrowid = 0;
1052
+			foreach ($filearray as $key => $file)      // filearray must be only files here
1053 1053
 			{
1054 1054
 				if ($file['name'] != '.'
1055 1055
 						&& $file['name'] != '..'
1056
-						&& ! preg_match('/\.meta$/i',$file['name']))
1056
+						&& !preg_match('/\.meta$/i', $file['name']))
1057 1057
 				{
1058 1058
 					if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1059 1059
 
1060
-					$editline=0;
1060
+					$editline = 0;
1061 1061
 					$nboflines++;
1062 1062
 			        print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1063 1063
 			        // Do we have entry into database ?
1064 1064
 			        print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1065
-					print '<tr id="row-'.($filearray[$key]['rowid']>0?$filearray[$key]['rowid']:'-AFTER'.$lastrowid.'POS'.($i+1)).'" '.$bcdd[$var].'>';
1065
+					print '<tr id="row-'.($filearray[$key]['rowid'] > 0 ? $filearray[$key]['rowid'] : '-AFTER'.$lastrowid.'POS'.($i + 1)).'" '.$bcdd[$var].'>';
1066 1066
 					print '<td class="tdoverflowmax300">';
1067 1067
 
1068
-					$filepath=$relativepath.$file['name'];
1068
+					$filepath = $relativepath.$file['name'];
1069 1069
 
1070
-					if (! $editline) print $this->showPreview($file,$modulepart,$filepath);
1070
+					if (!$editline) print $this->showPreview($file, $modulepart, $filepath);
1071 1071
 
1072 1072
 					//print "XX".$file['name'];	//$file['name'] must be utf8
1073 1073
 					print '<a class="paddingleft" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1074 1074
 					if ($forcedownload) print '&attachment=1';
1075
-					if (! empty($object->entity)) print '&entity='.$object->entity;
1075
+					if (!empty($object->entity)) print '&entity='.$object->entity;
1076 1076
 					print '&file='.urlencode($filepath);
1077 1077
 					print '">';
1078 1078
 
1079
-					print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1079
+					print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')').' ';
1080 1080
 					if ($showrelpart == 1) print $relativepath;
1081 1081
 					//print dol_trunc($file['name'],$maxlength,'middle');
1082
-					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile')))
1082
+					if (GETPOST('action', 'aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile')))
1083 1083
 					{
1084 1084
 					    print '</a>';
1085 1085
 					    print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1086 1086
 					    print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1087
-					    $editline=1;
1087
+					    $editline = 1;
1088 1088
 					}
1089 1089
 					else
1090 1090
 					{
@@ -1094,9 +1094,9 @@  discard block
 block discarded – undo
1094 1094
 
1095 1095
 					print "</td>\n";
1096 1096
 
1097
-					print '<td align="right" width="80px">'.dol_print_size($file['size'],1,1).'</td>';
1097
+					print '<td align="right" width="80px">'.dol_print_size($file['size'], 1, 1).'</td>';
1098 1098
 
1099
-					print '<td align="center" width="130px">'.dol_print_date($file['date'],"dayhour","tzuser").'</td>';
1099
+					print '<td align="center" width="130px">'.dol_print_date($file['date'], "dayhour", "tzuser").'</td>';
1100 1100
 
1101 1101
 					// Preview
1102 1102
 					if (empty($useinecm))
@@ -1105,20 +1105,20 @@  discard block
 block discarded – undo
1105 1105
 						print '<td align="center">';
1106 1106
 						if (image_format_supported($file['name']) > 0)
1107 1107
 						{
1108
-						    $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1109
-						    if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1108
+						    $minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1109
+						    if (!dol_is_file($file['path'].'/'.$minifile)) $minifile = getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1110 1110
 						    //print $file['path'].'/'.$minifile.'<br>';
1111 1111
 
1112
-						    $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1113
-						    if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1112
+						    $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
1113
+						    if (empty($urlforhref)) $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1114 1114
 						    print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1115
-							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1115
+							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1116 1116
 							print '</a>';
1117 1117
 						}
1118 1118
 						else print '&nbsp;';
1119 1119
 						print '</td>';
1120 1120
 					}
1121
-					if (! $editline)
1121
+					if (!$editline)
1122 1122
 					{
1123 1123
     					// Delete or view link
1124 1124
     					// ($param must start with &)
@@ -1129,24 +1129,24 @@  discard block
 block discarded – undo
1129 1129
     					}
1130 1130
     					else
1131 1131
     					{
1132
-        					$newmodulepart=$modulepart;
1133
-        					if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1132
+        					$newmodulepart = $modulepart;
1133
+        					if (in_array($modulepart, array('product', 'produit', 'service'))) $newmodulepart = 'produit|service';
1134 1134
 
1135
-        					$disablecrop=1;
1136
-        					if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0;
1135
+        					$disablecrop = 1;
1136
+        					if (in_array($modulepart, array('product', 'produit', 'service', 'expensereport', 'holiday', 'project', 'user'))) $disablecrop = 0;
1137 1137
 
1138
-    					    if (! $disablecrop && image_format_supported($file['name']) > 0)
1138
+    					    if (!$disablecrop && image_format_supported($file['name']) > 0)
1139 1139
     						{
1140 1140
     							if ($permtoeditline)
1141 1141
     							{
1142 1142
        								// Link to resize
1143
-       			               		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).'</a>';
1143
+       			               		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), DOL_URL_ROOT.'/theme/common/transform-crop-and-resize', 'class="paddingrightonly"', 1).'</a>';
1144 1144
     							}
1145 1145
     						}
1146 1146
 
1147 1147
     						if ($permtoeditline)
1148 1148
     						{
1149
-    						    print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=editfile&urlfile='.urlencode($filepath).$param).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1149
+    						    print '<a href="'.(($useinecm && $useajax) ? '#' : $url.'?action=editfile&urlfile='.urlencode($filepath).$param).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
1150 1150
     						}
1151 1151
     					}
1152 1152
     					if ($permonobject)
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
     						else
1158 1158
     							$filepath=$file['name'];
1159 1159
     						*/
1160
-    						$useajax=1;
1161
-    						if (! empty($conf->dol_use_jmobile)) $useajax=0;
1162
-    						if (empty($conf->use_javascript_ajax)) $useajax=0;
1163
-    						if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1160
+    						$useajax = 1;
1161
+    						if (!empty($conf->dol_use_jmobile)) $useajax = 0;
1162
+    						if (empty($conf->use_javascript_ajax)) $useajax = 0;
1163
+    						if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax = 0;
1164 1164
 
1165
-    						print '<a href="'.(($useinecm && $useajax)?'#':$url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1165
+    						print '<a href="'.(($useinecm && $useajax) ? '#' : $url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1166 1166
     					}
1167 1167
 					    print "</td>";
1168 1168
 
@@ -1171,15 +1171,15 @@  discard block
 block discarded – undo
1171 1171
     					    if ($nboffiles > 1 && empty($conf->browser->phone)) {
1172 1172
     					    	print '<td align="center" class="linecolmove tdlineupdown">';
1173 1173
     					    	if ($i > 0) {
1174
-    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1174
+    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default', 0, 'imgupforline').'</a>';
1175 1175
     					    	}
1176
-    					        if ($i < $nboffiles-1) {
1177
-    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1176
+    					        if ($i < $nboffiles - 1) {
1177
+    					    		print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default', 0, 'imgdownforline').'</a>';
1178 1178
     				    		}
1179 1179
     					    	print '</td>';
1180 1180
     					    }
1181 1181
     					    else {
1182
-    					       	print '<td align="center"'.((empty($conf->browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1182
+    					       	print '<td align="center"'.((empty($conf->browser->phone) && empty($disablemove)) ? ' class="linecolmove tdlineupdown"' : ' class="linecolmove"').'>';
1183 1183
     					       	print '</td>';
1184 1184
     					    }
1185 1185
 					   }
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
 			}
1200 1200
 			if ($nboffiles == 0)
1201 1201
 			{
1202
-			    $colspan=(empty($useinecm)?'5':'5');
1202
+			    $colspan = (empty($useinecm) ? '5' : '5');
1203 1203
 			    if (empty($disablemove)) $colspan++;
1204 1204
 				print '<tr '.$bc[false].'><td colspan="'.$colspan.'" class="opacitymedium">';
1205 1205
 				if (empty($textifempty)) print $langs->trans("NoFileFound");
@@ -1209,14 +1209,14 @@  discard block
 block discarded – undo
1209 1209
 			print "</table>";
1210 1210
 			print '</div>';
1211 1211
 
1212
-			if (! $editline && $nboflines > 1) {
1213
-				if (! empty($conf->use_javascript_ajax) && $permtoeditline) {
1212
+			if (!$editline && $nboflines > 1) {
1213
+				if (!empty($conf->use_javascript_ajax) && $permtoeditline) {
1214 1214
 				    $table_element_line = 'ecm_files';
1215
-				    include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1215
+				    include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
1216 1216
 				}
1217 1217
 			}
1218 1218
 
1219
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1219
+			if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline)
1220 1220
 			{
1221 1221
 			    print '</form>';
1222 1222
 			}
@@ -1243,7 +1243,7 @@  discard block
 block discarded – undo
1243 1243
      *  @param	int		$addfilterfields	Add line with filters
1244 1244
      *  @return int                 		<0 if KO, nb of files shown if OK
1245 1245
      */
1246
-    function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0)
1246
+    function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload = 0, $relativepath = '', $permtodelete = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $url = '', $addfilterfields = 0)
1247 1247
     {
1248 1248
         global $user, $conf, $langs, $form;
1249 1249
         global $bc;
@@ -1254,9 +1254,9 @@  discard block
 block discarded – undo
1254 1254
 
1255 1255
         // Show list of documents
1256 1256
         if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1257
-        if (empty($url)) $url=$_SERVER["PHP_SELF"];
1257
+        if (empty($url)) $url = $_SERVER["PHP_SELF"];
1258 1258
 
1259
-        if (! empty($addfilterfields))
1259
+        if (!empty($addfilterfields))
1260 1260
         {
1261 1261
         	print '<form action="'.$_SERVER['PHP_SELF'].'">';
1262 1262
         	print '<input type="hidden" name="module" value="'.$modulepart.'">';
@@ -1265,7 +1265,7 @@  discard block
 block discarded – undo
1265 1265
 		print '<div class="div-table-responsive-no-min">';
1266 1266
         print '<table width="100%" class="noborder">'."\n";
1267 1267
 
1268
-        if (! empty($addfilterfields))
1268
+        if (!empty($addfilterfields))
1269 1269
         {
1270 1270
         	print '<tr class="liste_titre nodrag nodrop">';
1271 1271
         	print '<td><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
@@ -1274,130 +1274,130 @@  discard block
 block discarded – undo
1274 1274
         	print '<td></td>';
1275 1275
 			// Action column
1276 1276
 			print '<td class="liste_titre" align="middle">';
1277
-			$searchpicto=$form->showFilterButtons();
1277
+			$searchpicto = $form->showFilterButtons();
1278 1278
 			print $searchpicto;
1279 1279
 			print '</td>';
1280 1280
         	print "</tr>\n";
1281 1281
         }
1282 1282
 
1283 1283
         print '<tr class="liste_titre">';
1284
-        $sortref="fullname";
1285
-        if ($modulepart == 'invoice_supplier') $sortref='level1name';
1286
-        print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1287
-        print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1288
-        print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1289
-        print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1290
-        print_liste_field_titre('','','');
1284
+        $sortref = "fullname";
1285
+        if ($modulepart == 'invoice_supplier') $sortref = 'level1name';
1286
+        print_liste_field_titre("Ref", $url, $sortref, "", $param, 'align="left"', $sortfield, $sortorder);
1287
+        print_liste_field_titre("Documents2", $url, "name", "", $param, 'align="left"', $sortfield, $sortorder);
1288
+        print_liste_field_titre("Size", $url, "size", "", $param, 'align="right"', $sortfield, $sortorder);
1289
+        print_liste_field_titre("Date", $url, "date", "", $param, 'align="center"', $sortfield, $sortorder);
1290
+        print_liste_field_titre('', '', '');
1291 1291
         print '</tr>'."\n";
1292 1292
 
1293 1293
         // To show ref or specific information according to view to show (defined by $module)
1294 1294
         if ($modulepart == 'company')
1295 1295
         {
1296 1296
             include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1297
-            $object_instance=new Societe($this->db);
1297
+            $object_instance = new Societe($this->db);
1298 1298
         }
1299 1299
         else if ($modulepart == 'invoice')
1300 1300
         {
1301 1301
             include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1302
-            $object_instance=new Facture($this->db);
1302
+            $object_instance = new Facture($this->db);
1303 1303
         }
1304 1304
         else if ($modulepart == 'invoice_supplier')
1305 1305
         {
1306 1306
             include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1307
-            $object_instance=new FactureFournisseur($this->db);
1307
+            $object_instance = new FactureFournisseur($this->db);
1308 1308
         }
1309 1309
         else if ($modulepart == 'propal')
1310 1310
         {
1311 1311
             include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1312
-            $object_instance=new Propal($this->db);
1312
+            $object_instance = new Propal($this->db);
1313 1313
         }
1314 1314
         else if ($modulepart == 'supplier_proposal')
1315 1315
         {
1316 1316
             include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1317
-            $object_instance=new SupplierProposal($this->db);
1317
+            $object_instance = new SupplierProposal($this->db);
1318 1318
         }
1319 1319
         else if ($modulepart == 'order')
1320 1320
         {
1321 1321
             include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1322
-            $object_instance=new Commande($this->db);
1322
+            $object_instance = new Commande($this->db);
1323 1323
         }
1324 1324
         else if ($modulepart == 'order_supplier')
1325 1325
         {
1326 1326
             include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1327
-            $object_instance=new CommandeFournisseur($this->db);
1327
+            $object_instance = new CommandeFournisseur($this->db);
1328 1328
         }
1329 1329
         else if ($modulepart == 'contract')
1330 1330
         {
1331 1331
             include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1332
-            $object_instance=new Contrat($this->db);
1332
+            $object_instance = new Contrat($this->db);
1333 1333
         }
1334 1334
         else if ($modulepart == 'product')
1335 1335
         {
1336 1336
             include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1337
-            $object_instance=new Product($this->db);
1337
+            $object_instance = new Product($this->db);
1338 1338
         }
1339 1339
         else if ($modulepart == 'tax')
1340 1340
         {
1341 1341
             include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1342
-            $object_instance=new ChargeSociales($this->db);
1342
+            $object_instance = new ChargeSociales($this->db);
1343 1343
         }
1344 1344
         else if ($modulepart == 'project')
1345 1345
         {
1346 1346
         	include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1347
-        	$object_instance=new Project($this->db);
1347
+        	$object_instance = new Project($this->db);
1348 1348
         }
1349 1349
         else if ($modulepart == 'fichinter')
1350 1350
         {
1351 1351
         	include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1352
-        	$object_instance=new Fichinter($this->db);
1352
+        	$object_instance = new Fichinter($this->db);
1353 1353
         }
1354 1354
         else if ($modulepart == 'user')
1355 1355
         {
1356 1356
         	include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1357
-        	$object_instance=new User($this->db);
1357
+        	$object_instance = new User($this->db);
1358 1358
         }
1359 1359
         else if ($modulepart == 'expensereport')
1360 1360
         {
1361 1361
         	include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1362
-        	$object_instance=new ExpenseReport($this->db);
1362
+        	$object_instance = new ExpenseReport($this->db);
1363 1363
         }
1364 1364
 
1365
-        $var=true;
1366
-        foreach($filearray as $key => $file)
1365
+        $var = true;
1366
+        foreach ($filearray as $key => $file)
1367 1367
         {
1368 1368
         	if (!is_dir($file['name'])
1369 1369
             && $file['name'] != '.'
1370 1370
             && $file['name'] != '..'
1371 1371
             && $file['name'] != 'CVS'
1372
-            && ! preg_match('/\.meta$/i',$file['name']))
1372
+            && !preg_match('/\.meta$/i', $file['name']))
1373 1373
             {
1374 1374
                 // Define relative path used to store the file
1375
-                $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1375
+                $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']);
1376 1376
 
1377 1377
                 //var_dump($file);
1378
-                $id=0; $ref=''; $label='';
1378
+                $id = 0; $ref = ''; $label = '';
1379 1379
 
1380 1380
                 // To show ref or specific information according to view to show (defined by $module)
1381
-                if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1382
-                if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1383
-                if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1384
-                if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1385
-				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1386
-                if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1387
-                if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1388
-                if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1389
-                if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1390
-                if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1391
-                if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1392
-                if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1393
-                if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1394
-                if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1395
-
1396
-                if (! $id && ! $ref) continue;
1397
-                $found=0;
1398
-                if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1381
+                if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1382
+                if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1383
+                if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); if (is_numeric($ref)) { $id = $ref; $ref = ''; } }	// $ref may be also id with old supplier invoices
1384
+                if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1385
+				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1386
+                if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1387
+                if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1388
+                if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1389
+                if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1390
+                if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1391
+                if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1392
+                if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1393
+                if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1394
+                if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1395
+
1396
+                if (!$id && !$ref) continue;
1397
+                $found = 0;
1398
+                if (!empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1399 1399
                 {
1400
-                    $found=1;
1400
+                    $found = 1;
1401 1401
                 }
1402 1402
                 else
1403 1403
                 {
@@ -1416,24 +1416,24 @@  discard block
 block discarded – undo
1416 1416
                     }
1417 1417
 
1418 1418
 					if ($result > 0) {  // Save object into a cache
1419
-						$found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1419
+						$found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1420 1420
 					}
1421
-                    if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1421
+                    if ($result == 0) { $found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = 'notfound'; unset($filearray[$key]); }
1422 1422
                 }
1423 1423
 
1424
-                if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1424
+                if (!$found > 0 || !is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files
1425 1425
 
1426 1426
                 print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1427 1427
                 print '<tr class="oddeven">';
1428 1428
                 print '<td>';
1429
-                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1430
-                else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1429
+                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1, 'document');
1430
+                else print $langs->trans("ObjectDeleted", ($id ? $id : $ref));
1431 1431
 
1432 1432
                 //$modulesubdir=dol_sanitizeFileName($ref);
1433
-                $modulesubdir=dirname($relativefile);
1433
+                $modulesubdir = dirname($relativefile);
1434 1434
 
1435 1435
                 //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1436
-                $filedir=$file['path'];
1436
+                $filedir = $file['path'];
1437 1437
                 //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1438 1438
                 //print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1439 1439
 
@@ -1445,15 +1445,15 @@  discard block
 block discarded – undo
1445 1445
                 print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1446 1446
                 if ($forcedownload) print '&attachment=1';
1447 1447
                 print '&file='.urlencode($relativefile).'">';
1448
-                print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
1449
-                print dol_trunc($file['name'],$maxlength,'middle');
1448
+                print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')').' ';
1449
+                print dol_trunc($file['name'], $maxlength, 'middle');
1450 1450
                 print '</a>';
1451 1451
 
1452
-                print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1452
+                print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'], '/').'$');
1453 1453
 
1454 1454
                 print "</td>\n";
1455
-                print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1456
-                print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1455
+                print '<td align="right">'.dol_print_size($file['size'], 1, 1).'</td>';
1456
+                print '<td align="center">'.dol_print_date($file['date'], "dayhour").'</td>';
1457 1457
                 print '<td align="right">';
1458 1458
                 //if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1459 1459
                 //if ($forcedownload) print '&attachment=1';
@@ -1475,7 +1475,7 @@  discard block
 block discarded – undo
1475 1475
         print "</table>";
1476 1476
         print '</div>';
1477 1477
 
1478
-        if (! empty($addfilterfields)) print '</form>';
1478
+        if (!empty($addfilterfields)) print '</form>';
1479 1479
         // Fin de zone
1480 1480
     }
1481 1481
 
@@ -1501,7 +1501,7 @@  discard block
 block discarded – undo
1501 1501
         $mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1502 1502
         $upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1503 1503
         // Max file size
1504
-        $max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1504
+        $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1505 1505
 
1506 1506
         // Include main
1507 1507
         include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
      * @param	string		$param			More param to add into URL
1522 1522
      * @return 	int							Number of links
1523 1523
      */
1524
-    public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1524
+    public function listOfLinks($object, $permtodelete = 1, $action = null, $selected = null, $param = '')
1525 1525
     {
1526 1526
         global $user, $conf, $langs, $user;
1527 1527
         global $bc;
@@ -1529,7 +1529,7 @@  discard block
 block discarded – undo
1529 1529
 
1530 1530
         $langs->load("link");
1531 1531
 
1532
-        require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1532
+        require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
1533 1533
         $link = new Link($this->db);
1534 1534
         $links = array();
1535 1535
         if ($sortfield == "name") {
@@ -1540,12 +1540,12 @@  discard block
 block discarded – undo
1540 1540
             $sortfield = null;
1541 1541
         }
1542 1542
         $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1543
-        $param .= (isset($object->id)?'&id=' . $object->id : '');
1543
+        $param .= (isset($object->id) ? '&id='.$object->id : '');
1544 1544
 
1545 1545
         // Show list of associated links
1546 1546
         print load_fiche_titre($langs->trans("LinkedFiles"));
1547 1547
 
1548
-        print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1548
+        print '<form action="'.$_SERVER['PHP_SELF'].($param ? '?'.$param : '').'" method="POST">';
1549 1549
 
1550 1550
         print '<table width="100%" class="liste">';
1551 1551
         print '<tr class="liste_titre">';
@@ -1585,7 +1585,7 @@  discard block
 block discarded – undo
1585 1585
             $param,
1586 1586
             'align="center"'
1587 1587
         );
1588
-        print_liste_field_titre('','','');
1588
+        print_liste_field_titre('', '', '');
1589 1589
         print '</tr>';
1590 1590
         $nboflinks = count($links);
1591 1591
         if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
@@ -1593,42 +1593,42 @@  discard block
 block discarded – undo
1593 1593
         $var = true;
1594 1594
         foreach ($links as $link)
1595 1595
         {
1596
-            $var =! $var;
1597
-            print '<tr ' . $bc[$var] . '>';
1596
+            $var = !$var;
1597
+            print '<tr '.$bc[$var].'>';
1598 1598
             //edit mode
1599 1599
             if ($action == 'update' && $selected === $link->id)
1600 1600
             {
1601 1601
                 print '<td>';
1602
-                print '<input type="hidden" name="id" value="' . $object->id . '">';
1603
-                print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1602
+                print '<input type="hidden" name="id" value="'.$object->id.'">';
1603
+                print '<input type="hidden" name="linkid" value="'.$link->id.'">';
1604 1604
                 print '<input type="hidden" name="action" value="confirm_updateline">';
1605
-                print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1605
+                print $langs->trans('Link').': <input type="text" name="link" value="'.$link->url.'">';
1606 1606
                 print '</td>';
1607 1607
                 print '<td>';
1608
-                print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1608
+                print $langs->trans('Label').': <input type="text" name="label" value="'.$link->label.'">';
1609 1609
                 print '</td>';
1610
-                print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1610
+                print '<td align="center">'.dol_print_date(dol_now(), "dayhour", "tzuser").'</td>';
1611 1611
                 print '<td align="right"></td>';
1612 1612
                 print '<td align="right">';
1613
-                print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1614
-                print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1613
+                print '<input type="submit" name="save" class="button" value="'.dol_escape_htmltag($langs->trans('Save')).'">';
1614
+                print '<input type="submit" name="cancel" class="button" value="'.dol_escape_htmltag($langs->trans('Cancel')).'">';
1615 1615
                 print '</td>';
1616 1616
             }
1617 1617
             else
1618 1618
 			{
1619 1619
                 print '<td>';
1620 1620
                 print img_picto('', 'object_globe').' ';
1621
-                print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1621
+                print '<a data-ajax="false" href="'.$link->url.'" target="_blank">';
1622 1622
                 print $link->label;
1623 1623
                 print '</a>';
1624 1624
                 print '</td>'."\n";
1625 1625
                 print '<td align="right"></td>';
1626
-                print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1626
+                print '<td align="center">'.dol_print_date($link->datea, "dayhour", "tzuser").'</td>';
1627 1627
                 print '<td align="center"></td>';
1628 1628
                 print '<td align="right">';
1629
-                print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1629
+                print '<a href="'.$_SERVER['PHP_SELF'].'?action=update&linkid='.$link->id.$param.'" class="editfilelink" >'.img_edit().'</a>'; // id= is included into $param
1630 1630
                 if ($permtodelete) {
1631
-                    print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1631
+                    print ' &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?action=delete&linkid='.$link->id.$param.'" class="deletefilelink">'.img_delete().'</a>'; // id= is included into $param
1632 1632
                 } else {
1633 1633
                     print '&nbsp;';
1634 1634
                 }
@@ -1638,7 +1638,7 @@  discard block
 block discarded – undo
1638 1638
         }
1639 1639
         if ($nboflinks == 0)
1640 1640
         {
1641
-            print '<tr ' . $bc[false] . '><td colspan="5" class="opacitymedium">';
1641
+            print '<tr '.$bc[false].'><td colspan="5" class="opacitymedium">';
1642 1642
             print $langs->trans("NoLinkFound");
1643 1643
             print '</td></tr>';
1644 1644
         }
@@ -1660,21 +1660,21 @@  discard block
 block discarded – undo
1660 1660
      * @param	string	  $param		  More param on http links
1661 1661
      * @return  string    $out            Output string with HTML
1662 1662
      */
1663
-    public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1663
+    public function showPreview($file, $modulepart, $relativepath, $ruleforpicto = 0, $param = '')
1664 1664
     {
1665 1665
         global $langs, $conf;
1666 1666
 
1667
-        $out='';
1668
-        if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1667
+        $out = '';
1668
+        if ($conf->browser->layout != 'phone' && !empty($conf->use_javascript_ajax))
1669 1669
         {
1670
-            $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1670
+            $urladvancedpreview = getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview.
1671 1671
             if (count($urladvancedpreview))
1672 1672
             {
1673
-                $out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1673
+                $out .= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime']) ? '' : ' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target']) ? '' : ' target="'.$urladvancedpreview['target'].'"').'>';
1674 1674
                 //$out.= '<a class="pictopreview">';
1675
-            	if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1676
-                else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1677
-                $out.= '</a>';
1675
+            	if (empty($ruleforpicto)) $out .= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1676
+                else $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1677
+                $out .= '</a>';
1678 1678
             }
1679 1679
         }
1680 1680
         return $out;
Please login to merge, or discard this patch.