Test Failed
Branch develop (86e751)
by Laurent
34:11
created
htdocs/comm/propal/class/propal.class.php 4 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -391,11 +391,11 @@  discard block
 block discarded – undo
391 391
      *      @param		string		$label				???
392 392
      *		@param      int			$date_start       	Start date of the line
393 393
      *		@param      int			$date_end         	End date of the line
394
-     *      @param		array		$array_options		extrafields array
394
+     *      @param		integer		$array_options		extrafields array
395 395
      * 		@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
396 396
      *      @param		string		$origin				'order', ...
397 397
      *      @param		int			$origin_id			Id of origin object
398
-     * 		@param		double		$pu_ht_devise		Unit price in currency
398
+     * 		@param		integer		$pu_ht_devise		Unit price in currency
399 399
      * 		@param		int    		$fk_remise_except	Id discount if line is from a discount
400 400
      *    	@return    	int         	    			>0 if OK, <0 if KO
401 401
      *    	@see       	add_product
@@ -615,9 +615,9 @@  discard block
 block discarded – undo
615 615
      *  @param		int			$type				0/1=Product/service
616 616
      *	@param      int			$date_start       	Start date of the line
617 617
      *	@param      int			$date_end         	End date of the line
618
-	 *  @param		array		$array_options		extrafields array
618
+	 *  @param		integer		$array_options		extrafields array
619 619
      * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
620
-	 * 	@param		double		$pu_ht_devise		Unit price in currency
620
+	 * 	@param		integer		$pu_ht_devise		Unit price in currency
621 621
 	 * 	@param		int			$notrigger			disable line update trigger
622 622
      *  @return     int     		        		0 if OK, <0 if KO
623 623
      */
Please login to merge, or discard this patch.
Indentation   +3342 added lines, -3342 removed lines patch added patch discarded remove patch
@@ -44,40 +44,40 @@  discard block
 block discarded – undo
44 44
  */
45 45
 class Propal extends CommonObject
46 46
 {
47
-    public $element='propal';
48
-    public $table_element='propal';
49
-    public $table_element_line='propaldet';
50
-    public $fk_element='fk_propal';
51
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
-    public $picto='propal';
47
+	public $element='propal';
48
+	public $table_element='propal';
49
+	public $table_element_line='propaldet';
50
+	public $fk_element='fk_propal';
51
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
+	public $picto='propal';
53 53
 
54
-    /**
55
-     * {@inheritdoc}
56
-     */
57
-    protected $table_ref_field = 'ref';
54
+	/**
55
+	 * {@inheritdoc}
56
+	 */
57
+	protected $table_ref_field = 'ref';
58 58
 
59 59
 	/**
60 60
 	 * ID of the client
61 61
 	 * @var int
62 62
 	 */
63
-    public $socid;
63
+	public $socid;
64 64
 
65
-    public $contactid;
66
-    public $author;
67
-    public $ref_client;
65
+	public $contactid;
66
+	public $author;
67
+	public $ref_client;
68 68
 
69 69
 	/**
70 70
 	 * Status of the quote
71 71
 	 * @var int
72 72
 	 * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED
73 73
 	 */
74
-    public $statut;
74
+	public $statut;
75 75
 
76 76
 	/**
77 77
 	 * @deprecated
78 78
 	 * @see date_creation
79 79
 	 */
80
-    public $datec;
80
+	public $datec;
81 81
 
82 82
 	/**
83 83
 	 * Creation date
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 * @deprecated
90 90
 	 * @see date_validation
91 91
 	 */
92
-    public $datev;
92
+	public $datev;
93 93
 
94 94
 	/**
95 95
 	 * Validation date
@@ -101,62 +101,62 @@  discard block
 block discarded – undo
101 101
 	 * Date of the quote
102 102
 	 * @var
103 103
 	 */
104
-    public $date;
104
+	public $date;
105 105
 
106 106
 	/**
107 107
 	 * @deprecated
108 108
 	 * @see date
109 109
 	 */
110
-    public $datep;
111
-    public $date_livraison;
112
-    public $fin_validite;
110
+	public $datep;
111
+	public $date_livraison;
112
+	public $fin_validite;
113 113
 
114
-    public $user_author_id;
115
-    public $user_valid_id;
116
-    public $user_close_id;
114
+	public $user_author_id;
115
+	public $user_valid_id;
116
+	public $user_close_id;
117 117
 
118 118
 	/**
119 119
 	 * @deprecated
120 120
 	 * @see total_ht
121 121
 	 */
122
-    public $price;
122
+	public $price;
123 123
 	/**
124 124
 	 * @deprecated
125 125
 	 * @see total_tva
126 126
 	 */
127
-    public $tva;
127
+	public $tva;
128 128
 	/**
129 129
 	 * @deprecated
130 130
 	 * @see total_ttc
131 131
 	 */
132
-    public $total;
133
-
134
-    public $cond_reglement_code;
135
-    public $mode_reglement_code;
136
-    public $remise;
137
-    public $remise_percent;
138
-    public $remise_absolue;
139
-    public $fk_address;
140
-    public $address_type;
141
-    public $address;
142
-    public $availability_id;
143
-    public $availability_code;
144
-    public $demand_reason_id;
145
-    public $demand_reason_code;
146
-
147
-    public $products=array();
148
-    public $extraparams=array();
132
+	public $total;
133
+
134
+	public $cond_reglement_code;
135
+	public $mode_reglement_code;
136
+	public $remise;
137
+	public $remise_percent;
138
+	public $remise_absolue;
139
+	public $fk_address;
140
+	public $address_type;
141
+	public $address;
142
+	public $availability_id;
143
+	public $availability_code;
144
+	public $demand_reason_id;
145
+	public $demand_reason_code;
146
+
147
+	public $products=array();
148
+	public $extraparams=array();
149 149
 
150 150
 	/**
151 151
 	 * @var PropaleLigne[]
152 152
 	 */
153
-    public $lines = array();
154
-    public $line;
153
+	public $lines = array();
154
+	public $line;
155 155
 
156
-    public $labelstatut=array();
157
-    public $labelstatut_short=array();
156
+	public $labelstatut=array();
157
+	public $labelstatut_short=array();
158 158
 
159
-    public $specimen;
159
+	public $specimen;
160 160
 
161 161
 	// Multicurrency
162 162
 	public $fk_multicurrency;
@@ -189,256 +189,256 @@  discard block
 block discarded – undo
189 189
 	 */
190 190
 	const STATUS_BILLED = 4;   // Todo rename into STATUS_CLOSE ?
191 191
 
192
-    /**
193
-     *	Constructor
194
-     *
195
-     *	@param      DoliDB	$db         Database handler
196
-     *	@param      int		$socid		Id third party
197
-     *	@param      int		$propalid   Id proposal
198
-     */
199
-    function __construct($db, $socid="", $propalid=0)
200
-    {
201
-        global $conf,$langs;
202
-
203
-        $this->db = $db;
204
-        $this->socid = $socid;
205
-        $this->id = $propalid;
206
-        $this->products = array();
207
-        $this->remise = 0;
208
-        $this->remise_percent = 0;
209
-        $this->remise_absolue = 0;
210
-
211
-        $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION;
212
-
213
-        $langs->load("propal");
214
-        $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft"));
215
-        $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated"));
216
-        $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned"));
217
-        $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned"));
218
-        $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled"));
219
-        $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort"));
220
-        $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened"));
221
-        $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort"));
222
-        $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort"));
223
-        $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort"));
224
-    }
225
-
226
-
227
-    /**
228
-     * 	Add line into array products
229
-     *	$this->thirdparty should be loaded
230
-     *
231
-     * 	@param  int		$idproduct       	Product Id to add
232
-     * 	@param  int		$qty             	Quantity
233
-     * 	@param  int		$remise_percent  	Discount effected on Product
234
-     *  @return	int							<0 if KO, >0 if OK
235
-     *
236
-     *	TODO	Replace calls to this function by generation objet Ligne
237
-     *			inserted into table $this->products
238
-     */
239
-    function add_product($idproduct, $qty, $remise_percent=0)
240
-    {
241
-        global $conf, $mysoc;
242
-
243
-        if (! $qty) $qty = 1;
244
-
245
-        dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
246
-        if ($idproduct > 0)
247
-        {
248
-            $prod=new Product($this->db);
249
-            $prod->fetch($idproduct);
250
-
251
-            $productdesc = $prod->description;
252
-
253
-            $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
254
-            $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
255
-            if (empty($tva_tx)) $tva_npr=0;
256
-            $vat_src_code = '';     // May be defined into tva_tx
257
-
258
-            $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr);
259
-            $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr);
260
-
261
-            // multiprices
262
-            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
263
-            {
264
-                $price = $prod->multiprices[$this->thirdparty->price_level];
265
-            }
266
-            else
267
-            {
268
-                $price = $prod->price;
269
-            }
270
-
271
-            $line = new PropaleLigne($this->db);
272
-
273
-            $line->fk_product=$idproduct;
274
-            $line->desc=$productdesc;
275
-            $line->qty=$qty;
276
-            $line->subprice=$price;
277
-            $line->remise_percent=$remise_percent;
278
-            $line->vat_src_code=$vat_src_code;
279
-            $line->tva_tx=$tva_tx;
280
-	        $line->fk_unit=$prod->fk_unit;
192
+	/**
193
+	 *	Constructor
194
+	 *
195
+	 *	@param      DoliDB	$db         Database handler
196
+	 *	@param      int		$socid		Id third party
197
+	 *	@param      int		$propalid   Id proposal
198
+	 */
199
+	function __construct($db, $socid="", $propalid=0)
200
+	{
201
+		global $conf,$langs;
202
+
203
+		$this->db = $db;
204
+		$this->socid = $socid;
205
+		$this->id = $propalid;
206
+		$this->products = array();
207
+		$this->remise = 0;
208
+		$this->remise_percent = 0;
209
+		$this->remise_absolue = 0;
210
+
211
+		$this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION;
212
+
213
+		$langs->load("propal");
214
+		$this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft"));
215
+		$this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated"));
216
+		$this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned"));
217
+		$this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned"));
218
+		$this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled"));
219
+		$this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort"));
220
+		$this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened"));
221
+		$this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort"));
222
+		$this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort"));
223
+		$this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort"));
224
+	}
225
+
226
+
227
+	/**
228
+	 * 	Add line into array products
229
+	 *	$this->thirdparty should be loaded
230
+	 *
231
+	 * 	@param  int		$idproduct       	Product Id to add
232
+	 * 	@param  int		$qty             	Quantity
233
+	 * 	@param  int		$remise_percent  	Discount effected on Product
234
+	 *  @return	int							<0 if KO, >0 if OK
235
+	 *
236
+	 *	TODO	Replace calls to this function by generation objet Ligne
237
+	 *			inserted into table $this->products
238
+	 */
239
+	function add_product($idproduct, $qty, $remise_percent=0)
240
+	{
241
+		global $conf, $mysoc;
242
+
243
+		if (! $qty) $qty = 1;
244
+
245
+		dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
246
+		if ($idproduct > 0)
247
+		{
248
+			$prod=new Product($this->db);
249
+			$prod->fetch($idproduct);
250
+
251
+			$productdesc = $prod->description;
252
+
253
+			$tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
254
+			$tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
255
+			if (empty($tva_tx)) $tva_npr=0;
256
+			$vat_src_code = '';     // May be defined into tva_tx
257
+
258
+			$localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr);
259
+			$localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr);
260
+
261
+			// multiprices
262
+			if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
263
+			{
264
+				$price = $prod->multiprices[$this->thirdparty->price_level];
265
+			}
266
+			else
267
+			{
268
+				$price = $prod->price;
269
+			}
270
+
271
+			$line = new PropaleLigne($this->db);
272
+
273
+			$line->fk_product=$idproduct;
274
+			$line->desc=$productdesc;
275
+			$line->qty=$qty;
276
+			$line->subprice=$price;
277
+			$line->remise_percent=$remise_percent;
278
+			$line->vat_src_code=$vat_src_code;
279
+			$line->tva_tx=$tva_tx;
280
+			$line->fk_unit=$prod->fk_unit;
281 281
 			if ($tva_npr) $line->info_bits = 1;
282 282
 
283
-            $this->lines[]=$line;
284
-        }
285
-    }
286
-
287
-    /**
288
-     *	Adding line of fixed discount in the proposal in DB
289
-     *
290
-     *	@param     int		$idremise			Id of fixed discount
291
-     *  @return    int          				>0 if OK, <0 if KO
292
-     */
293
-    function insert_discount($idremise)
294
-    {
295
-        global $langs;
296
-
297
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
298
-        include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
299
-
300
-        $this->db->begin();
301
-
302
-        $remise=new DiscountAbsolute($this->db);
303
-        $result=$remise->fetch($idremise);
304
-
305
-        if ($result > 0)
306
-        {
307
-            if ($remise->fk_facture)	// Protection against multiple submission
308
-            {
309
-                $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
310
-                $this->db->rollback();
311
-                return -5;
312
-            }
313
-
314
-            $line=new PropaleLigne($this->db);
315
-
316
-            $this->line->context = $this->context;
317
-
318
-            $line->fk_propal=$this->id;
319
-            $line->fk_remise_except=$remise->id;
320
-            $line->desc=$remise->description;   	// Description ligne
321
-            $line->vat_src_code=$remise->vat_src_code;
322
-            $line->tva_tx=$remise->tva_tx;
323
-            $line->subprice=-$remise->amount_ht;
324
-            $line->fk_product=0;					// Id produit predefined
325
-            $line->qty=1;
326
-            $line->remise=0;
327
-            $line->remise_percent=0;
328
-            $line->rang=-1;
329
-            $line->info_bits=2;
330
-
331
-            // TODO deprecated
332
-            $line->price=-$remise->amount_ht;
333
-
334
-            $line->total_ht  = -$remise->amount_ht;
335
-            $line->total_tva = -$remise->amount_tva;
336
-            $line->total_ttc = -$remise->amount_ttc;
337
-
338
-            $result=$line->insert();
339
-            if ($result > 0)
340
-            {
341
-                $result=$this->update_price(1);
342
-                if ($result > 0)
343
-                {
344
-                    $this->db->commit();
345
-                    return 1;
346
-                }
347
-                else
348
-                {
349
-                    $this->db->rollback();
350
-                    return -1;
351
-                }
352
-            }
353
-            else
354
-            {
355
-                $this->error=$line->error;
356
-                $this->db->rollback();
357
-                return -2;
358
-            }
359
-        }
360
-        else
361
-        {
362
-            $this->db->rollback();
363
-            return -2;
364
-        }
365
-    }
366
-
367
-    /**
368
-     *    	Add a proposal line into database (linked to product/service or not)
369
-     *      The parameters are already supposed to be appropriate and with final values to the call
370
-     *      of this method. Also, for the VAT rate, it must have already been defined
371
-     *      by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product)
372
-     *      and desc must already have the right value (it's up to the caller to manage multilanguage)
373
-     *
374
-     * 		@param    	string		$desc				Description de la ligne
375
-     * 		@param    	float		$pu_ht				Prix unitaire
376
-     * 		@param    	float		$qty             	Quantite
377
-     * 		@param    	float		$txtva           	Taux de tva
378
-     * 		@param		float		$txlocaltax1		Local tax 1 rate
379
-     *  	@param		float		$txlocaltax2		Local tax 2 rate
380
-     *		@param    	int			$fk_product      	Id du produit/service predefini
381
-     * 		@param    	float		$remise_percent  	Pourcentage de remise de la ligne
382
-     * 		@param    	string		$price_base_type	HT or TTC
383
-     * 		@param    	float		$pu_ttc             Prix unitaire TTC
384
-     * 		@param    	int			$info_bits			Bits de type de lignes
385
-     *      @param      int			$type               Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
386
-     *      @param      int			$rang               Position of line
387
-     *      @param		int			$special_code		Special code (also used by externals modules!)
388
-     *      @param		int			$fk_parent_line		Id of parent line
389
-     *      @param		int			$fk_fournprice		Id supplier price
390
-     *      @param		int			$pa_ht				Buying price without tax
391
-     *      @param		string		$label				???
392
-     *		@param      int			$date_start       	Start date of the line
393
-     *		@param      int			$date_end         	End date of the line
394
-     *      @param		array		$array_options		extrafields array
395
-     * 		@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
396
-     *      @param		string		$origin				'order', ...
397
-     *      @param		int			$origin_id			Id of origin object
398
-     * 		@param		double		$pu_ht_devise		Unit price in currency
399
-     * 		@param		int    		$fk_remise_except	Id discount if line is from a discount
400
-     *    	@return    	int         	    			>0 if OK, <0 if KO
401
-     *    	@see       	add_product
402
-     */
283
+			$this->lines[]=$line;
284
+		}
285
+	}
286
+
287
+	/**
288
+	 *	Adding line of fixed discount in the proposal in DB
289
+	 *
290
+	 *	@param     int		$idremise			Id of fixed discount
291
+	 *  @return    int          				>0 if OK, <0 if KO
292
+	 */
293
+	function insert_discount($idremise)
294
+	{
295
+		global $langs;
296
+
297
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
298
+		include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
299
+
300
+		$this->db->begin();
301
+
302
+		$remise=new DiscountAbsolute($this->db);
303
+		$result=$remise->fetch($idremise);
304
+
305
+		if ($result > 0)
306
+		{
307
+			if ($remise->fk_facture)	// Protection against multiple submission
308
+			{
309
+				$this->error=$langs->trans("ErrorDiscountAlreadyUsed");
310
+				$this->db->rollback();
311
+				return -5;
312
+			}
313
+
314
+			$line=new PropaleLigne($this->db);
315
+
316
+			$this->line->context = $this->context;
317
+
318
+			$line->fk_propal=$this->id;
319
+			$line->fk_remise_except=$remise->id;
320
+			$line->desc=$remise->description;   	// Description ligne
321
+			$line->vat_src_code=$remise->vat_src_code;
322
+			$line->tva_tx=$remise->tva_tx;
323
+			$line->subprice=-$remise->amount_ht;
324
+			$line->fk_product=0;					// Id produit predefined
325
+			$line->qty=1;
326
+			$line->remise=0;
327
+			$line->remise_percent=0;
328
+			$line->rang=-1;
329
+			$line->info_bits=2;
330
+
331
+			// TODO deprecated
332
+			$line->price=-$remise->amount_ht;
333
+
334
+			$line->total_ht  = -$remise->amount_ht;
335
+			$line->total_tva = -$remise->amount_tva;
336
+			$line->total_ttc = -$remise->amount_ttc;
337
+
338
+			$result=$line->insert();
339
+			if ($result > 0)
340
+			{
341
+				$result=$this->update_price(1);
342
+				if ($result > 0)
343
+				{
344
+					$this->db->commit();
345
+					return 1;
346
+				}
347
+				else
348
+				{
349
+					$this->db->rollback();
350
+					return -1;
351
+				}
352
+			}
353
+			else
354
+			{
355
+				$this->error=$line->error;
356
+				$this->db->rollback();
357
+				return -2;
358
+			}
359
+		}
360
+		else
361
+		{
362
+			$this->db->rollback();
363
+			return -2;
364
+		}
365
+	}
366
+
367
+	/**
368
+	 *    	Add a proposal line into database (linked to product/service or not)
369
+	 *      The parameters are already supposed to be appropriate and with final values to the call
370
+	 *      of this method. Also, for the VAT rate, it must have already been defined
371
+	 *      by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product)
372
+	 *      and desc must already have the right value (it's up to the caller to manage multilanguage)
373
+	 *
374
+	 * 		@param    	string		$desc				Description de la ligne
375
+	 * 		@param    	float		$pu_ht				Prix unitaire
376
+	 * 		@param    	float		$qty             	Quantite
377
+	 * 		@param    	float		$txtva           	Taux de tva
378
+	 * 		@param		float		$txlocaltax1		Local tax 1 rate
379
+	 *  	@param		float		$txlocaltax2		Local tax 2 rate
380
+	 *		@param    	int			$fk_product      	Id du produit/service predefini
381
+	 * 		@param    	float		$remise_percent  	Pourcentage de remise de la ligne
382
+	 * 		@param    	string		$price_base_type	HT or TTC
383
+	 * 		@param    	float		$pu_ttc             Prix unitaire TTC
384
+	 * 		@param    	int			$info_bits			Bits de type de lignes
385
+	 *      @param      int			$type               Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
386
+	 *      @param      int			$rang               Position of line
387
+	 *      @param		int			$special_code		Special code (also used by externals modules!)
388
+	 *      @param		int			$fk_parent_line		Id of parent line
389
+	 *      @param		int			$fk_fournprice		Id supplier price
390
+	 *      @param		int			$pa_ht				Buying price without tax
391
+	 *      @param		string		$label				???
392
+	 *		@param      int			$date_start       	Start date of the line
393
+	 *		@param      int			$date_end         	End date of the line
394
+	 *      @param		array		$array_options		extrafields array
395
+	 * 		@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
396
+	 *      @param		string		$origin				'order', ...
397
+	 *      @param		int			$origin_id			Id of origin object
398
+	 * 		@param		double		$pu_ht_devise		Unit price in currency
399
+	 * 		@param		int    		$fk_remise_except	Id discount if line is from a discount
400
+	 *    	@return    	int         	    			>0 if OK, <0 if KO
401
+	 *    	@see       	add_product
402
+	 */
403 403
 	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0)
404
-    {
405
-    	global $mysoc, $conf, $langs;
406
-
407
-        dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except);
408
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
409
-
410
-        // Clean parameters
411
-        if (empty($remise_percent)) $remise_percent=0;
412
-        if (empty($qty)) $qty=0;
413
-        if (empty($info_bits)) $info_bits=0;
414
-        if (empty($rang)) $rang=0;
415
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
416
-
417
-        $remise_percent=price2num($remise_percent);
418
-        $qty=price2num($qty);
419
-        $pu_ht=price2num($pu_ht);
420
-        $pu_ttc=price2num($pu_ttc);
421
-        $txtva=price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
422
-        $txlocaltax1=price2num($txlocaltax1);
423
-        $txlocaltax2=price2num($txlocaltax2);
424
-    	$pa_ht=price2num($pa_ht);
425
-        if ($price_base_type=='HT')
426
-        {
427
-            $pu=$pu_ht;
428
-        }
429
-        else
430
-        {
431
-            $pu=$pu_ttc;
432
-        }
433
-
434
-        // Check parameters
435
-        if ($type < 0) return -1;
436
-
437
-        if ($this->statut == self::STATUS_DRAFT)
438
-        {
439
-            $this->db->begin();
440
-
441
-        	$product_type=$type;
404
+	{
405
+		global $mysoc, $conf, $langs;
406
+
407
+		dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except);
408
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
409
+
410
+		// Clean parameters
411
+		if (empty($remise_percent)) $remise_percent=0;
412
+		if (empty($qty)) $qty=0;
413
+		if (empty($info_bits)) $info_bits=0;
414
+		if (empty($rang)) $rang=0;
415
+		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
416
+
417
+		$remise_percent=price2num($remise_percent);
418
+		$qty=price2num($qty);
419
+		$pu_ht=price2num($pu_ht);
420
+		$pu_ttc=price2num($pu_ttc);
421
+		$txtva=price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
422
+		$txlocaltax1=price2num($txlocaltax1);
423
+		$txlocaltax2=price2num($txlocaltax2);
424
+		$pa_ht=price2num($pa_ht);
425
+		if ($price_base_type=='HT')
426
+		{
427
+			$pu=$pu_ht;
428
+		}
429
+		else
430
+		{
431
+			$pu=$pu_ttc;
432
+		}
433
+
434
+		// Check parameters
435
+		if ($type < 0) return -1;
436
+
437
+		if ($this->statut == self::STATUS_DRAFT)
438
+		{
439
+			$this->db->begin();
440
+
441
+			$product_type=$type;
442 442
 			if (!empty($fk_product))
443 443
 			{
444 444
 				$product=new Product($this->db);
@@ -446,390 +446,390 @@  discard block
 block discarded – undo
446 446
 				$product_type=$product->type;
447 447
 
448 448
 				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) {
449
-                    $langs->load("errors");
450
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
449
+					$langs->load("errors");
450
+					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
451 451
 					$this->db->rollback();
452 452
 					return -3;
453 453
 				}
454 454
 			}
455 455
 
456 456
 			// Calcul du total TTC et de la TVA pour la ligne a partir de
457
-            // qty, pu, remise_percent et txtva
458
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
459
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
460
-
461
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
462
-
463
-            // Clean vat code
464
-            $vat_src_code='';
465
-            if (preg_match('/\((.*)\)/', $txtva, $reg))
466
-            {
467
-                $vat_src_code = $reg[1];
468
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
469
-            }
470
-
471
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
472
-
473
-            $total_ht  = $tabprice[0];
474
-            $total_tva = $tabprice[1];
475
-            $total_ttc = $tabprice[2];
476
-            $total_localtax1 = $tabprice[9];
477
-            $total_localtax2 = $tabprice[10];
457
+			// qty, pu, remise_percent et txtva
458
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
459
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
460
+
461
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
462
+
463
+			// Clean vat code
464
+			$vat_src_code='';
465
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
466
+			{
467
+				$vat_src_code = $reg[1];
468
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
469
+			}
470
+
471
+			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
472
+
473
+			$total_ht  = $tabprice[0];
474
+			$total_tva = $tabprice[1];
475
+			$total_ttc = $tabprice[2];
476
+			$total_localtax1 = $tabprice[9];
477
+			$total_localtax2 = $tabprice[10];
478 478
 			$pu_ht  = $tabprice[3];
479 479
 			$pu_tva = $tabprice[4];
480 480
 			$pu_ttc = $tabprice[5];
481 481
 
482 482
 			// MultiCurrency
483 483
 			$multicurrency_total_ht  = $tabprice[16];
484
-            $multicurrency_total_tva = $tabprice[17];
485
-            $multicurrency_total_ttc = $tabprice[18];
484
+			$multicurrency_total_tva = $tabprice[17];
485
+			$multicurrency_total_ttc = $tabprice[18];
486 486
 			$pu_ht_devise = $tabprice[19];
487 487
 
488
-            // Rang to use
489
-            $rangtouse = $rang;
490
-            if ($rangtouse == -1)
491
-            {
492
-                $rangmax = $this->line_max($fk_parent_line);
493
-                $rangtouse = $rangmax + 1;
494
-            }
495
-
496
-            // TODO A virer
497
-            // Anciens indicateurs: $price, $remise (a ne plus utiliser)
498
-            $price = $pu;
499
-            $remise = 0;
500
-            if ($remise_percent > 0)
501
-            {
502
-                $remise = round(($pu * $remise_percent / 100), 2);
503
-                $price = $pu - $remise;
504
-            }
505
-
506
-            // Insert line
507
-            $this->line=new PropaleLigne($this->db);
508
-
509
-            $this->line->context = $this->context;
510
-
511
-            $this->line->fk_propal=$this->id;
512
-            $this->line->label=$label;
513
-            $this->line->desc=$desc;
514
-            $this->line->qty=$qty;
488
+			// Rang to use
489
+			$rangtouse = $rang;
490
+			if ($rangtouse == -1)
491
+			{
492
+				$rangmax = $this->line_max($fk_parent_line);
493
+				$rangtouse = $rangmax + 1;
494
+			}
495
+
496
+			// TODO A virer
497
+			// Anciens indicateurs: $price, $remise (a ne plus utiliser)
498
+			$price = $pu;
499
+			$remise = 0;
500
+			if ($remise_percent > 0)
501
+			{
502
+				$remise = round(($pu * $remise_percent / 100), 2);
503
+				$price = $pu - $remise;
504
+			}
505
+
506
+			// Insert line
507
+			$this->line=new PropaleLigne($this->db);
508
+
509
+			$this->line->context = $this->context;
510
+
511
+			$this->line->fk_propal=$this->id;
512
+			$this->line->label=$label;
513
+			$this->line->desc=$desc;
514
+			$this->line->qty=$qty;
515 515
 
516 516
 			$this->line->vat_src_code=$vat_src_code;
517
-            $this->line->tva_tx=$txtva;
518
-            $this->line->localtax1_tx=$txlocaltax1;
519
-            $this->line->localtax2_tx=$txlocaltax2;
517
+			$this->line->tva_tx=$txtva;
518
+			$this->line->localtax1_tx=$txlocaltax1;
519
+			$this->line->localtax2_tx=$txlocaltax2;
520 520
 			$this->line->localtax1_type = $localtaxes_type[0];
521 521
 			$this->line->localtax2_type = $localtaxes_type[2];
522
-            $this->line->fk_product=$fk_product;
523
-            $this->line->product_type=$type;
524
-            $this->line->fk_remise_except=$fk_remise_except;
525
-            $this->line->remise_percent=$remise_percent;
526
-            $this->line->subprice=$pu_ht;
527
-            $this->line->rang=$rangtouse;
528
-            $this->line->info_bits=$info_bits;
529
-            $this->line->total_ht=$total_ht;
530
-            $this->line->total_tva=$total_tva;
531
-            $this->line->total_localtax1=$total_localtax1;
532
-            $this->line->total_localtax2=$total_localtax2;
533
-            $this->line->total_ttc=$total_ttc;
534
-            $this->line->special_code=$special_code;
535
-            $this->line->fk_parent_line=$fk_parent_line;
536
-            $this->line->fk_unit=$fk_unit;
537
-
538
-            $this->line->date_start=$date_start;
539
-            $this->line->date_end=$date_end;
522
+			$this->line->fk_product=$fk_product;
523
+			$this->line->product_type=$type;
524
+			$this->line->fk_remise_except=$fk_remise_except;
525
+			$this->line->remise_percent=$remise_percent;
526
+			$this->line->subprice=$pu_ht;
527
+			$this->line->rang=$rangtouse;
528
+			$this->line->info_bits=$info_bits;
529
+			$this->line->total_ht=$total_ht;
530
+			$this->line->total_tva=$total_tva;
531
+			$this->line->total_localtax1=$total_localtax1;
532
+			$this->line->total_localtax2=$total_localtax2;
533
+			$this->line->total_ttc=$total_ttc;
534
+			$this->line->special_code=$special_code;
535
+			$this->line->fk_parent_line=$fk_parent_line;
536
+			$this->line->fk_unit=$fk_unit;
537
+
538
+			$this->line->date_start=$date_start;
539
+			$this->line->date_end=$date_end;
540 540
 
541 541
 			$this->line->fk_fournprice = $fk_fournprice;
542 542
 			$this->line->pa_ht = $pa_ht;
543 543
 
544
-            $this->line->origin_id = $origin_id;
545
-            $this->line->origin = $origin;
544
+			$this->line->origin_id = $origin_id;
545
+			$this->line->origin = $origin;
546 546
 
547 547
 			// Multicurrency
548 548
 			$this->line->fk_multicurrency			= $this->fk_multicurrency;
549 549
 			$this->line->multicurrency_code			= $this->multicurrency_code;
550 550
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
551 551
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
552
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
553
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
552
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
553
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
554 554
 
555
-            // Mise en option de la ligne
556
-            if (empty($qty) && empty($special_code)) $this->line->special_code=3;
555
+			// Mise en option de la ligne
556
+			if (empty($qty) && empty($special_code)) $this->line->special_code=3;
557 557
 
558
-            // TODO deprecated
559
-            $this->line->price=$price;
560
-            $this->line->remise=$remise;
558
+			// TODO deprecated
559
+			$this->line->price=$price;
560
+			$this->line->remise=$remise;
561 561
 
562
-            if (is_array($array_options) && count($array_options)>0) {
563
-            	$this->line->array_options=$array_options;
564
-            }
562
+			if (is_array($array_options) && count($array_options)>0) {
563
+				$this->line->array_options=$array_options;
564
+			}
565 565
 
566
-            $result=$this->line->insert();
567
-            if ($result > 0)
568
-            {
569
-                // Reorder if child line
570
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
566
+			$result=$this->line->insert();
567
+			if ($result > 0)
568
+			{
569
+				// Reorder if child line
570
+				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
571 571
 
572
-                // Mise a jour informations denormalisees au niveau de la propale meme
573
-                $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
574
-                if ($result > 0)
575
-                {
576
-                    $this->db->commit();
577
-                    return $this->line->rowid;
578
-                }
579
-                else
580
-                {
581
-                    $this->error=$this->db->error();
582
-                    $this->db->rollback();
583
-                    return -1;
584
-                }
585
-            }
586
-            else
587
-            {
588
-                $this->error=$this->line->error;
589
-                $this->db->rollback();
590
-                return -2;
591
-            }
592
-        }
593
-    }
594
-
595
-
596
-    /**
597
-     *  Update a proposal line
598
-     *
599
-     *  @param      int			$rowid           	Id de la ligne
600
-     *  @param      float		$pu		     	  	Prix unitaire (HT ou TTC selon price_base_type)
601
-     *  @param      float		$qty            	Quantity
602
-     *  @param      float		$remise_percent  	Remise effectuee sur le produit
603
-     *  @param      float		$txtva	          	Taux de TVA
604
-     * 	@param	  	float		$txlocaltax1		Local tax 1 rate
605
-     *  @param	  	float		$txlocaltax2		Local tax 2 rate
606
-     *  @param      string		$desc            	Description
607
-     *	@param	  	string		$price_base_type	HT ou TTC
608
-     *	@param      int			$info_bits        	Miscellaneous informations
609
-     *	@param		int			$special_code		Special code (also used by externals modules!)
610
-     * 	@param		int			$fk_parent_line		Id of parent line (0 in most cases, used by modules adding sublevels into lines).
611
-     * 	@param		int			$skip_update_total	Keep fields total_xxx to 0 (used for special lines by some modules)
612
-     *  @param		int			$fk_fournprice		Id of origin supplier price
613
-     *  @param		int			$pa_ht				Price (without tax) of product when it was bought
614
-     *  @param		string		$label				???
615
-     *  @param		int			$type				0/1=Product/service
616
-     *	@param      int			$date_start       	Start date of the line
617
-     *	@param      int			$date_end         	End date of the line
572
+				// Mise a jour informations denormalisees au niveau de la propale meme
573
+				$result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
574
+				if ($result > 0)
575
+				{
576
+					$this->db->commit();
577
+					return $this->line->rowid;
578
+				}
579
+				else
580
+				{
581
+					$this->error=$this->db->error();
582
+					$this->db->rollback();
583
+					return -1;
584
+				}
585
+			}
586
+			else
587
+			{
588
+				$this->error=$this->line->error;
589
+				$this->db->rollback();
590
+				return -2;
591
+			}
592
+		}
593
+	}
594
+
595
+
596
+	/**
597
+	 *  Update a proposal line
598
+	 *
599
+	 *  @param      int			$rowid           	Id de la ligne
600
+	 *  @param      float		$pu		     	  	Prix unitaire (HT ou TTC selon price_base_type)
601
+	 *  @param      float		$qty            	Quantity
602
+	 *  @param      float		$remise_percent  	Remise effectuee sur le produit
603
+	 *  @param      float		$txtva	          	Taux de TVA
604
+	 * 	@param	  	float		$txlocaltax1		Local tax 1 rate
605
+	 *  @param	  	float		$txlocaltax2		Local tax 2 rate
606
+	 *  @param      string		$desc            	Description
607
+	 *	@param	  	string		$price_base_type	HT ou TTC
608
+	 *	@param      int			$info_bits        	Miscellaneous informations
609
+	 *	@param		int			$special_code		Special code (also used by externals modules!)
610
+	 * 	@param		int			$fk_parent_line		Id of parent line (0 in most cases, used by modules adding sublevels into lines).
611
+	 * 	@param		int			$skip_update_total	Keep fields total_xxx to 0 (used for special lines by some modules)
612
+	 *  @param		int			$fk_fournprice		Id of origin supplier price
613
+	 *  @param		int			$pa_ht				Price (without tax) of product when it was bought
614
+	 *  @param		string		$label				???
615
+	 *  @param		int			$type				0/1=Product/service
616
+	 *	@param      int			$date_start       	Start date of the line
617
+	 *	@param      int			$date_end         	End date of the line
618 618
 	 *  @param		array		$array_options		extrafields array
619
-     * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
619
+	 * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
620 620
 	 * 	@param		double		$pu_ht_devise		Unit price in currency
621 621
 	 * 	@param		int			$notrigger			disable line update trigger
622
-     *  @return     int     		        		0 if OK, <0 if KO
623
-     */
622
+	 *  @return     int     		        		0 if OK, <0 if KO
623
+	 */
624 624
 	function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
625
-    {
626
-        global $mysoc;
625
+	{
626
+		global $mysoc;
627 627
 
628
-        dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
628
+		dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
629 629
         txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, type=$type, date_start=$date_start, date_end=$date_end");
630
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
631
-
632
-        // Clean parameters
633
-        $remise_percent=price2num($remise_percent);
634
-        $qty=price2num($qty);
635
-        $pu = price2num($pu);
636
-        $txtva = price2num($txtva);
637
-        $txlocaltax1=price2num($txlocaltax1);
638
-        $txlocaltax2=price2num($txlocaltax2);
639
-    	$pa_ht=price2num($pa_ht);
640
-        if (empty($qty) && empty($special_code)) $special_code=3;    // Set option tag
641
-        if (! empty($qty) && $special_code == 3) $special_code=0;    // Remove option tag
642
-        if (empty($type)) $type=0;
643
-
644
-        if ($this->statut == self::STATUS_DRAFT)
645
-        {
646
-            $this->db->begin();
647
-
648
-            // Calcul du total TTC et de la TVA pour la ligne a partir de
649
-            // qty, pu, remise_percent et txtva
650
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
651
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
652
-
653
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
654
-
655
-            // Clean vat code
656
-            $vat_src_code='';
657
-            if (preg_match('/\((.*)\)/', $txtva, $reg))
658
-            {
659
-                $vat_src_code = $reg[1];
660
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
661
-            }
662
-
663
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
664
-            $total_ht  = $tabprice[0];
665
-            $total_tva = $tabprice[1];
666
-            $total_ttc = $tabprice[2];
667
-            $total_localtax1 = $tabprice[9];
668
-            $total_localtax2 = $tabprice[10];
630
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
631
+
632
+		// Clean parameters
633
+		$remise_percent=price2num($remise_percent);
634
+		$qty=price2num($qty);
635
+		$pu = price2num($pu);
636
+		$txtva = price2num($txtva);
637
+		$txlocaltax1=price2num($txlocaltax1);
638
+		$txlocaltax2=price2num($txlocaltax2);
639
+		$pa_ht=price2num($pa_ht);
640
+		if (empty($qty) && empty($special_code)) $special_code=3;    // Set option tag
641
+		if (! empty($qty) && $special_code == 3) $special_code=0;    // Remove option tag
642
+		if (empty($type)) $type=0;
643
+
644
+		if ($this->statut == self::STATUS_DRAFT)
645
+		{
646
+			$this->db->begin();
647
+
648
+			// Calcul du total TTC et de la TVA pour la ligne a partir de
649
+			// qty, pu, remise_percent et txtva
650
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
651
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
652
+
653
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
654
+
655
+			// Clean vat code
656
+			$vat_src_code='';
657
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
658
+			{
659
+				$vat_src_code = $reg[1];
660
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
661
+			}
662
+
663
+			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
664
+			$total_ht  = $tabprice[0];
665
+			$total_tva = $tabprice[1];
666
+			$total_ttc = $tabprice[2];
667
+			$total_localtax1 = $tabprice[9];
668
+			$total_localtax2 = $tabprice[10];
669 669
 			$pu_ht  = $tabprice[3];
670 670
 			$pu_tva = $tabprice[4];
671 671
 			$pu_ttc = $tabprice[5];
672 672
 
673 673
 			// MultiCurrency
674 674
 			$multicurrency_total_ht  = $tabprice[16];
675
-            $multicurrency_total_tva = $tabprice[17];
676
-            $multicurrency_total_ttc = $tabprice[18];
675
+			$multicurrency_total_tva = $tabprice[17];
676
+			$multicurrency_total_ttc = $tabprice[18];
677 677
 			$pu_ht_devise = $tabprice[19];
678 678
 
679
-            // Anciens indicateurs: $price, $remise (a ne plus utiliser)
680
-            $price = $pu;
681
-            if ($remise_percent > 0)
682
-            {
683
-                $remise = round(($pu * $remise_percent / 100), 2);
684
-                $price = $pu - $remise;
685
-            }
686
-
687
-            //Fetch current line from the database and then clone the object and set it in $oldline property
688
-            $line = new PropaleLigne($this->db);
689
-            $line->fetch($rowid);
679
+			// Anciens indicateurs: $price, $remise (a ne plus utiliser)
680
+			$price = $pu;
681
+			if ($remise_percent > 0)
682
+			{
683
+				$remise = round(($pu * $remise_percent / 100), 2);
684
+				$price = $pu - $remise;
685
+			}
686
+
687
+			//Fetch current line from the database and then clone the object and set it in $oldline property
688
+			$line = new PropaleLigne($this->db);
689
+			$line->fetch($rowid);
690 690
 			$line->fetch_optionals(); // Fetch extrafields for oldcopy
691 691
 
692 692
 			$staticline = clone $line;
693 693
 
694
-            $line->oldline = $staticline;
695
-            $this->line = $line;
696
-            $this->line->context = $this->context;
697
-
698
-            // Reorder if fk_parent_line change
699
-            if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
700
-            {
701
-                $rangmax = $this->line_max($fk_parent_line);
702
-                $this->line->rang = $rangmax + 1;
703
-            }
704
-
705
-            $this->line->rowid				= $rowid;
706
-            $this->line->label				= $label;
707
-            $this->line->desc				= $desc;
708
-            $this->line->qty				= $qty;
709
-            $this->line->product_type		= $type;
710
-            $this->line->vat_src_code		= $vat_src_code;
711
-            $this->line->tva_tx				= $txtva;
712
-            $this->line->localtax1_tx		= $txlocaltax1;
713
-            $this->line->localtax2_tx		= $txlocaltax2;
694
+			$line->oldline = $staticline;
695
+			$this->line = $line;
696
+			$this->line->context = $this->context;
697
+
698
+			// Reorder if fk_parent_line change
699
+			if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
700
+			{
701
+				$rangmax = $this->line_max($fk_parent_line);
702
+				$this->line->rang = $rangmax + 1;
703
+			}
704
+
705
+			$this->line->rowid				= $rowid;
706
+			$this->line->label				= $label;
707
+			$this->line->desc				= $desc;
708
+			$this->line->qty				= $qty;
709
+			$this->line->product_type		= $type;
710
+			$this->line->vat_src_code		= $vat_src_code;
711
+			$this->line->tva_tx				= $txtva;
712
+			$this->line->localtax1_tx		= $txlocaltax1;
713
+			$this->line->localtax2_tx		= $txlocaltax2;
714 714
 			$this->line->localtax1_type		= $localtaxes_type[0];
715 715
 			$this->line->localtax2_type		= $localtaxes_type[2];
716
-            $this->line->remise_percent		= $remise_percent;
717
-            $this->line->subprice			= $pu_ht;
718
-            $this->line->info_bits			= $info_bits;
719
-
720
-            $this->line->total_ht			= $total_ht;
721
-            $this->line->total_tva			= $total_tva;
722
-            $this->line->total_localtax1	= $total_localtax1;
723
-            $this->line->total_localtax2	= $total_localtax2;
724
-            $this->line->total_ttc			= $total_ttc;
725
-            $this->line->special_code		= $special_code;
726
-            $this->line->fk_parent_line		= $fk_parent_line;
727
-            $this->line->skip_update_total	= $skip_update_total;
728
-            $this->line->fk_unit	= $fk_unit;
716
+			$this->line->remise_percent		= $remise_percent;
717
+			$this->line->subprice			= $pu_ht;
718
+			$this->line->info_bits			= $info_bits;
719
+
720
+			$this->line->total_ht			= $total_ht;
721
+			$this->line->total_tva			= $total_tva;
722
+			$this->line->total_localtax1	= $total_localtax1;
723
+			$this->line->total_localtax2	= $total_localtax2;
724
+			$this->line->total_ttc			= $total_ttc;
725
+			$this->line->special_code		= $special_code;
726
+			$this->line->fk_parent_line		= $fk_parent_line;
727
+			$this->line->skip_update_total	= $skip_update_total;
728
+			$this->line->fk_unit	= $fk_unit;
729 729
 
730 730
 			$this->line->fk_fournprice = $fk_fournprice;
731
-            $this->line->pa_ht = $pa_ht;
731
+			$this->line->pa_ht = $pa_ht;
732 732
 
733
-            $this->line->date_start=$date_start;
734
-            $this->line->date_end=$date_end;
733
+			$this->line->date_start=$date_start;
734
+			$this->line->date_end=$date_end;
735 735
 
736
-            // TODO deprecated
737
-            $this->line->price=$price;
738
-            $this->line->remise=$remise;
736
+			// TODO deprecated
737
+			$this->line->price=$price;
738
+			$this->line->remise=$remise;
739 739
 
740
-            if (is_array($array_options) && count($array_options)>0) {
741
-            	$this->line->array_options=$array_options;
742
-            }
740
+			if (is_array($array_options) && count($array_options)>0) {
741
+				$this->line->array_options=$array_options;
742
+			}
743 743
 
744 744
 			// Multicurrency
745 745
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
746 746
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
747
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
748
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
749
-
750
-            $result=$this->line->update($notrigger);
751
-            if ($result > 0)
752
-            {
753
-                // Reorder if child line
754
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
755
-
756
-                $this->update_price(1);
757
-
758
-                $this->fk_propal = $this->id;
759
-                $this->rowid = $rowid;
760
-
761
-                $this->db->commit();
762
-                return $result;
763
-            }
764
-            else
765
-            {
766
-                $this->error=$this->line->error;
767
-
768
-                $this->db->rollback();
769
-                return -1;
770
-            }
771
-        }
772
-        else
773
-        {
774
-            dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
775
-            return -2;
776
-        }
777
-    }
778
-
779
-
780
-    /**
781
-     *  Delete detail line
782
-     *
783
-     *  @param		int		$lineid			Id of line to delete
784
-     *  @return     int         			>0 if OK, <0 if KO
785
-     */
786
-    function deleteline($lineid)
787
-    {
788
-        if ($this->statut == self::STATUS_DRAFT)
789
-        {
790
-            $line=new PropaleLigne($this->db);
791
-
792
-            // For triggers
793
-            $line->fetch($lineid);
794
-
795
-            if ($line->delete() > 0)
796
-            {
797
-                $this->update_price(1);
798
-
799
-                return 1;
800
-            }
801
-            else
802
-            {
803
-                return -1;
804
-            }
805
-        }
806
-        else
807
-        {
808
-            return -2;
809
-        }
810
-    }
811
-
812
-
813
-    /**
814
-     *  Create commercial proposal into database
815
-     * 	this->ref can be set or empty. If empty, we will use "(PROVid)"
816
-     *
817
-     * 	@param		User	$user		User that create
818
-     * 	@param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
819
-     *  @return     int     			<0 if KO, >=0 if OK
820
-     */
821
-    function create($user, $notrigger=0)
822
-    {
823
-        global $conf,$hookmanager;
824
-        $error=0;
825
-
826
-        $now=dol_now();
827
-
828
-        // Clean parameters
829
-        if (empty($this->date)) $this->date=$this->datep;
830
-        $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
831
-        if (empty($this->availability_id)) $this->availability_id=0;
832
-        if (empty($this->demand_reason_id)) $this->demand_reason_id=0;
747
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
748
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
749
+
750
+			$result=$this->line->update($notrigger);
751
+			if ($result > 0)
752
+			{
753
+				// Reorder if child line
754
+				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
755
+
756
+				$this->update_price(1);
757
+
758
+				$this->fk_propal = $this->id;
759
+				$this->rowid = $rowid;
760
+
761
+				$this->db->commit();
762
+				return $result;
763
+			}
764
+			else
765
+			{
766
+				$this->error=$this->line->error;
767
+
768
+				$this->db->rollback();
769
+				return -1;
770
+			}
771
+		}
772
+		else
773
+		{
774
+			dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
775
+			return -2;
776
+		}
777
+	}
778
+
779
+
780
+	/**
781
+	 *  Delete detail line
782
+	 *
783
+	 *  @param		int		$lineid			Id of line to delete
784
+	 *  @return     int         			>0 if OK, <0 if KO
785
+	 */
786
+	function deleteline($lineid)
787
+	{
788
+		if ($this->statut == self::STATUS_DRAFT)
789
+		{
790
+			$line=new PropaleLigne($this->db);
791
+
792
+			// For triggers
793
+			$line->fetch($lineid);
794
+
795
+			if ($line->delete() > 0)
796
+			{
797
+				$this->update_price(1);
798
+
799
+				return 1;
800
+			}
801
+			else
802
+			{
803
+				return -1;
804
+			}
805
+		}
806
+		else
807
+		{
808
+			return -2;
809
+		}
810
+	}
811
+
812
+
813
+	/**
814
+	 *  Create commercial proposal into database
815
+	 * 	this->ref can be set or empty. If empty, we will use "(PROVid)"
816
+	 *
817
+	 * 	@param		User	$user		User that create
818
+	 * 	@param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
819
+	 *  @return     int     			<0 if KO, >=0 if OK
820
+	 */
821
+	function create($user, $notrigger=0)
822
+	{
823
+		global $conf,$hookmanager;
824
+		$error=0;
825
+
826
+		$now=dol_now();
827
+
828
+		// Clean parameters
829
+		if (empty($this->date)) $this->date=$this->datep;
830
+		$this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
831
+		if (empty($this->availability_id)) $this->availability_id=0;
832
+		if (empty($this->demand_reason_id)) $this->demand_reason_id=0;
833 833
 
834 834
 		// Multicurrency
835 835
 		if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
@@ -840,18 +840,18 @@  discard block
 block discarded – undo
840 840
 			$this->multicurrency_tx = 1;
841 841
 		}
842 842
 
843
-        dol_syslog(get_class($this)."::create");
843
+		dol_syslog(get_class($this)."::create");
844 844
 
845
-        // Check parameters
846
-        $result=$this->fetch_thirdparty();
847
-        if ($result < 0)
848
-        {
849
-            $this->error="Failed to fetch company";
850
-            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
851
-            return -3;
852
-        }
845
+		// Check parameters
846
+		$result=$this->fetch_thirdparty();
847
+		if ($result < 0)
848
+		{
849
+			$this->error="Failed to fetch company";
850
+			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
851
+			return -3;
852
+		}
853 853
 
854
-        // Check parameters
854
+		// Check parameters
855 855
 		if (! empty($this->ref))	// We check that ref is not already used
856 856
 		{
857 857
 			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
@@ -864,111 +864,111 @@  discard block
 block discarded – undo
864 864
 			}
865 865
 		}
866 866
 
867
-        if (empty($this->date))
868
-        {
869
-            $this->error="Date of proposal is required";
870
-            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
871
-            return -4;
872
-        }
873
-
874
-
875
-        $this->db->begin();
876
-
877
-        // Insert into database
878
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal (";
879
-        $sql.= "fk_soc";
880
-        $sql.= ", price";
881
-        $sql.= ", remise";
882
-        $sql.= ", remise_percent";
883
-        $sql.= ", remise_absolue";
884
-        $sql.= ", tva";
885
-        $sql.= ", total";
886
-        $sql.= ", datep";
887
-        $sql.= ", datec";
888
-        $sql.= ", ref";
889
-        $sql.= ", fk_user_author";
890
-        $sql.= ", note_private";
891
-        $sql.= ", note_public";
892
-        $sql.= ", model_pdf";
893
-        $sql.= ", fin_validite";
894
-        $sql.= ", fk_cond_reglement";
895
-        $sql.= ", fk_mode_reglement";
896
-        $sql.= ", fk_account";
897
-        $sql.= ", ref_client";
898
-        $sql.= ", date_livraison";
899
-        $sql.= ", fk_shipping_method";
900
-        $sql.= ", fk_availability";
901
-        $sql.= ", fk_input_reason";
902
-        $sql.= ", fk_projet";
903
-        $sql.= ", fk_incoterms";
904
-        $sql.= ", location_incoterms";
905
-        $sql.= ", entity";
906
-        $sql.= ", fk_multicurrency";
907
-        $sql.= ", multicurrency_code";
908
-        $sql.= ", multicurrency_tx";
909
-        $sql.= ") ";
910
-        $sql.= " VALUES (";
911
-        $sql.= $this->socid;
912
-        $sql.= ", 0";
913
-        $sql.= ", ".$this->remise;
914
-        $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL');
915
-        $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL');
916
-        $sql.= ", 0";
917
-        $sql.= ", 0";
918
-        $sql.= ", '".$this->db->idate($this->date)."'";
919
-        $sql.= ", '".$this->db->idate($now)."'";
920
-        $sql.= ", '(PROV)'";
921
-        $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL");
922
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
923
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
924
-        $sql.= ", '".$this->db->escape($this->modelpdf)."'";
925
-        $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL");
926
-        $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
927
-        $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
928
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
929
-        $sql.= ", '".$this->db->escape($this->ref_client)."'";
930
-        $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL");
931
-        $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
932
-        $sql.= ", ".$this->availability_id;
933
-        $sql.= ", ".$this->demand_reason_id;
934
-        $sql.= ", ".($this->fk_project?$this->fk_project:"null");
935
-        $sql.= ", ".(int) $this->fk_incoterms;
936
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
937
-        $sql.= ", ".$conf->entity;
867
+		if (empty($this->date))
868
+		{
869
+			$this->error="Date of proposal is required";
870
+			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
871
+			return -4;
872
+		}
873
+
874
+
875
+		$this->db->begin();
876
+
877
+		// Insert into database
878
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."propal (";
879
+		$sql.= "fk_soc";
880
+		$sql.= ", price";
881
+		$sql.= ", remise";
882
+		$sql.= ", remise_percent";
883
+		$sql.= ", remise_absolue";
884
+		$sql.= ", tva";
885
+		$sql.= ", total";
886
+		$sql.= ", datep";
887
+		$sql.= ", datec";
888
+		$sql.= ", ref";
889
+		$sql.= ", fk_user_author";
890
+		$sql.= ", note_private";
891
+		$sql.= ", note_public";
892
+		$sql.= ", model_pdf";
893
+		$sql.= ", fin_validite";
894
+		$sql.= ", fk_cond_reglement";
895
+		$sql.= ", fk_mode_reglement";
896
+		$sql.= ", fk_account";
897
+		$sql.= ", ref_client";
898
+		$sql.= ", date_livraison";
899
+		$sql.= ", fk_shipping_method";
900
+		$sql.= ", fk_availability";
901
+		$sql.= ", fk_input_reason";
902
+		$sql.= ", fk_projet";
903
+		$sql.= ", fk_incoterms";
904
+		$sql.= ", location_incoterms";
905
+		$sql.= ", entity";
906
+		$sql.= ", fk_multicurrency";
907
+		$sql.= ", multicurrency_code";
908
+		$sql.= ", multicurrency_tx";
909
+		$sql.= ") ";
910
+		$sql.= " VALUES (";
911
+		$sql.= $this->socid;
912
+		$sql.= ", 0";
913
+		$sql.= ", ".$this->remise;
914
+		$sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL');
915
+		$sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL');
916
+		$sql.= ", 0";
917
+		$sql.= ", 0";
918
+		$sql.= ", '".$this->db->idate($this->date)."'";
919
+		$sql.= ", '".$this->db->idate($now)."'";
920
+		$sql.= ", '(PROV)'";
921
+		$sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL");
922
+		$sql.= ", '".$this->db->escape($this->note_private)."'";
923
+		$sql.= ", '".$this->db->escape($this->note_public)."'";
924
+		$sql.= ", '".$this->db->escape($this->modelpdf)."'";
925
+		$sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL");
926
+		$sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
927
+		$sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
928
+		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
929
+		$sql.= ", '".$this->db->escape($this->ref_client)."'";
930
+		$sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL");
931
+		$sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
932
+		$sql.= ", ".$this->availability_id;
933
+		$sql.= ", ".$this->demand_reason_id;
934
+		$sql.= ", ".($this->fk_project?$this->fk_project:"null");
935
+		$sql.= ", ".(int) $this->fk_incoterms;
936
+		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
937
+		$sql.= ", ".$conf->entity;
938 938
 		$sql.= ", ".(int) $this->fk_multicurrency;
939 939
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
940 940
 		$sql.= ", ".(double) $this->multicurrency_tx;
941
-        $sql.= ")";
941
+		$sql.= ")";
942 942
 
943
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
944
-        $resql=$this->db->query($sql);
945
-        if ($resql)
946
-        {
947
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal");
943
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
944
+		$resql=$this->db->query($sql);
945
+		if ($resql)
946
+		{
947
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal");
948 948
 
949
-            if ($this->id)
950
-            {
951
-                $this->ref='(PROV'.$this->id.')';
952
-                $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
949
+			if ($this->id)
950
+			{
951
+				$this->ref='(PROV'.$this->id.')';
952
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
953 953
 
954
-                dol_syslog(get_class($this)."::create", LOG_DEBUG);
955
-                $resql=$this->db->query($sql);
956
-                if (! $resql) $error++;
954
+				dol_syslog(get_class($this)."::create", LOG_DEBUG);
955
+				$resql=$this->db->query($sql);
956
+				if (! $resql) $error++;
957 957
 
958
-                /*
958
+				/*
959 959
                  *  Insertion du detail des produits dans la base
960 960
                 */
961
-                if (! $error)
962
-                {
963
-                    $fk_parent_line=0;
964
-                    $num=count($this->lines);
961
+				if (! $error)
962
+				{
963
+					$fk_parent_line=0;
964
+					$num=count($this->lines);
965 965
 
966
-                    for ($i=0;$i<$num;$i++)
967
-                    {
968
-                        // Reset fk_parent_line for line that are not child lines or special product
969
-                        if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
970
-                            $fk_parent_line = 0;
971
-                        }
966
+					for ($i=0;$i<$num;$i++)
967
+					{
968
+						// Reset fk_parent_line for line that are not child lines or special product
969
+						if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
970
+							$fk_parent_line = 0;
971
+						}
972 972
 
973 973
 						$result = $this->addline(
974 974
 							$this->lines[$i]->desc,
@@ -989,168 +989,168 @@  discard block
 block discarded – undo
989 989
 							$this->lines[$i]->fk_fournprice,
990 990
 							$this->lines[$i]->pa_ht,
991 991
 							$this->lines[$i]->label,
992
-                            $this->lines[$i]->date_start,
992
+							$this->lines[$i]->date_start,
993 993
 							$this->lines[$i]->date_end,
994 994
 							$this->lines[$i]->array_options,
995 995
 							$this->lines[$i]->fk_unit,
996
-                            $this->element,
997
-                            $this->lines[$i]->id
996
+							$this->element,
997
+							$this->lines[$i]->id
998 998
 						);
999 999
 
1000
-                        if ($result < 0)
1001
-                        {
1002
-                            $error++;
1003
-                            $this->error=$this->db->error;
1004
-                            dol_print_error($this->db);
1005
-                            break;
1006
-                        }
1007
-                        // Defined the new fk_parent_line
1008
-                        if ($result > 0 && $this->lines[$i]->product_type == 9) {
1009
-                            $fk_parent_line = $result;
1010
-                        }
1011
-                    }
1012
-                }
1013
-
1014
-                // Add linked object
1015
-                if (! $error && $this->origin && $this->origin_id)
1016
-                {
1017
-                    $ret = $this->add_object_linked();
1018
-                    if (! $ret)	dol_print_error($this->db);
1019
-                }
1000
+						if ($result < 0)
1001
+						{
1002
+							$error++;
1003
+							$this->error=$this->db->error;
1004
+							dol_print_error($this->db);
1005
+							break;
1006
+						}
1007
+						// Defined the new fk_parent_line
1008
+						if ($result > 0 && $this->lines[$i]->product_type == 9) {
1009
+							$fk_parent_line = $result;
1010
+						}
1011
+					}
1012
+				}
1020 1013
 
1021
-                // Set delivery address
1022
-                if (! $error && $this->fk_delivery_address)
1023
-                {
1024
-                    $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1025
-                    $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address;
1026
-                    $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'";
1027
-                    $sql.= " AND entity = ".$conf->entity;
1014
+				// Add linked object
1015
+				if (! $error && $this->origin && $this->origin_id)
1016
+				{
1017
+					$ret = $this->add_object_linked();
1018
+					if (! $ret)	dol_print_error($this->db);
1019
+				}
1020
+
1021
+				// Set delivery address
1022
+				if (! $error && $this->fk_delivery_address)
1023
+				{
1024
+					$sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1025
+					$sql.= " SET fk_delivery_address = ".$this->fk_delivery_address;
1026
+					$sql.= " WHERE ref = '".$this->db->escape($this->ref)."'";
1027
+					$sql.= " AND entity = ".$conf->entity;
1028 1028
 
1029
-                    $result=$this->db->query($sql);
1030
-                }
1029
+					$result=$this->db->query($sql);
1030
+				}
1031 1031
 
1032
-                if (! $error)
1033
-                {
1034
-                    // Mise a jour infos denormalisees
1035
-                    $resql=$this->update_price(1);
1036
-                    if ($resql)
1037
-                    {
1038
-                    	$action='update';
1039
-
1040
-                    	// Actions on extra fields (by external module or standard code)
1041
-                    	// TODO le hook fait double emploi avec le trigger !!
1042
-                    	$hookmanager->initHooks(array('propaldao'));
1043
-                    	$parameters=array('socid'=>$this->id);
1044
-                    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1045
-                    	if (empty($reshook))
1046
-                    	{
1047
-                    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1048
-                    		{
1049
-                    			$result=$this->insertExtraFields();
1050
-                    			if ($result < 0)
1051
-                    			{
1052
-                    				$error++;
1053
-                    			}
1054
-                    		}
1055
-                    	}
1056
-                    	else if ($reshook < 0) $error++;
1057
-
1058
-                        if (! $notrigger)
1059
-                        {
1060
-                            // Call trigger
1061
-                            $result=$this->call_trigger('PROPAL_CREATE',$user);
1062
-                            if ($result < 0) { $error++; }
1063
-                            // End call triggers
1064
-                        }
1065
-                    }
1066
-                    else
1032
+				if (! $error)
1033
+				{
1034
+					// Mise a jour infos denormalisees
1035
+					$resql=$this->update_price(1);
1036
+					if ($resql)
1067 1037
 					{
1068
-                        $this->error=$this->db->lasterror();
1069
-                        $error++;
1070
-                    }
1071
-                }
1072
-            }
1073
-            else
1074
-			{
1075
-                $this->error=$this->db->lasterror();
1076
-                $error++;
1077
-            }
1078
-
1079
-            if (! $error)
1080
-            {
1081
-                $this->db->commit();
1082
-                dol_syslog(get_class($this)."::create done id=".$this->id);
1083
-                return $this->id;
1084
-            }
1085
-            else
1086
-            {
1087
-                $this->db->rollback();
1088
-                return -2;
1089
-            }
1090
-        }
1091
-        else
1092
-        {
1093
-            $this->error=$this->db->lasterror();
1094
-            $this->db->rollback();
1095
-            return -1;
1096
-        }
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     *	Insert into DB a proposal object completely defined by its data members (ex, results from copy).
1102
-     *
1103
-     *	@param 		User	$user	User that create
1104
-     *	@return    	int				Id of the new object if ok, <0 if ko
1105
-     *	@see       	create
1106
-     */
1107
-    function create_from($user)
1108
-    {
1109
-    	// i love this function because $this->products is not used in create function...
1110
-        $this->products=$this->lines;
1111
-
1112
-        return $this->create($user);
1113
-    }
1114
-
1115
-    /**
1116
-     *		Load an object from its id and create a new one in database
1117
-     *
1118
-     *		@param		int				$socid			Id of thirdparty
1119
-     * 	 	@return		int								New id of clone
1120
-     */
1121
-    function createFromClone($socid=0)
1122
-    {
1123
-        global $user,$conf,$hookmanager;
1038
+						$action='update';
1039
+
1040
+						// Actions on extra fields (by external module or standard code)
1041
+						// TODO le hook fait double emploi avec le trigger !!
1042
+						$hookmanager->initHooks(array('propaldao'));
1043
+						$parameters=array('socid'=>$this->id);
1044
+						$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1045
+						if (empty($reshook))
1046
+						{
1047
+							if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1048
+							{
1049
+								$result=$this->insertExtraFields();
1050
+								if ($result < 0)
1051
+								{
1052
+									$error++;
1053
+								}
1054
+							}
1055
+						}
1056
+						else if ($reshook < 0) $error++;
1057
+
1058
+						if (! $notrigger)
1059
+						{
1060
+							// Call trigger
1061
+							$result=$this->call_trigger('PROPAL_CREATE',$user);
1062
+							if ($result < 0) { $error++; }
1063
+							// End call triggers
1064
+						}
1065
+					}
1066
+					else
1067
+					{
1068
+						$this->error=$this->db->lasterror();
1069
+						$error++;
1070
+					}
1071
+				}
1072
+			}
1073
+			else
1074
+			{
1075
+				$this->error=$this->db->lasterror();
1076
+				$error++;
1077
+			}
1078
+
1079
+			if (! $error)
1080
+			{
1081
+				$this->db->commit();
1082
+				dol_syslog(get_class($this)."::create done id=".$this->id);
1083
+				return $this->id;
1084
+			}
1085
+			else
1086
+			{
1087
+				$this->db->rollback();
1088
+				return -2;
1089
+			}
1090
+		}
1091
+		else
1092
+		{
1093
+			$this->error=$this->db->lasterror();
1094
+			$this->db->rollback();
1095
+			return -1;
1096
+		}
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 *	Insert into DB a proposal object completely defined by its data members (ex, results from copy).
1102
+	 *
1103
+	 *	@param 		User	$user	User that create
1104
+	 *	@return    	int				Id of the new object if ok, <0 if ko
1105
+	 *	@see       	create
1106
+	 */
1107
+	function create_from($user)
1108
+	{
1109
+		// i love this function because $this->products is not used in create function...
1110
+		$this->products=$this->lines;
1111
+
1112
+		return $this->create($user);
1113
+	}
1114
+
1115
+	/**
1116
+	 *		Load an object from its id and create a new one in database
1117
+	 *
1118
+	 *		@param		int				$socid			Id of thirdparty
1119
+	 * 	 	@return		int								New id of clone
1120
+	 */
1121
+	function createFromClone($socid=0)
1122
+	{
1123
+		global $user,$conf,$hookmanager;
1124 1124
 
1125 1125
 		dol_include_once('/projet/class/project.class.php');
1126 1126
 
1127
-        $this->context['createfromclone']='createfromclone';
1127
+		$this->context['createfromclone']='createfromclone';
1128 1128
 
1129
-        $error=0;
1130
-        $now=dol_now();
1129
+		$error=0;
1130
+		$now=dol_now();
1131 1131
 
1132
-        $this->db->begin();
1132
+		$this->db->begin();
1133 1133
 
1134 1134
 		// get extrafields so they will be clone
1135 1135
 		foreach($this->lines as $line)
1136 1136
 			$line->fetch_optionals($line->rowid);
1137 1137
 
1138
-        // Load dest object
1139
-        $clonedObj = clone $this;
1138
+		// Load dest object
1139
+		$clonedObj = clone $this;
1140 1140
 
1141
-        $objsoc=new Societe($this->db);
1141
+		$objsoc=new Societe($this->db);
1142 1142
 
1143
-        // Change socid if needed
1144
-        if (! empty($socid) && $socid != $clonedObj->socid)
1145
-        {
1146
-            if ($objsoc->fetch($socid) > 0)
1147
-            {
1148
-                $clonedObj->socid 				= $objsoc->id;
1149
-                $clonedObj->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1150
-                $clonedObj->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1151
-                $clonedObj->fk_delivery_address	= '';
1143
+		// Change socid if needed
1144
+		if (! empty($socid) && $socid != $clonedObj->socid)
1145
+		{
1146
+			if ($objsoc->fetch($socid) > 0)
1147
+			{
1148
+				$clonedObj->socid 				= $objsoc->id;
1149
+				$clonedObj->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1150
+				$clonedObj->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1151
+				$clonedObj->fk_delivery_address	= '';
1152 1152
 
1153
-                /*if (!empty($conf->projet->enabled))
1153
+				/*if (!empty($conf->projet->enabled))
1154 1154
                 {
1155 1155
                     $project = new Project($db);
1156 1156
     				if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
@@ -1160,189 +1160,189 @@  discard block
 block discarded – undo
1160 1160
     					$clonedObj->fk_project = '';
1161 1161
     				}
1162 1162
                 }*/
1163
-                $clonedObj->fk_project = '';    // A cloned proposal is set by default to no project.
1164
-            }
1165
-
1166
-            // reset ref_client
1167
-            $clonedObj->ref_client  = '';
1168
-
1169
-            // TODO Change product price if multi-prices
1170
-        }
1171
-        else
1172
-        {
1173
-            $objsoc->fetch($clonedObj->socid);
1174
-        }
1175
-
1176
-        $clonedObj->id=0;
1177
-        $clonedObj->ref='';
1178
-        $clonedObj->statut=self::STATUS_DRAFT;
1179
-
1180
-        // Clear fields
1181
-        $clonedObj->user_author	= $user->id;
1182
-        $clonedObj->user_valid	= '';
1183
-        $clonedObj->date		= $now;
1184
-        $clonedObj->datep		= $now;    // deprecated
1185
-        $clonedObj->fin_validite	= $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600);
1186
-        if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client	= '';
1187
-
1188
-        // Create clone
1189
-
1190
-        $result=$clonedObj->create($user);
1191
-        if ($result < 0) $error++;
1192
-        else
1193
-        {
1194
-			// copy internal contacts
1195
-    		if ($clonedObj->copy_linked_contact($this, 'internal') < 0)
1196
-            	$error++;
1163
+				$clonedObj->fk_project = '';    // A cloned proposal is set by default to no project.
1164
+			}
1197 1165
 
1198
-            // copy external contacts if same company
1199
-            elseif ($this->socid == $clonedObj->socid)
1200
-            {
1201
-		        if ($clonedObj->copy_linked_contact($this, 'external') < 0)
1202
-					$error++;
1203
-            }
1204
-        }
1205
-
1206
-        if (! $error)
1207
-        {
1208
-            // Hook of thirdparty module
1209
-            if (is_object($hookmanager))
1210
-            {
1211
-                $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj);
1212
-                $action='';
1213
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action);    // Note that $action and $object may have been modified by some hooks
1214
-                if ($reshook < 0) $error++;
1215
-            }
1216
-
1217
-            // Call trigger
1218
-            $result=$clonedObj->call_trigger('PROPAL_CLONE',$user);
1219
-            if ($result < 0) { $error++; }
1220
-            // End call triggers
1221
-        }
1222
-
1223
-        unset($this->context['createfromclone']);
1224
-
1225
-        // End
1226
-        if (! $error)
1227
-        {
1228
-            $this->db->commit();
1229
-            return $clonedObj->id;
1230
-        }
1231
-        else
1232
-        {
1233
-            $this->db->rollback();
1234
-            return -1;
1235
-        }
1236
-    }
1237
-
1238
-    /**
1239
-     *	Load a proposal from database and its ligne array
1240
-     *
1241
-     *	@param      int			$rowid		id of object to load
1242
-     *	@param		string		$ref		Ref of proposal
1243
-     *	@return     int         			>0 if OK, <0 if KO
1244
-     */
1245
-    function fetch($rowid,$ref='')
1246
-    {
1247
-
1248
-        $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
1249
-        $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
1250
-        $sql.= ", p.datec";
1251
-        $sql.= ", p.date_valid as datev";
1252
-        $sql.= ", p.datep as dp";
1253
-        $sql.= ", p.fin_validite as dfv";
1254
-        $sql.= ", p.date_livraison as date_livraison";
1255
-        $sql.= ", p.model_pdf, p.ref_client, p.extraparams";
1256
-        $sql.= ", p.note_private, p.note_public";
1257
-        $sql.= ", p.fk_projet, p.fk_statut";
1258
-        $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1259
-        $sql.= ", p.fk_delivery_address";
1260
-        $sql.= ", p.fk_availability";
1261
-        $sql.= ", p.fk_input_reason";
1262
-        $sql.= ", p.fk_cond_reglement";
1263
-        $sql.= ", p.fk_mode_reglement";
1264
-        $sql.= ', p.fk_account';
1265
-        $sql.= ", p.fk_shipping_method";
1266
-        $sql.= ", p.fk_incoterms, p.location_incoterms";
1267
-		$sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1268
-        $sql.= ", i.libelle as libelle_incoterms";
1269
-        $sql.= ", c.label as statut_label";
1270
-        $sql.= ", ca.code as availability_code, ca.label as availability";
1271
-        $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason";
1272
-        $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
1273
-        $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1274
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p";
1275
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')';
1276
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')';
1277
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1278
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1166
+			// reset ref_client
1167
+			$clonedObj->ref_client  = '';
1168
+
1169
+			// TODO Change product price if multi-prices
1170
+		}
1171
+		else
1172
+		{
1173
+			$objsoc->fetch($clonedObj->socid);
1174
+		}
1175
+
1176
+		$clonedObj->id=0;
1177
+		$clonedObj->ref='';
1178
+		$clonedObj->statut=self::STATUS_DRAFT;
1179
+
1180
+		// Clear fields
1181
+		$clonedObj->user_author	= $user->id;
1182
+		$clonedObj->user_valid	= '';
1183
+		$clonedObj->date		= $now;
1184
+		$clonedObj->datep		= $now;    // deprecated
1185
+		$clonedObj->fin_validite	= $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600);
1186
+		if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client	= '';
1187
+
1188
+		// Create clone
1189
+
1190
+		$result=$clonedObj->create($user);
1191
+		if ($result < 0) $error++;
1192
+		else
1193
+		{
1194
+			// copy internal contacts
1195
+			if ($clonedObj->copy_linked_contact($this, 'internal') < 0)
1196
+				$error++;
1197
+
1198
+			// copy external contacts if same company
1199
+			elseif ($this->socid == $clonedObj->socid)
1200
+			{
1201
+				if ($clonedObj->copy_linked_contact($this, 'external') < 0)
1202
+					$error++;
1203
+			}
1204
+		}
1205
+
1206
+		if (! $error)
1207
+		{
1208
+			// Hook of thirdparty module
1209
+			if (is_object($hookmanager))
1210
+			{
1211
+				$parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj);
1212
+				$action='';
1213
+				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action);    // Note that $action and $object may have been modified by some hooks
1214
+				if ($reshook < 0) $error++;
1215
+			}
1216
+
1217
+			// Call trigger
1218
+			$result=$clonedObj->call_trigger('PROPAL_CLONE',$user);
1219
+			if ($result < 0) { $error++; }
1220
+			// End call triggers
1221
+		}
1222
+
1223
+		unset($this->context['createfromclone']);
1224
+
1225
+		// End
1226
+		if (! $error)
1227
+		{
1228
+			$this->db->commit();
1229
+			return $clonedObj->id;
1230
+		}
1231
+		else
1232
+		{
1233
+			$this->db->rollback();
1234
+			return -1;
1235
+		}
1236
+	}
1237
+
1238
+	/**
1239
+	 *	Load a proposal from database and its ligne array
1240
+	 *
1241
+	 *	@param      int			$rowid		id of object to load
1242
+	 *	@param		string		$ref		Ref of proposal
1243
+	 *	@return     int         			>0 if OK, <0 if KO
1244
+	 */
1245
+	function fetch($rowid,$ref='')
1246
+	{
1247
+
1248
+		$sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
1249
+		$sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
1250
+		$sql.= ", p.datec";
1251
+		$sql.= ", p.date_valid as datev";
1252
+		$sql.= ", p.datep as dp";
1253
+		$sql.= ", p.fin_validite as dfv";
1254
+		$sql.= ", p.date_livraison as date_livraison";
1255
+		$sql.= ", p.model_pdf, p.ref_client, p.extraparams";
1256
+		$sql.= ", p.note_private, p.note_public";
1257
+		$sql.= ", p.fk_projet, p.fk_statut";
1258
+		$sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1259
+		$sql.= ", p.fk_delivery_address";
1260
+		$sql.= ", p.fk_availability";
1261
+		$sql.= ", p.fk_input_reason";
1262
+		$sql.= ", p.fk_cond_reglement";
1263
+		$sql.= ", p.fk_mode_reglement";
1264
+		$sql.= ', p.fk_account';
1265
+		$sql.= ", p.fk_shipping_method";
1266
+		$sql.= ", p.fk_incoterms, p.location_incoterms";
1267
+		$sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1268
+		$sql.= ", i.libelle as libelle_incoterms";
1269
+		$sql.= ", c.label as statut_label";
1270
+		$sql.= ", ca.code as availability_code, ca.label as availability";
1271
+		$sql.= ", dr.code as demand_reason_code, dr.label as demand_reason";
1272
+		$sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
1273
+		$sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1274
+		$sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p";
1275
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')';
1276
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')';
1277
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1278
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1279 1279
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1280
-        $sql.= " WHERE p.fk_statut = c.id";
1281
-        $sql.= " AND p.entity IN (".getEntity('propal').")";
1282
-        if ($ref) $sql.= " AND p.ref='".$ref."'";
1283
-        else $sql.= " AND p.rowid=".$rowid;
1284
-
1285
-        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1286
-        $resql=$this->db->query($sql);
1287
-        if ($resql)
1288
-        {
1289
-            if ($this->db->num_rows($resql))
1290
-            {
1291
-                $obj = $this->db->fetch_object($resql);
1292
-
1293
-                $this->id                   = $obj->rowid;
1294
-
1295
-                $this->ref                  = $obj->ref;
1296
-                $this->ref_client           = $obj->ref_client;
1297
-                $this->remise               = $obj->remise;
1298
-                $this->remise_percent       = $obj->remise_percent;
1299
-                $this->remise_absolue       = $obj->remise_absolue;
1300
-                $this->total                = $obj->total; // TODO deprecated
1301
-                $this->total_ht             = $obj->total_ht;
1302
-                $this->total_tva            = $obj->tva;
1303
-                $this->total_localtax1		= $obj->localtax1;
1304
-                $this->total_localtax2		= $obj->localtax2;
1305
-                $this->total_ttc            = $obj->total;
1306
-                $this->socid                = $obj->fk_soc;
1307
-                $this->fk_project           = $obj->fk_projet;
1308
-                $this->modelpdf             = $obj->model_pdf;
1309
-                $this->note                 = $obj->note_private; // TODO deprecated
1310
-                $this->note_private         = $obj->note_private;
1311
-                $this->note_public          = $obj->note_public;
1312
-                $this->statut               = (int) $obj->fk_statut;
1313
-                $this->statut_libelle       = $obj->statut_label;
1314
-
1315
-                $this->datec                = $this->db->jdate($obj->datec); // TODO deprecated
1316
-                $this->datev                = $this->db->jdate($obj->datev); // TODO deprecated
1317
-                $this->date_creation		= $this->db->jdate($obj->datec); //Creation date
1318
-                $this->date_validation		= $this->db->jdate($obj->datev); //Validation date
1319
-                $this->date                 = $this->db->jdate($obj->dp);	// Proposal date
1320
-                $this->datep                = $this->db->jdate($obj->dp);    // deprecated
1321
-                $this->fin_validite         = $this->db->jdate($obj->dfv);
1322
-                $this->date_livraison       = $this->db->jdate($obj->date_livraison);
1323
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1324
-                $this->availability_id      = $obj->fk_availability;
1325
-                $this->availability_code    = $obj->availability_code;
1326
-                $this->availability         = $obj->availability;
1327
-                $this->demand_reason_id     = $obj->fk_input_reason;
1328
-                $this->demand_reason_code   = $obj->demand_reason_code;
1329
-                $this->demand_reason        = $obj->demand_reason;
1330
-                $this->fk_address  			= $obj->fk_delivery_address;
1331
-
1332
-                $this->mode_reglement_id    = $obj->fk_mode_reglement;
1333
-                $this->mode_reglement_code  = $obj->mode_reglement_code;
1334
-                $this->mode_reglement       = $obj->mode_reglement;
1335
-                $this->fk_account           = ($obj->fk_account>0)?$obj->fk_account:null;
1336
-                $this->cond_reglement_id    = $obj->fk_cond_reglement;
1337
-                $this->cond_reglement_code  = $obj->cond_reglement_code;
1338
-                $this->cond_reglement       = $obj->cond_reglement;
1339
-                $this->cond_reglement_doc   = $obj->cond_reglement_libelle_doc;
1340
-
1341
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
1342
-
1343
-                $this->user_author_id = $obj->fk_user_author;
1344
-                $this->user_valid_id  = $obj->fk_user_valid;
1345
-                $this->user_close_id  = $obj->fk_user_cloture;
1280
+		$sql.= " WHERE p.fk_statut = c.id";
1281
+		$sql.= " AND p.entity IN (".getEntity('propal').")";
1282
+		if ($ref) $sql.= " AND p.ref='".$ref."'";
1283
+		else $sql.= " AND p.rowid=".$rowid;
1284
+
1285
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1286
+		$resql=$this->db->query($sql);
1287
+		if ($resql)
1288
+		{
1289
+			if ($this->db->num_rows($resql))
1290
+			{
1291
+				$obj = $this->db->fetch_object($resql);
1292
+
1293
+				$this->id                   = $obj->rowid;
1294
+
1295
+				$this->ref                  = $obj->ref;
1296
+				$this->ref_client           = $obj->ref_client;
1297
+				$this->remise               = $obj->remise;
1298
+				$this->remise_percent       = $obj->remise_percent;
1299
+				$this->remise_absolue       = $obj->remise_absolue;
1300
+				$this->total                = $obj->total; // TODO deprecated
1301
+				$this->total_ht             = $obj->total_ht;
1302
+				$this->total_tva            = $obj->tva;
1303
+				$this->total_localtax1		= $obj->localtax1;
1304
+				$this->total_localtax2		= $obj->localtax2;
1305
+				$this->total_ttc            = $obj->total;
1306
+				$this->socid                = $obj->fk_soc;
1307
+				$this->fk_project           = $obj->fk_projet;
1308
+				$this->modelpdf             = $obj->model_pdf;
1309
+				$this->note                 = $obj->note_private; // TODO deprecated
1310
+				$this->note_private         = $obj->note_private;
1311
+				$this->note_public          = $obj->note_public;
1312
+				$this->statut               = (int) $obj->fk_statut;
1313
+				$this->statut_libelle       = $obj->statut_label;
1314
+
1315
+				$this->datec                = $this->db->jdate($obj->datec); // TODO deprecated
1316
+				$this->datev                = $this->db->jdate($obj->datev); // TODO deprecated
1317
+				$this->date_creation		= $this->db->jdate($obj->datec); //Creation date
1318
+				$this->date_validation		= $this->db->jdate($obj->datev); //Validation date
1319
+				$this->date                 = $this->db->jdate($obj->dp);	// Proposal date
1320
+				$this->datep                = $this->db->jdate($obj->dp);    // deprecated
1321
+				$this->fin_validite         = $this->db->jdate($obj->dfv);
1322
+				$this->date_livraison       = $this->db->jdate($obj->date_livraison);
1323
+				$this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1324
+				$this->availability_id      = $obj->fk_availability;
1325
+				$this->availability_code    = $obj->availability_code;
1326
+				$this->availability         = $obj->availability;
1327
+				$this->demand_reason_id     = $obj->fk_input_reason;
1328
+				$this->demand_reason_code   = $obj->demand_reason_code;
1329
+				$this->demand_reason        = $obj->demand_reason;
1330
+				$this->fk_address  			= $obj->fk_delivery_address;
1331
+
1332
+				$this->mode_reglement_id    = $obj->fk_mode_reglement;
1333
+				$this->mode_reglement_code  = $obj->mode_reglement_code;
1334
+				$this->mode_reglement       = $obj->mode_reglement;
1335
+				$this->fk_account           = ($obj->fk_account>0)?$obj->fk_account:null;
1336
+				$this->cond_reglement_id    = $obj->fk_cond_reglement;
1337
+				$this->cond_reglement_code  = $obj->cond_reglement_code;
1338
+				$this->cond_reglement       = $obj->cond_reglement;
1339
+				$this->cond_reglement_doc   = $obj->cond_reglement_libelle_doc;
1340
+
1341
+				$this->extraparams			= (array) json_decode($obj->extraparams, true);
1342
+
1343
+				$this->user_author_id = $obj->fk_user_author;
1344
+				$this->user_valid_id  = $obj->fk_user_valid;
1345
+				$this->user_close_id  = $obj->fk_user_cloture;
1346 1346
 
1347 1347
 				//Incoterms
1348 1348
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -1357,43 +1357,43 @@  discard block
 block discarded – undo
1357 1357
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1358 1358
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1359 1359
 
1360
-                if ($obj->fk_statut == self::STATUS_DRAFT)
1361
-                {
1362
-                    $this->brouillon = 1;
1363
-                }
1360
+				if ($obj->fk_statut == self::STATUS_DRAFT)
1361
+				{
1362
+					$this->brouillon = 1;
1363
+				}
1364 1364
 
1365
-                // Retreive all extrafield for invoice
1366
-                // fetch optionals attributes and labels
1367
-                require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1368
-                $extrafields=new ExtraFields($this->db);
1369
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1370
-                $this->fetch_optionals($this->id,$extralabels);
1365
+				// Retreive all extrafield for invoice
1366
+				// fetch optionals attributes and labels
1367
+				require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1368
+				$extrafields=new ExtraFields($this->db);
1369
+				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1370
+				$this->fetch_optionals($this->id,$extralabels);
1371 1371
 
1372
-                $this->db->free($resql);
1372
+				$this->db->free($resql);
1373 1373
 
1374
-                $this->lines = array();
1374
+				$this->lines = array();
1375 1375
 
1376
-                /*
1376
+				/*
1377 1377
                  * Lines
1378 1378
                  */
1379
-                $result=$this->fetch_lines();
1380
-                if ($result < 0)
1381
-                {
1382
-                    return -3;
1383
-                }
1379
+				$result=$this->fetch_lines();
1380
+				if ($result < 0)
1381
+				{
1382
+					return -3;
1383
+				}
1384 1384
 
1385
-                return 1;
1386
-            }
1385
+				return 1;
1386
+			}
1387 1387
 
1388
-            $this->error="Record Not Found";
1389
-            return 0;
1390
-        }
1391
-        else
1392
-        {
1393
-            $this->error=$this->db->lasterror();
1394
-            return -1;
1395
-        }
1396
-    }
1388
+			$this->error="Record Not Found";
1389
+			return 0;
1390
+		}
1391
+		else
1392
+		{
1393
+			$this->error=$this->db->lasterror();
1394
+			return -1;
1395
+		}
1396
+	}
1397 1397
 
1398 1398
 	/**
1399 1399
 	 * Load array lines
@@ -1500,1941 +1500,1941 @@  discard block
 block discarded – undo
1500 1500
 		}
1501 1501
 		else
1502 1502
 		{
1503
-			$this->error=$this->db->lasterror();
1504
-			return -3;
1503
+			$this->error=$this->db->lasterror();
1504
+			return -3;
1505
+		}
1506
+	}
1507
+
1508
+	/**
1509
+	 *	Update value of extrafields on the proposal
1510
+	 *
1511
+	 *	@param      User	$user       Object user that modify
1512
+	 *	@return     int         		<0 if ko, >0 if ok
1513
+	 */
1514
+	function update_extrafields($user)
1515
+	{
1516
+		global $conf, $hookmanager;
1517
+
1518
+		$action='update';
1519
+		$error = 0;
1520
+
1521
+		// Actions on extra fields (by external module or standard code)
1522
+		// TODO le hook fait double emploi avec le trigger !!
1523
+		$hookmanager->initHooks(array('propaldao'));
1524
+		$parameters=array('id'=>$this->id);
1525
+		$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1526
+		if (empty($reshook))
1527
+		{
1528
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1529
+			{
1530
+				$result=$this->insertExtraFields();
1531
+				if ($result < 0)
1532
+				{
1533
+					$error++;
1534
+				}
1535
+			}
1536
+		}
1537
+		else if ($reshook < 0) $error++;
1538
+
1539
+		if (!$error)
1540
+		{
1541
+			return 1;
1542
+		}
1543
+		else
1544
+		{
1545
+			return -1;
1546
+		}
1547
+
1548
+	}
1549
+
1550
+	/**
1551
+	 *  Set status to validated
1552
+	 *
1553
+	 *  @param	User	$user       Object user that validate
1554
+	 *  @param	int		$notrigger	1=Does not execute triggers, 0=execute triggers
1555
+	 *  @return int         		<0 if KO, 0=Nothing done, >=0 if OK
1556
+	 */
1557
+	function valid($user, $notrigger=0)
1558
+	{
1559
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1560
+
1561
+		global $conf;
1562
+
1563
+		$error=0;
1564
+
1565
+		// Protection
1566
+		if ($this->statut == self::STATUS_VALIDATED)
1567
+		{
1568
+			dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
1569
+			return 0;
1570
+		}
1571
+
1572
+		if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer))
1573
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))))
1574
+		{
1575
+			$this->error='ErrorPermissionDenied';
1576
+			dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1577
+			return -1;
1578
+		}
1579
+
1580
+		$now=dol_now();
1581
+
1582
+		$this->db->begin();
1583
+
1584
+		// Numbering module definition
1585
+		$soc = new Societe($this->db);
1586
+		$soc->fetch($this->socid);
1587
+
1588
+		// Define new ref
1589
+		if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1590
+		{
1591
+			$num = $this->getNextNumRef($soc);
1592
+		}
1593
+		else
1594
+		{
1595
+			$num = $this->ref;
1596
+		}
1597
+		$this->newref = $num;
1598
+
1599
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1600
+		$sql.= " SET ref = '".$num."',";
1601
+		$sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
1602
+		$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1603
+
1604
+		dol_syslog(get_class($this)."::valid", LOG_DEBUG);
1605
+		$resql=$this->db->query($sql);
1606
+		if (! $resql)
1607
+		{
1608
+			dol_print_error($this->db);
1609
+			$error++;
1610
+		}
1611
+
1612
+		// Trigger calls
1613
+		if (! $error && ! $notrigger)
1614
+		{
1615
+			// Call trigger
1616
+			$result=$this->call_trigger('PROPAL_VALIDATE',$user);
1617
+			if ($result < 0) { $error++; }
1618
+			// End call triggers
1619
+		}
1620
+
1621
+		if (! $error)
1622
+		{
1623
+			$this->oldref = $this->ref;
1624
+
1625
+			// Rename directory if dir was a temporary ref
1626
+			if (preg_match('/^[\(]?PROV/i', $this->ref))
1627
+			{
1628
+				// Rename of propal directory ($this->ref = old ref, $num = new ref)
1629
+				// to  not lose the linked files
1630
+				$oldref = dol_sanitizeFileName($this->ref);
1631
+				$newref = dol_sanitizeFileName($num);
1632
+				$dirsource = $conf->propal->dir_output.'/'.$oldref;
1633
+				$dirdest = $conf->propal->dir_output.'/'.$newref;
1634
+
1635
+				if (file_exists($dirsource))
1636
+				{
1637
+					dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
1638
+					if (@rename($dirsource, $dirdest))
1639
+					{
1640
+						dol_syslog("Rename ok");
1641
+						// Rename docs starting with $oldref with $newref
1642
+						$listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1643
+						foreach($listoffiles as $fileentry)
1644
+						{
1645
+							$dirsource=$fileentry['name'];
1646
+							$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1647
+							$dirsource=$fileentry['path'].'/'.$dirsource;
1648
+							$dirdest=$fileentry['path'].'/'.$dirdest;
1649
+							@rename($dirsource, $dirdest);
1650
+						}
1651
+					}
1652
+				}
1653
+			}
1654
+
1655
+			$this->ref=$num;
1656
+			$this->brouillon=0;
1657
+			$this->statut = self::STATUS_VALIDATED;
1658
+			$this->user_valid_id=$user->id;
1659
+			$this->datev=$now;
1660
+
1661
+			$this->db->commit();
1662
+			return 1;
1663
+		}
1664
+		else
1665
+		{
1666
+			$this->db->rollback();
1667
+			return -1;
1668
+		}
1669
+	}
1670
+
1671
+
1672
+	/**
1673
+	 *  Define proposal date
1674
+	 *
1675
+	 *  @param  User		$user      	Object user that modify
1676
+	 *  @param  int			$date		Date
1677
+	 *  @param  int			$notrigger	1=Does not execute triggers, 0= execute triggers
1678
+	 *  @return	int         			<0 if KO, >0 if OK
1679
+	 */
1680
+	function set_date($user, $date, $notrigger=0)
1681
+	{
1682
+		if (empty($date))
1683
+		{
1684
+			$this->error='ErrorBadParameter';
1685
+			dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
1686
+			return -1;
1687
+		}
1688
+
1689
+		if (! empty($user->rights->propal->creer))
1690
+		{
1691
+			$error=0;
1692
+
1693
+			$this->db->begin();
1694
+
1695
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'";
1696
+			$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1697
+
1698
+			dol_syslog(__METHOD__, LOG_DEBUG);
1699
+			$resql=$this->db->query($sql);
1700
+			if (!$resql)
1701
+			{
1702
+				$this->errors[]=$this->db->error();
1703
+				$error++;
1704
+			}
1705
+
1706
+			if (! $error)
1707
+			{
1708
+				$this->oldcopy= clone $this;
1709
+				$this->date = $date;
1710
+				$this->datep = $date;    // deprecated
1711
+			}
1712
+
1713
+			if (! $notrigger && empty($error))
1714
+			{
1715
+				// Call trigger
1716
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
1717
+				if ($result < 0) $error++;
1718
+				// End call triggers
1719
+			}
1720
+
1721
+			if (! $error)
1722
+			{
1723
+				$this->db->commit();
1724
+				return 1;
1725
+			}
1726
+			else
1727
+			{
1728
+				foreach($this->errors as $errmsg)
1729
+				{
1730
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1731
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
1732
+				}
1733
+				$this->db->rollback();
1734
+				return -1*$error;
1735
+			}
1736
+		}
1737
+	}
1738
+
1739
+	/**
1740
+	 *	Define end validity date
1741
+	 *
1742
+	 *	@param		User	$user        		Object user that modify
1743
+	 *	@param      int		$date_fin_validite	End of validity date
1744
+	 *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1745
+	 *	@return     int         				<0 if KO, >0 if OK
1746
+	 */
1747
+	function set_echeance($user, $date_fin_validite, $notrigger=0)
1748
+	{
1749
+		if (! empty($user->rights->propal->creer))
1750
+		{
1751
+			$error=0;
1752
+
1753
+			$this->db->begin();
1754
+
1755
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null');
1756
+			$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1757
+
1758
+			dol_syslog(__METHOD__, LOG_DEBUG);
1759
+			$resql=$this->db->query($sql);
1760
+			if (!$resql)
1761
+			{
1762
+				$this->errors[]=$this->db->error();
1763
+				$error++;
1764
+			}
1765
+
1766
+
1767
+			if (! $error)
1768
+			{
1769
+				$this->oldcopy= clone $this;
1770
+				$this->fin_validite = $date_fin_validite;
1771
+			}
1772
+
1773
+			if (! $notrigger && empty($error))
1774
+			{
1775
+				// Call trigger
1776
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
1777
+				if ($result < 0) $error++;
1778
+				// End call triggers
1779
+			}
1780
+
1781
+			if (! $error)
1782
+			{
1783
+				$this->db->commit();
1784
+				return 1;
1785
+			}
1786
+			else
1787
+			{
1788
+				foreach($this->errors as $errmsg)
1789
+				{
1790
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1791
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
1792
+				}
1793
+				$this->db->rollback();
1794
+				return -1*$error;
1795
+			}
1796
+		}
1797
+	}
1798
+
1799
+	/**
1800
+	 *	Set delivery date
1801
+	 *
1802
+	 *	@param      User 	$user        		Object user that modify
1803
+	 *	@param      int		$date_livraison     Delivery date
1804
+	 *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1805
+	 *	@return     int         				<0 if ko, >0 if ok
1806
+	 */
1807
+	function set_date_livraison($user, $date_livraison, $notrigger=0)
1808
+	{
1809
+		if (! empty($user->rights->propal->creer))
1810
+		{
1811
+			$error=0;
1812
+
1813
+			$this->db->begin();
1814
+
1815
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1816
+			$sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null');
1817
+			$sql.= " WHERE rowid = ".$this->id;
1818
+
1819
+			dol_syslog(__METHOD__, LOG_DEBUG);
1820
+			$resql=$this->db->query($sql);
1821
+			if (!$resql)
1822
+			{
1823
+				$this->errors[]=$this->db->error();
1824
+				$error++;
1825
+			}
1826
+
1827
+			if (! $error)
1828
+			{
1829
+				$this->oldcopy= clone $this;
1830
+				$this->date_livraison = $date_livraison;
1831
+			}
1832
+
1833
+			if (! $notrigger && empty($error))
1834
+			{
1835
+				// Call trigger
1836
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
1837
+				if ($result < 0) $error++;
1838
+				// End call triggers
1839
+			}
1840
+
1841
+			if (! $error)
1842
+			{
1843
+				$this->db->commit();
1844
+				return 1;
1845
+			}
1846
+			else
1847
+			{
1848
+				foreach($this->errors as $errmsg)
1849
+				{
1850
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1851
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
1852
+				}
1853
+				$this->db->rollback();
1854
+				return -1*$error;
1855
+			}
1856
+		}
1857
+	}
1858
+
1859
+	/**
1860
+	 *  Set delivery
1861
+	 *
1862
+	 *  @param		User	$user		  	Object user that modify
1863
+	 *  @param      int		$id				Availability id
1864
+	 *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1865
+	 *  @return     int           			<0 if KO, >0 if OK
1866
+	 */
1867
+	function set_availability($user, $id, $notrigger=0)
1868
+	{
1869
+		if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1870
+		{
1871
+			$error=0;
1872
+
1873
+			$this->db->begin();
1874
+
1875
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1876
+			$sql.= " SET fk_availability = '".$id."'";
1877
+			$sql.= " WHERE rowid = ".$this->id;
1878
+
1879
+			dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
1880
+			$resql=$this->db->query($sql);
1881
+			if (!$resql)
1882
+			{
1883
+				$this->errors[]=$this->db->error();
1884
+				$error++;
1885
+			}
1886
+
1887
+			if (! $error)
1888
+			{
1889
+				$this->oldcopy= clone $this;
1890
+				$this->fk_availability = $id;
1891
+				$this->availability_id = $id;
1892
+			}
1893
+
1894
+			if (! $notrigger && empty($error))
1895
+			{
1896
+				// Call trigger
1897
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
1898
+				if ($result < 0) $error++;
1899
+				// End call triggers
1900
+			}
1901
+
1902
+			if (! $error)
1903
+			{
1904
+				$this->db->commit();
1905
+				return 1;
1906
+			}
1907
+			else
1908
+			{
1909
+				foreach($this->errors as $errmsg)
1910
+				{
1911
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1912
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
1913
+				}
1914
+				$this->db->rollback();
1915
+				return -1*$error;
1916
+			}
1917
+		}
1918
+		else
1919
+		{
1920
+			$error_str='Propal status do not meet requirement '.$this->statut;
1921
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
1922
+			$this->error=$error_str;
1923
+			$this->errors[]= $this->error;
1924
+			return -2;
1925
+		}
1926
+	}
1927
+
1928
+	/**
1929
+	 *  Set source of demand
1930
+	 *
1931
+	 *  @param		User	$user		Object user that modify
1932
+	 *  @param      int		$id			Input reason id
1933
+	 *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1934
+	 *  @return     int           		<0 if KO, >0 if OK
1935
+	 */
1936
+	function set_demand_reason($user, $id, $notrigger=0)
1937
+	{
1938
+		if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1939
+		{
1940
+			$error=0;
1941
+
1942
+			$this->db->begin();
1943
+
1944
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1945
+			$sql.= " SET fk_input_reason = ".$id;
1946
+			$sql.= " WHERE rowid = ".$this->id;
1947
+
1948
+			dol_syslog(__METHOD__, LOG_DEBUG);
1949
+			$resql=$this->db->query($sql);
1950
+			if (!$resql)
1951
+			{
1952
+				$this->errors[]=$this->db->error();
1953
+				$error++;
1954
+			}
1955
+
1956
+
1957
+			if (! $error)
1958
+			{
1959
+				$this->oldcopy= clone $this;
1960
+				$this->fk_input_reason = $id;
1961
+				$this->demand_reason_id = $id;
1962
+			}
1963
+
1964
+
1965
+			if (! $notrigger && empty($error))
1966
+			{
1967
+				// Call trigger
1968
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
1969
+				if ($result < 0) $error++;
1970
+				// End call triggers
1971
+			}
1972
+
1973
+			if (! $error)
1974
+			{
1975
+				$this->db->commit();
1976
+				return 1;
1977
+			}
1978
+			else
1979
+			{
1980
+				foreach($this->errors as $errmsg)
1981
+				{
1982
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1983
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
1984
+				}
1985
+				$this->db->rollback();
1986
+				return -1*$error;
1987
+			}
1988
+		}
1989
+		else
1990
+		{
1991
+			$error_str='Propal status do not meet requirement '.$this->statut;
1992
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
1993
+			$this->error=$error_str;
1994
+			$this->errors[]= $this->error;
1995
+			return -2;
1996
+		}
1997
+	}
1998
+
1999
+	/**
2000
+	 * Set customer reference number
2001
+	 *
2002
+	 *  @param      User	$user			Object user that modify
2003
+	 *  @param      string	$ref_client		Customer reference
2004
+	 *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2005
+	 *  @return     int						<0 if ko, >0 if ok
2006
+	 */
2007
+	function set_ref_client($user, $ref_client, $notrigger=0)
2008
+	{
2009
+		if (! empty($user->rights->propal->creer))
2010
+		{
2011
+			$error=0;
2012
+
2013
+			$this->db->begin();
2014
+
2015
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2016
+			$sql.= ' WHERE rowid = '.$this->id;
2017
+
2018
+			dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2019
+			$resql=$this->db->query($sql);
2020
+			if (!$resql)
2021
+			{
2022
+				$this->errors[]=$this->db->error();
2023
+				$error++;
2024
+			}
2025
+
2026
+			if (! $error)
2027
+			{
2028
+				$this->oldcopy= clone $this;
2029
+				$this->ref_client = $ref_client;
2030
+			}
2031
+
2032
+			if (! $notrigger && empty($error))
2033
+			{
2034
+				// Call trigger
2035
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
2036
+				if ($result < 0) $error++;
2037
+				// End call triggers
2038
+			}
2039
+
2040
+			if (! $error)
2041
+			{
2042
+				$this->db->commit();
2043
+				return 1;
2044
+			}
2045
+			else
2046
+			{
2047
+				foreach($this->errors as $errmsg)
2048
+				{
2049
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2050
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2051
+				}
2052
+				$this->db->rollback();
2053
+				return -1*$error;
2054
+			}
2055
+		}
2056
+		else
2057
+		{
2058
+			return -1;
2059
+		}
2060
+	}
2061
+
2062
+	/**
2063
+	 *	Set an overall discount on the proposal
2064
+	 *
2065
+	 *	@param      User	$user       Object user that modify
2066
+	 *	@param      double	$remise     Amount discount
2067
+	 *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2068
+	 *	@return     int         		<0 if ko, >0 if ok
2069
+	 */
2070
+	function set_remise_percent($user, $remise, $notrigger=0)
2071
+	{
2072
+		$remise=trim($remise)?trim($remise):0;
2073
+
2074
+		if (! empty($user->rights->propal->creer))
2075
+		{
2076
+			$remise = price2num($remise);
2077
+
2078
+			$error=0;
2079
+
2080
+			$this->db->begin();
2081
+
2082
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise;
2083
+			$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2084
+
2085
+			dol_syslog(__METHOD__, LOG_DEBUG);
2086
+			$resql=$this->db->query($sql);
2087
+			if (!$resql)
2088
+			{
2089
+				$this->errors[]=$this->db->error();
2090
+				$error++;
2091
+			}
2092
+
2093
+			if (! $error)
2094
+			{
2095
+				$this->oldcopy= clone $this;
2096
+				$this->remise_percent = $remise;
2097
+				$this->update_price(1);
2098
+			}
2099
+
2100
+			if (! $notrigger && empty($error))
2101
+			{
2102
+				// Call trigger
2103
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
2104
+				if ($result < 0) $error++;
2105
+				// End call triggers
2106
+			}
2107
+
2108
+			if (! $error)
2109
+			{
2110
+				$this->db->commit();
2111
+				return 1;
2112
+			}
2113
+			else
2114
+			{
2115
+				foreach($this->errors as $errmsg)
2116
+				{
2117
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2118
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2119
+				}
2120
+				$this->db->rollback();
2121
+				return -1*$error;
2122
+			}
2123
+		}
2124
+	}
2125
+
2126
+
2127
+	/**
2128
+	 *	Set an absolute overall discount on the proposal
2129
+	 *
2130
+	 *	@param      User	$user       Object user that modify
2131
+	 *	@param      double	$remise     Amount discount
2132
+	 *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2133
+	 *	@return     int         		<0 if ko, >0 if ok
2134
+	 */
2135
+	function set_remise_absolue($user, $remise, $notrigger=0)
2136
+	{
2137
+		$remise=trim($remise)?trim($remise):0;
2138
+
2139
+		if (! empty($user->rights->propal->creer))
2140
+		{
2141
+			$remise = price2num($remise);
2142
+
2143
+			$error=0;
2144
+
2145
+			$this->db->begin();
2146
+
2147
+			$sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
2148
+			$sql.= " SET remise_absolue = ".$remise;
2149
+			$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2150
+
2151
+			dol_syslog(__METHOD__, LOG_DEBUG);
2152
+			$resql=$this->db->query($sql);
2153
+			if (!$resql)
2154
+			{
2155
+				$this->errors[]=$this->db->error();
2156
+				$error++;
2157
+			}
2158
+
2159
+			if (! $error)
2160
+			{
2161
+				$this->oldcopy= clone $this;
2162
+				$this->remise_absolue = $remise;
2163
+				$this->update_price(1);
2164
+			}
2165
+
2166
+			if (! $notrigger && empty($error))
2167
+			{
2168
+				// Call trigger
2169
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
2170
+				if ($result < 0) $error++;
2171
+				// End call triggers
2172
+			}
2173
+
2174
+			if (! $error)
2175
+			{
2176
+				$this->db->commit();
2177
+				return 1;
2178
+			}
2179
+			else
2180
+			{
2181
+				foreach($this->errors as $errmsg)
2182
+				{
2183
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2184
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2185
+				}
2186
+				$this->db->rollback();
2187
+				return -1*$error;
2188
+			}
2189
+		}
2190
+	}
2191
+
2192
+
2193
+
2194
+	/**
2195
+	 *	Reopen the commercial proposal
2196
+	 *
2197
+	 *	@param      User	$user		Object user that close
2198
+	 *	@param      int		$statut		Statut
2199
+	 *	@param      string	$note		Comment
2200
+	 *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2201
+	 *	@return     int         		<0 if KO, >0 if OK
2202
+	 */
2203
+	function reopen($user, $statut, $note='', $notrigger=0)
2204
+	{
2205
+
2206
+		$this->statut = $statut;
2207
+		$error=0;
2208
+
2209
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2210
+		$sql.= " SET fk_statut = ".$this->statut.",";
2211
+		if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',";
2212
+		$sql.= " date_cloture=NULL, fk_user_cloture=NULL";
2213
+		$sql.= " WHERE rowid = ".$this->id;
2214
+
2215
+		$this->db->begin();
2216
+
2217
+		dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2218
+		$resql = $this->db->query($sql);
2219
+		if (! $resql) {
2220
+			$error++; $this->errors[]="Error ".$this->db->lasterror();
2221
+		}
2222
+		if (! $error)
2223
+		{
2224
+			if (! $notrigger)
2225
+			{
2226
+				// Call trigger
2227
+				$result=$this->call_trigger('PROPAL_REOPEN',$user);
2228
+				if ($result < 0) { $error++; }
2229
+				// End call triggers
2230
+			}
2231
+		}
2232
+
2233
+		// Commit or rollback
2234
+		if ($error)
2235
+		{
2236
+			if (!empty($this->errors))
2237
+			{
2238
+				foreach($this->errors as $errmsg)
2239
+				{
2240
+					dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2241
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2242
+				}
2243
+			}
2244
+			$this->db->rollback();
2245
+			return -1*$error;
2246
+		}
2247
+		else
2248
+		{
2249
+			$this->db->commit();
2250
+			return 1;
2251
+		}
2252
+	}
2253
+
2254
+
2255
+	/**
2256
+	 *	Close the commercial proposal
2257
+	 *
2258
+	 *	@param      User	$user		Object user that close
2259
+	 *	@param      int		$statut		Statut
2260
+	 *	@param      string	$note		Comment
2261
+	 *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2262
+	 *	@return     int         		<0 if KO, >0 if OK
2263
+	 */
2264
+	function cloture($user, $statut, $note, $notrigger=0)
2265
+	{
2266
+		global $langs,$conf;
2267
+
2268
+		$error=0;
2269
+		$now=dol_now();
2270
+
2271
+		$this->db->begin();
2272
+
2273
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2274
+		$sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
2275
+		$sql.= " WHERE rowid = ".$this->id;
2276
+
2277
+		$resql=$this->db->query($sql);
2278
+		if ($resql)
2279
+		{
2280
+			$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf;
2281
+			$trigger_name='PROPAL_CLOSE_REFUSED';
2282
+
2283
+			if ($statut == self::STATUS_SIGNED)
2284
+			{
2285
+				$trigger_name='PROPAL_CLOSE_SIGNED';
2286
+				$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf;
2287
+
2288
+				// The connected company is classified as a client
2289
+				$soc=new Societe($this->db);
2290
+				$soc->id = $this->socid;
2291
+				$result=$soc->set_as_client();
2292
+
2293
+				if ($result < 0)
2294
+				{
2295
+					$this->error=$this->db->lasterror();
2296
+					$this->db->rollback();
2297
+					return -2;
2298
+				}
2299
+			}
2300
+			if ($statut == self::STATUS_BILLED)
2301
+			{
2302
+				$trigger_name='PROPAL_CLASSIFY_BILLED';
2303
+			}
2304
+
2305
+			if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
2306
+			{
2307
+			 	// Define output language
2308
+			  	$outputlangs = $langs;
2309
+			   	if (! empty($conf->global->MAIN_MULTILANGS))
2310
+			   	{
2311
+			   		$outputlangs = new Translate("",$conf);
2312
+			   		$newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang);
2313
+			   		$outputlangs->setDefaultLang($newlang);
2314
+			   	}
2315
+			   	//$ret=$object->fetch($id);    // Reload to get new records
2316
+				   $this->generateDocument($modelpdf, $outputlangs);
2317
+			}
2318
+
2319
+			if (! $error)
2320
+			{
2321
+				$this->oldcopy= clone $this;
2322
+				$this->statut = $statut;
2323
+				$this->date_cloture = $now;
2324
+				$this->note_private = $note;
2325
+			}
2326
+
2327
+			if (! $notrigger && empty($error))
2328
+			{
2329
+				// Call trigger
2330
+				$result=$this->call_trigger($trigger_name,$user);
2331
+				if ($result < 0) { $error++; }
2332
+				// End call triggers
2333
+			}
2334
+
2335
+			if ( ! $error )
2336
+			{
2337
+				$this->db->commit();
2338
+				return 1;
2339
+			}
2340
+			else
2341
+			{
2342
+				$this->db->rollback();
2343
+				return -1;
2344
+			}
2345
+		}
2346
+		else
2347
+		{
2348
+			$this->error=$this->db->lasterror();
2349
+			$this->db->rollback();
2350
+			return -1;
2351
+		}
2352
+	}
2353
+
2354
+	/**
2355
+	 *	Class invoiced the Propal
2356
+	 *
2357
+	 *	@param  	User	$user    	Object user
2358
+	 *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2359
+	 *	@return     int     			<0 si ko, >0 si ok
2360
+	 */
2361
+	function classifyBilled(User $user, $notrigger=0)
2362
+	{
2363
+		$error=0;
2364
+
2365
+		$this->db->begin();
2366
+
2367
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED;
2368
+		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2369
+
2370
+		dol_syslog(__METHOD__, LOG_DEBUG);
2371
+		$resql=$this->db->query($sql);
2372
+		if (!$resql)
2373
+		{
2374
+			$this->errors[]=$this->db->error();
2375
+			$error++;
2376
+		}
2377
+
2378
+		if (! $error)
2379
+		{
2380
+			$this->oldcopy= clone $this;
2381
+			$this->statut=self::STATUS_BILLED;
2382
+		}
2383
+
2384
+		if (! $notrigger && empty($error))
2385
+		{
2386
+			// Call trigger
2387
+			$result=$this->call_trigger('PROPAL_MODIFY',$user);
2388
+			if ($result < 0) $error++;
2389
+			// End call triggers
2390
+		}
2391
+
2392
+		if (! $error)
2393
+		{
2394
+			$this->db->commit();
2395
+			return 1;
2396
+		}
2397
+		else
2398
+		{
2399
+			foreach($this->errors as $errmsg)
2400
+			{
2401
+				dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2402
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
2403
+			}
2404
+			$this->db->rollback();
2405
+			return -1*$error;
2406
+		}
2407
+	}
2408
+
2409
+	/**
2410
+	 *	Class invoiced the Propal
2411
+	 *
2412
+	 *	@return     int     	<0 si ko, >0 si ok
2413
+	 *  @deprecated
2414
+	 *  @see classifyBilled()
2415
+	 */
2416
+	function classer_facturee()
2417
+	{
2418
+		global $user;
2419
+		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
2420
+
2421
+		return $this->classifyBilled($user);
2422
+	}
2423
+
2424
+	/**
2425
+	 *	Set draft status
2426
+	 *
2427
+	 *	@param		User	$user		Object user that modify
2428
+	 *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2429
+	 *	@return		int					<0 if KO, >0 if OK
2430
+	 */
2431
+	function set_draft($user, $notrigger=0)
2432
+	{
2433
+		$error=0;
2434
+
2435
+		$this->db->begin();
2436
+
2437
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT;
2438
+		$sql.= " WHERE rowid = ".$this->id;
2439
+
2440
+		dol_syslog(__METHOD__, LOG_DEBUG);
2441
+		$resql=$this->db->query($sql);
2442
+		if (!$resql)
2443
+		{
2444
+			$this->errors[]=$this->db->error();
2445
+			$error++;
2446
+		}
2447
+
2448
+		if (! $error)
2449
+		{
2450
+			$this->oldcopy= clone $this;
2451
+			$this->statut = self::STATUS_DRAFT;
2452
+			$this->brouillon = 1;
2453
+		}
2454
+
2455
+		if (! $notrigger && empty($error))
2456
+		{
2457
+			// Call trigger
2458
+			$result=$this->call_trigger('PROPAL_MODIFY',$user);
2459
+			if ($result < 0) $error++;
2460
+			// End call triggers
2461
+		}
2462
+
2463
+		if (! $error)
2464
+		{
2465
+			$this->db->commit();
2466
+			return 1;
2467
+		}
2468
+		else
2469
+		{
2470
+			foreach($this->errors as $errmsg)
2471
+			{
2472
+				dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2473
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
2474
+			}
2475
+			$this->db->rollback();
2476
+			return -1*$error;
2477
+		}
2478
+	}
2479
+
2480
+
2481
+	/**
2482
+	 *    Return list of proposal (eventually filtered on user) into an array
2483
+	 *
2484
+	 *    @param	int		$shortlist			0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
2485
+	 *    @param	int		$draft				0=not draft, 1=draft
2486
+	 *    @param	int		$notcurrentuser		0=all user, 1=not current user
2487
+	 *    @param    int		$socid				Id third pary
2488
+	 *    @param    int		$limit				For pagination
2489
+	 *    @param    int		$offset				For pagination
2490
+	 *    @param    string	$sortfield			Sort criteria
2491
+	 *    @param    string	$sortorder			Sort order
2492
+	 *    @return	int		       				-1 if KO, array with result if OK
2493
+	 */
2494
+	function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC')
2495
+	{
2496
+		global $user;
2497
+
2498
+		$ga = array();
2499
+
2500
+		$sql = "SELECT s.rowid, s.nom as name, s.client,";
2501
+		$sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2502
+		$sql.= " p.datep as dp, p.fin_validite as datelimite";
2503
+		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2504
+		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2505
+		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2506
+		$sql.= " WHERE p.entity IN (".getEntity('propal').")";
2507
+		$sql.= " AND p.fk_soc = s.rowid";
2508
+		$sql.= " AND p.fk_statut = c.id";
2509
+		if (! $user->rights->societe->client->voir && ! $socid) //restriction
2510
+		{
2511
+			$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2512
+		}
2513
+		if ($socid) $sql.= " AND s.rowid = ".$socid;
2514
+		if ($draft)	$sql.= " AND p.fk_statut = ".self::STATUS_DRAFT;
2515
+		if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id;
2516
+		$sql.= $this->db->order($sortfield,$sortorder);
2517
+		$sql.= $this->db->plimit($limit,$offset);
2518
+
2519
+		$result=$this->db->query($sql);
2520
+		if ($result)
2521
+		{
2522
+			$num = $this->db->num_rows($result);
2523
+			if ($num)
2524
+			{
2525
+				$i = 0;
2526
+				while ($i < $num)
2527
+				{
2528
+					$obj = $this->db->fetch_object($result);
2529
+
2530
+					if ($shortlist == 1)
2531
+					{
2532
+						$ga[$obj->propalid] = $obj->ref;
2533
+					}
2534
+					else if ($shortlist == 2)
2535
+					{
2536
+						$ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
2537
+					}
2538
+					else
2539
+					{
2540
+						$ga[$i]['id']	= $obj->propalid;
2541
+						$ga[$i]['ref'] 	= $obj->ref;
2542
+						$ga[$i]['name'] = $obj->name;
2543
+					}
2544
+
2545
+					$i++;
2546
+				}
2547
+			}
2548
+			return $ga;
2549
+		}
2550
+		else
2551
+		{
2552
+			dol_print_error($this->db);
2553
+			return -1;
2554
+		}
2555
+	}
2556
+
2557
+	/**
2558
+	 *  Returns an array with the numbers of related invoices
2559
+	 *
2560
+	 *	@return	array		Array of invoices
2561
+	 */
2562
+	function getInvoiceArrayList()
2563
+	{
2564
+		return $this->InvoiceArrayList($this->id);
2565
+	}
2566
+
2567
+	/**
2568
+	 *  Returns an array with id and ref of related invoices
2569
+	 *
2570
+	 *	@param		int		$id			Id propal
2571
+	 *	@return		array				Array of invoices id
2572
+	 */
2573
+	function InvoiceArrayList($id)
2574
+	{
2575
+		$ga = array();
2576
+		$linkedInvoices = array();
2577
+
2578
+		$this->fetchObjectLinked($id,$this->element);
2579
+		foreach($this->linkedObjectsIds as $objecttype => $objectid)
2580
+		{
2581
+			// Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n
2582
+			// On parcourt donc une liste d'objets en tant qu'objet unique
2583
+			foreach($objectid as $key => $object)
2584
+			{
2585
+				// Cas des factures liees directement
2586
+				if ($objecttype == 'facture')
2587
+				{
2588
+					$linkedInvoices[] = $object;
2589
+				}
2590
+				// Cas des factures liees par un autre objet (ex: commande)
2591
+				else
2592
+				{
2593
+					$this->fetchObjectLinked($object,$objecttype);
2594
+					foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid)
2595
+					{
2596
+						foreach($subobjectid as $subkey => $subobject)
2597
+						{
2598
+							if ($subobjecttype == 'facture')
2599
+							{
2600
+								$linkedInvoices[] = $subobject;
2601
+							}
2602
+						}
2603
+					}
2604
+				}
2605
+			}
2606
+		}
2607
+
2608
+		if (count($linkedInvoices) > 0)
2609
+		{
2610
+			$sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye";
2611
+			$sql.= " FROM ".MAIN_DB_PREFIX."facture";
2612
+			$sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")";
2613
+
2614
+			dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
2615
+			$resql=$this->db->query($sql);
2616
+
2617
+			if ($resql)
2618
+			{
2619
+				$tab_sqlobj=array();
2620
+				$nump = $this->db->num_rows($resql);
2621
+				for ($i = 0;$i < $nump;$i++)
2622
+				{
2623
+					$sqlobj = $this->db->fetch_object($resql);
2624
+					$tab_sqlobj[] = $sqlobj;
2625
+				}
2626
+				$this->db->free($resql);
2627
+
2628
+				$nump = count($tab_sqlobj);
2629
+
2630
+				if ($nump)
2631
+				{
2632
+					$i = 0;
2633
+					while ($i < $nump)
2634
+					{
2635
+						$obj = array_shift($tab_sqlobj);
2636
+
2637
+						$ga[$i] = $obj;
2638
+
2639
+						$i++;
2640
+					}
2641
+				}
2642
+				return $ga;
2643
+			}
2644
+			else
2645
+			{
2646
+				return -1;
2647
+			}
2648
+		}
2649
+		else return $ga;
2650
+	}
2651
+
2652
+	/**
2653
+	 *	Delete proposal
2654
+	 *
2655
+	 *	@param	User	$user        	Object user that delete
2656
+	 *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2657
+	 *	@return	int						1 if ok, otherwise if error
2658
+	 */
2659
+	function delete($user, $notrigger=0)
2660
+	{
2661
+		global $conf;
2662
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2663
+
2664
+		$error=0;
2665
+
2666
+		$this->db->begin();
2667
+
2668
+		if (! $notrigger)
2669
+		{
2670
+			// Call trigger
2671
+			$result=$this->call_trigger('PROPAL_DELETE',$user);
2672
+			if ($result < 0) { $error++; }
2673
+			// End call triggers
2674
+		}
2675
+
2676
+		if (! $error)
2677
+		{
2678
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id;
2679
+			if ($this->db->query($sql))
2680
+			{
2681
+				$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id;
2682
+				if ($this->db->query($sql))
2683
+				{
2684
+					// Delete linked object
2685
+					$res = $this->deleteObjectLinked();
2686
+					if ($res < 0) $error++;
2687
+
2688
+					// Delete linked contacts
2689
+					$res = $this->delete_linked_contact();
2690
+					if ($res < 0) $error++;
2691
+
2692
+					if (! $error)
2693
+					{
2694
+						// We remove directory
2695
+						$ref = dol_sanitizeFileName($this->ref);
2696
+						if ($conf->propal->dir_output && !empty($this->ref))
2697
+						{
2698
+							$dir = $conf->propal->dir_output . "/" . $ref ;
2699
+							$file = $dir . "/" . $ref . ".pdf";
2700
+							if (file_exists($file))
2701
+							{
2702
+								dol_delete_preview($this);
2703
+
2704
+								if (! dol_delete_file($file,0,0,0,$this)) // For triggers
2705
+								{
2706
+									$this->error='ErrorFailToDeleteFile';
2707
+									$this->errors=array('ErrorFailToDeleteFile');
2708
+									$this->db->rollback();
2709
+									return 0;
2710
+								}
2711
+							}
2712
+							if (file_exists($dir))
2713
+							{
2714
+								$res=@dol_delete_dir_recursive($dir);
2715
+								if (! $res)
2716
+								{
2717
+									$this->error='ErrorFailToDeleteDir';
2718
+									$this->errors=array('ErrorFailToDeleteDir');
2719
+									$this->db->rollback();
2720
+									return 0;
2721
+								}
2722
+							}
2723
+						}
2724
+					}
2725
+
2726
+					// Removed extrafields
2727
+					if (! $error)
2728
+					{
2729
+						if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2730
+						{
2731
+							$result=$this->deleteExtraFields();
2732
+							if ($result < 0)
2733
+							{
2734
+								$error++;
2735
+								$errorflag=-4;
2736
+								dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
2737
+							}
2738
+						}
2739
+					}
2740
+
2741
+					if (! $error)
2742
+					{
2743
+						dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
2744
+						$this->db->commit();
2745
+						return 1;
2746
+					}
2747
+					else
2748
+					{
2749
+						$this->error=$this->db->lasterror();
2750
+						$this->db->rollback();
2751
+						return 0;
2752
+					}
2753
+				}
2754
+				else
2755
+				{
2756
+					$this->error=$this->db->lasterror();
2757
+					$this->db->rollback();
2758
+					return -3;
2759
+				}
2760
+			}
2761
+			else
2762
+			{
2763
+				$this->error=$this->db->lasterror();
2764
+				$this->db->rollback();
2765
+				return -2;
2766
+			}
2767
+		}
2768
+		else
2769
+		{
2770
+			$this->db->rollback();
2771
+			return -1;
2772
+		}
2773
+	}
2774
+
2775
+	/**
2776
+	 *  Change the delivery time
2777
+	 *
2778
+	 *  @param	int	$availability_id	Id of new delivery time
2779
+	 * 	@param	int	$notrigger			1=Does not execute triggers, 0= execute triggers
2780
+	 *  @return int                  	>0 if OK, <0 if KO
2781
+	 *  @deprecated  use set_availability
2782
+	 */
2783
+	function availability($availability_id, $notrigger=0)
2784
+	{
2785
+		global $user;
2786
+
2787
+		if ($this->statut >= self::STATUS_DRAFT)
2788
+		{
2789
+			$error=0;
2790
+
2791
+			$this->db->begin();
2792
+
2793
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
2794
+			$sql .= ' SET fk_availability = '.$availability_id;
2795
+			$sql .= ' WHERE rowid='.$this->id;
2796
+
2797
+			dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
2798
+			$resql=$this->db->query($sql);
2799
+			if (!$resql)
2800
+			{
2801
+				$this->errors[]=$this->db->error();
2802
+				$error++;
2803
+			}
2804
+
2805
+			if (! $error)
2806
+			{
2807
+				$this->oldcopy= clone $this;
2808
+				$this->availability_id = $availability_id;
2809
+			}
2810
+
2811
+			if (! $notrigger && empty($error))
2812
+			{
2813
+				// Call trigger
2814
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
2815
+				if ($result < 0) $error++;
2816
+				// End call triggers
2817
+			}
2818
+
2819
+			if (! $error)
2820
+			{
2821
+				$this->db->commit();
2822
+				return 1;
2823
+			}
2824
+			else
2825
+			{
2826
+				foreach($this->errors as $errmsg)
2827
+				{
2828
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2829
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2830
+				}
2831
+				$this->db->rollback();
2832
+				return -1*$error;
2833
+			}
2834
+		}
2835
+		else
2836
+		{
2837
+			$error_str='Propal status do not meet requirement '.$this->statut;
2838
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
2839
+			$this->error=$error_str;
2840
+			$this->errors[]= $this->error;
2841
+			return -2;
2842
+		}
2843
+	}
2844
+
2845
+	/**
2846
+	 *	Change source demand
2847
+	 *
2848
+	 *	@param	int $demand_reason_id 	Id of new source demand
2849
+	 * 	@param	int	$notrigger			1=Does not execute triggers, 0= execute triggers
2850
+	 *	@return int						>0 si ok, <0 si ko
2851
+	 *	@deprecated use set_demand_reason
2852
+	 */
2853
+	function demand_reason($demand_reason_id, $notrigger=0)
2854
+	{
2855
+		if ($this->statut >= self::STATUS_DRAFT)
2856
+		{
2857
+			$error=0;
2858
+
2859
+			$this->db->begin();
2860
+
2861
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
2862
+			$sql .= ' SET fk_input_reason = '.$demand_reason_id;
2863
+			$sql .= ' WHERE rowid='.$this->id;
2864
+
2865
+			dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
2866
+			$resql=$this->db->query($sql);
2867
+			if (!$resql)
2868
+			{
2869
+				$this->errors[]=$this->db->error();
2870
+				$error++;
2871
+			}
2872
+
2873
+			if (! $error)
2874
+			{
2875
+				$this->oldcopy= clone $this;
2876
+				$this->demand_reason_id = $demand_reason_id;
2877
+			}
2878
+
2879
+			if (! $notrigger && empty($error))
2880
+			{
2881
+				// Call trigger
2882
+				$result=$this->call_trigger('PROPAL_MODIFY',$user);
2883
+				if ($result < 0) $error++;
2884
+				// End call triggers
2885
+			}
2886
+
2887
+			if (! $error)
2888
+			{
2889
+				$this->db->commit();
2890
+				return 1;
2891
+			}
2892
+			else
2893
+			{
2894
+				foreach($this->errors as $errmsg)
2895
+				{
2896
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2897
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2898
+				}
2899
+				$this->db->rollback();
2900
+				return -1*$error;
2901
+			}
2902
+		}
2903
+		else
2904
+		{
2905
+			$error_str='Propal status do not meet requirement '.$this->statut;
2906
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
2907
+			$this->error=$error_str;
2908
+			$this->errors[]= $this->error;
2909
+			return -2;
2910
+		}
2911
+	}
2912
+
2913
+
2914
+	/**
2915
+	 *	Object Proposal Information
2916
+	 *
2917
+	 * 	@param	int		$id		Proposal id
2918
+	 *  @return	void
2919
+	 */
2920
+	function info($id)
2921
+	{
2922
+		$sql = "SELECT c.rowid, ";
2923
+		$sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
2924
+		$sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
2925
+		$sql.= " FROM ".MAIN_DB_PREFIX."propal as c";
2926
+		$sql.= " WHERE c.rowid = ".$id;
2927
+
2928
+		$result = $this->db->query($sql);
2929
+
2930
+		if ($result)
2931
+		{
2932
+			if ($this->db->num_rows($result))
2933
+			{
2934
+				$obj = $this->db->fetch_object($result);
2935
+
2936
+				$this->id                = $obj->rowid;
2937
+
2938
+				$this->date_creation     = $this->db->jdate($obj->datec);
2939
+				$this->date_validation   = $this->db->jdate($obj->datev);
2940
+				$this->date_cloture      = $this->db->jdate($obj->dateo);
2941
+
2942
+				$cuser = new User($this->db);
2943
+				$cuser->fetch($obj->fk_user_author);
2944
+				$this->user_creation     = $cuser;
2945
+
2946
+				if ($obj->fk_user_valid)
2947
+				{
2948
+					$vuser = new User($this->db);
2949
+					$vuser->fetch($obj->fk_user_valid);
2950
+					$this->user_validation     = $vuser;
2951
+				}
2952
+
2953
+				if ($obj->fk_user_cloture)
2954
+				{
2955
+					$cluser = new User($this->db);
2956
+					$cluser->fetch($obj->fk_user_cloture);
2957
+					$this->user_cloture     = $cluser;
2958
+				}
2959
+
2960
+
2961
+			}
2962
+			$this->db->free($result);
2963
+
2964
+		}
2965
+		else
2966
+		{
2967
+			dol_print_error($this->db);
2968
+		}
2969
+	}
2970
+
2971
+
2972
+	/**
2973
+	 *    	Return label of status of proposal (draft, validated, ...)
2974
+	 *
2975
+	 *    	@param      int			$mode        0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
2976
+	 *    	@return     string		Label
2977
+	 */
2978
+	function getLibStatut($mode=0)
2979
+	{
2980
+		return $this->LibStatut($this->statut, $mode);
2981
+	}
2982
+
2983
+	/**
2984
+	 *    	Return label of a status (draft, validated, ...)
2985
+	 *
2986
+	 *    	@param      int			$statut		id statut
2987
+	 *    	@param      int			$mode      	0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2988
+	 *    	@return     string		Label
2989
+	 */
2990
+	 function LibStatut($statut,$mode=1)
2991
+	{
2992
+		global $langs;
2993
+		$langs->load("propal");
2994
+
2995
+		if ($statut==self::STATUS_DRAFT) $statuttrans='statut0';
2996
+		if ($statut==self::STATUS_VALIDATED) $statuttrans='statut1';
2997
+		if ($statut==self::STATUS_SIGNED) $statuttrans='statut3';
2998
+		if ($statut==self::STATUS_NOTSIGNED) $statuttrans='statut5';
2999
+		if ($statut==self::STATUS_BILLED) $statuttrans='statut6';
3000
+
3001
+		if ($mode == 0)	return $this->labelstatut[$statut];
3002
+		if ($mode == 1)	return $this->labelstatut_short[$statut];
3003
+		if ($mode == 2)	return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut];
3004
+		if ($mode == 3)	return img_picto($this->labelstatut[$statut], $statuttrans);
3005
+		if ($mode == 4)	return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut];
3006
+		if ($mode == 5)	return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3007
+		if ($mode == 6)	return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3008
+	 }
3009
+
3010
+
3011
+	/**
3012
+	 *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
3013
+	 *
3014
+	 *      @param          User	$user   Object user
3015
+	 *      @param          int		$mode   "opened" for proposal to close, "signed" for proposal to invoice
3016
+	 *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
3017
+	 */
3018
+	function load_board($user,$mode)
3019
+	{
3020
+		global $conf, $langs;
3021
+
3022
+		$clause = " WHERE";
3023
+
3024
+		$sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin";
3025
+		$sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3026
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
3027
+		{
3028
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3029
+			$sql.= " WHERE sc.fk_user = " .$user->id;
3030
+			$clause = " AND";
3031
+		}
3032
+		$sql.= $clause." p.entity IN (".getEntity('propal').")";
3033
+		if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3034
+		if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED;
3035
+		if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id;
3036
+
3037
+		$resql=$this->db->query($sql);
3038
+		if ($resql)
3039
+		{
3040
+			$langs->load("propal");
3041
+			$now=dol_now();
3042
+
3043
+			if ($mode == 'opened') {
3044
+				$delay_warning=$conf->propal->cloture->warning_delay;
3045
+				$statut = self::STATUS_VALIDATED;
3046
+				$label = $langs->trans("PropalsToClose");
3047
+			}
3048
+			if ($mode == 'signed') {
3049
+				$delay_warning=$conf->propal->facturation->warning_delay;
3050
+				$statut = self::STATUS_SIGNED;
3051
+				$label = $langs->trans("PropalsToBill");         // We set here bill but may be billed or ordered
3052
+			}
3053
+
3054
+			$response = new WorkboardResponse();
3055
+			$response->warning_delay = $delay_warning/60/60/24;
3056
+			$response->label = $label;
3057
+			$response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals';
3058
+			$response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
3059
+			$response->img = img_object('',"propal");
3060
+
3061
+			// This assignment in condition is not a bug. It allows walking the results.
3062
+			while ($obj=$this->db->fetch_object($resql))
3063
+			{
3064
+				$response->nbtodo++;
3065
+				if ($mode == 'opened')
3066
+				{
3067
+					$datelimit = $this->db->jdate($obj->datefin);
3068
+					if ($datelimit < ($now - $delay_warning))
3069
+					{
3070
+						$response->nbtodolate++;
3071
+					}
3072
+				}
3073
+				// TODO Definir regle des propales a facturer en retard
3074
+				// if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
3075
+			}
3076
+
3077
+			return $response;
3078
+		}
3079
+		else
3080
+		{
3081
+			$this->error=$this->db->error();
3082
+			return -1;
3083
+		}
3084
+	}
3085
+
3086
+
3087
+	/**
3088
+	 *  Initialise an instance with random values.
3089
+	 *  Used to build previews or test instances.
3090
+	 *	id must be 0 if object instance is a specimen.
3091
+	 *
3092
+	 *  @return	void
3093
+	 */
3094
+	function initAsSpecimen()
3095
+	{
3096
+		global $langs;
3097
+
3098
+		// Load array of products prodids
3099
+		$num_prods = 0;
3100
+		$prodids = array();
3101
+		$sql = "SELECT rowid";
3102
+		$sql.= " FROM ".MAIN_DB_PREFIX."product";
3103
+		$sql.= " WHERE entity IN (".getEntity('product').")";
3104
+		$resql = $this->db->query($sql);
3105
+		if ($resql)
3106
+		{
3107
+			$num_prods = $this->db->num_rows($resql);
3108
+			$i = 0;
3109
+			while ($i < $num_prods)
3110
+			{
3111
+				$i++;
3112
+				$row = $this->db->fetch_row($resql);
3113
+				$prodids[$i] = $row[0];
3114
+			}
3115
+		}
3116
+
3117
+		// Initialise parametres
3118
+		$this->id=0;
3119
+		$this->ref = 'SPECIMEN';
3120
+		$this->ref_client='NEMICEPS';
3121
+		$this->specimen=1;
3122
+		$this->socid = 1;
3123
+		$this->date = time();
3124
+		$this->fin_validite = $this->date+3600*24*30;
3125
+		$this->cond_reglement_id   = 1;
3126
+		$this->cond_reglement_code = 'RECEP';
3127
+		$this->mode_reglement_id   = 7;
3128
+		$this->mode_reglement_code = 'CHQ';
3129
+		$this->availability_id     = 1;
3130
+		$this->availability_code   = 'AV_NOW';
3131
+		$this->demand_reason_id    = 1;
3132
+		$this->demand_reason_code  = 'SRC_00';
3133
+		$this->note_public='This is a comment (public)';
3134
+		$this->note_private='This is a comment (private)';
3135
+		// Lines
3136
+		$nbp = 5;
3137
+		$xnbp = 0;
3138
+		while ($xnbp < $nbp)
3139
+		{
3140
+			$line=new PropaleLigne($this->db);
3141
+			$line->desc=$langs->trans("Description")." ".$xnbp;
3142
+			$line->qty=1;
3143
+			$line->subprice=100;
3144
+			$line->price=100;
3145
+			$line->tva_tx=20;
3146
+			$line->localtax1_tx=0;
3147
+			$line->localtax2_tx=0;
3148
+			if ($xnbp == 2)
3149
+			{
3150
+				$line->total_ht=50;
3151
+				$line->total_ttc=60;
3152
+				$line->total_tva=10;
3153
+				$line->remise_percent=50;
3154
+			}
3155
+			else
3156
+			{
3157
+				$line->total_ht=100;
3158
+				$line->total_ttc=120;
3159
+				$line->total_tva=20;
3160
+				$line->remise_percent=00;
3161
+			}
3162
+
3163
+			if ($num_prods > 0)
3164
+			{
3165
+				$prodid = mt_rand(1, $num_prods);
3166
+				$line->fk_product=$prodids[$prodid];
3167
+		$line->product_ref='SPECIMEN';
3168
+			}
3169
+
3170
+			$this->lines[$xnbp]=$line;
3171
+
3172
+			$this->total_ht       += $line->total_ht;
3173
+			$this->total_tva      += $line->total_tva;
3174
+			$this->total_ttc      += $line->total_ttc;
3175
+
3176
+			$xnbp++;
3177
+		}
3178
+	}
3179
+
3180
+	/**
3181
+	 *      Charge indicateurs this->nb de tableau de bord
3182
+	 *
3183
+	 *      @return     int         <0 if ko, >0 if ok
3184
+	 */
3185
+	function load_state_board()
3186
+	{
3187
+		global $user;
3188
+
3189
+		$this->nb=array();
3190
+		$clause = "WHERE";
3191
+
3192
+		$sql = "SELECT count(p.rowid) as nb";
3193
+		$sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3194
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3195
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
3196
+		{
3197
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3198
+			$sql.= " WHERE sc.fk_user = " .$user->id;
3199
+			$clause = "AND";
3200
+		}
3201
+		$sql.= " ".$clause." p.entity IN (".getEntity('propal').")";
3202
+
3203
+		$resql=$this->db->query($sql);
3204
+		if ($resql)
3205
+		{
3206
+			// This assignment in condition is not a bug. It allows walking the results.
3207
+			while ($obj=$this->db->fetch_object($resql))
3208
+			{
3209
+				$this->nb["proposals"]=$obj->nb;
3210
+			}
3211
+			$this->db->free($resql);
3212
+			return 1;
3213
+		}
3214
+		else
3215
+		{
3216
+			dol_print_error($this->db);
3217
+			$this->error=$this->db->error();
3218
+			return -1;
1505 3219
 		}
1506 3220
 	}
1507 3221
 
1508
-    /**
1509
-     *	Update value of extrafields on the proposal
1510
-     *
1511
-     *	@param      User	$user       Object user that modify
1512
-     *	@return     int         		<0 if ko, >0 if ok
1513
-     */
1514
-    function update_extrafields($user)
1515
-    {
1516
-        global $conf, $hookmanager;
1517
-
1518
-    	$action='update';
1519
-        $error = 0;
1520
-
1521
-    	// Actions on extra fields (by external module or standard code)
1522
-    	// TODO le hook fait double emploi avec le trigger !!
1523
-    	$hookmanager->initHooks(array('propaldao'));
1524
-    	$parameters=array('id'=>$this->id);
1525
-    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1526
-    	if (empty($reshook))
1527
-    	{
1528
-    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1529
-    		{
1530
-    			$result=$this->insertExtraFields();
1531
-    			if ($result < 0)
1532
-    			{
1533
-    				$error++;
1534
-    			}
1535
-    		}
1536
-    	}
1537
-    	else if ($reshook < 0) $error++;
1538 3222
 
1539
-		if (!$error)
1540
-	    {
1541
-	    	return 1;
1542
-	    }
1543
-	    else
1544
-	    {
1545
-	    	return -1;
1546
-	    }
1547
-
1548
-    }
1549
-
1550
-    /**
1551
-     *  Set status to validated
1552
-     *
1553
-     *  @param	User	$user       Object user that validate
1554
-     *  @param	int		$notrigger	1=Does not execute triggers, 0=execute triggers
1555
-     *  @return int         		<0 if KO, 0=Nothing done, >=0 if OK
1556
-     */
1557
-    function valid($user, $notrigger=0)
1558
-    {
1559
-    	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1560
-
1561
-    	global $conf;
1562
-
1563
-        $error=0;
1564
-
1565
-        // Protection
1566
-        if ($this->statut == self::STATUS_VALIDATED)
1567
-        {
1568
-            dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
1569
-            return 0;
1570
-        }
1571
-
1572
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer))
1573
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))))
1574
-        {
1575
-            $this->error='ErrorPermissionDenied';
1576
-            dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1577
-            return -1;
1578
-        }
1579
-
1580
-        $now=dol_now();
1581
-
1582
-        $this->db->begin();
1583
-
1584
-        // Numbering module definition
1585
-        $soc = new Societe($this->db);
1586
-        $soc->fetch($this->socid);
1587
-
1588
-        // Define new ref
1589
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1590
-        {
1591
-        	$num = $this->getNextNumRef($soc);
1592
-        }
1593
-        else
1594
-        {
1595
-        	$num = $this->ref;
1596
-        }
1597
-        $this->newref = $num;
1598
-
1599
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1600
-        $sql.= " SET ref = '".$num."',";
1601
-        $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
1602
-        $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1603
-
1604
-        dol_syslog(get_class($this)."::valid", LOG_DEBUG);
1605
-		$resql=$this->db->query($sql);
1606
-		if (! $resql)
1607
-		{
1608
-			dol_print_error($this->db);
1609
-			$error++;
1610
-		}
3223
+	/**
3224
+	 *  Returns the reference to the following non used Proposal used depending on the active numbering module
3225
+	 *  defined into PROPALE_ADDON
3226
+	 *
3227
+	 *  @param	Societe		$soc  	Object thirdparty
3228
+	 *  @return string      		Reference libre pour la propale
3229
+	 */
3230
+	function getNextNumRef($soc)
3231
+	{
3232
+		global $conf,$langs;
3233
+		$langs->load("propal");
1611 3234
 
1612
-		// Trigger calls
1613
-		if (! $error && ! $notrigger)
3235
+		if (! empty($conf->global->PROPALE_ADDON))
1614 3236
 		{
1615
-            // Call trigger
1616
-            $result=$this->call_trigger('PROPAL_VALIDATE',$user);
1617
-            if ($result < 0) { $error++; }
1618
-            // End call triggers
1619
-        }
1620
-
1621
-        if (! $error)
1622
-        {
1623
-        	$this->oldref = $this->ref;
1624
-
1625
-        	// Rename directory if dir was a temporary ref
1626
-        	if (preg_match('/^[\(]?PROV/i', $this->ref))
1627
-        	{
1628
-        		// Rename of propal directory ($this->ref = old ref, $num = new ref)
1629
-        		// to  not lose the linked files
1630
-        		$oldref = dol_sanitizeFileName($this->ref);
1631
-        		$newref = dol_sanitizeFileName($num);
1632
-        		$dirsource = $conf->propal->dir_output.'/'.$oldref;
1633
-        		$dirdest = $conf->propal->dir_output.'/'.$newref;
1634
-
1635
-        		if (file_exists($dirsource))
1636
-        		{
1637
-        			dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
1638
-        			if (@rename($dirsource, $dirdest))
1639
-        			{
1640
-        				dol_syslog("Rename ok");
1641
-        				// Rename docs starting with $oldref with $newref
1642
-        				$listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1643
-        				foreach($listoffiles as $fileentry)
1644
-        				{
1645
-        					$dirsource=$fileentry['name'];
1646
-        					$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1647
-        					$dirsource=$fileentry['path'].'/'.$dirsource;
1648
-        					$dirdest=$fileentry['path'].'/'.$dirdest;
1649
-        					@rename($dirsource, $dirdest);
1650
-        				}
1651
-        			}
1652
-        		}
1653
-        	}
1654
-
1655
-        	$this->ref=$num;
1656
-        	$this->brouillon=0;
1657
-        	$this->statut = self::STATUS_VALIDATED;
1658
-        	$this->user_valid_id=$user->id;
1659
-        	$this->datev=$now;
1660
-
1661
-        	$this->db->commit();
1662
-        	return 1;
1663
-        }
1664
-        else
1665
-		{
1666
-        	$this->db->rollback();
1667
-        	return -1;
1668
-        }
1669
-    }
1670
-
1671
-
1672
-    /**
1673
-     *  Define proposal date
1674
-     *
1675
-     *  @param  User		$user      	Object user that modify
1676
-     *  @param  int			$date		Date
1677
-     *  @param  int			$notrigger	1=Does not execute triggers, 0= execute triggers
1678
-     *  @return	int         			<0 if KO, >0 if OK
1679
-     */
1680
-    function set_date($user, $date, $notrigger=0)
1681
-    {
1682
-        if (empty($date))
1683
-        {
1684
-            $this->error='ErrorBadParameter';
1685
-            dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
1686
-            return -1;
1687
-        }
1688
-
1689
-        if (! empty($user->rights->propal->creer))
1690
-        {
1691
-        	$error=0;
1692
-
1693
-        	$this->db->begin();
1694
-
1695
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'";
1696
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1697
-
1698
-            dol_syslog(__METHOD__, LOG_DEBUG);
1699
-            $resql=$this->db->query($sql);
1700
-            if (!$resql)
1701
-            {
1702
-            	$this->errors[]=$this->db->error();
1703
-            	$error++;
1704
-            }
1705
-
1706
-            if (! $error)
1707
-            {
1708
-            	$this->oldcopy= clone $this;
1709
-            	$this->date = $date;
1710
-            	$this->datep = $date;    // deprecated
1711
-            }
1712
-
1713
-            if (! $notrigger && empty($error))
1714
-            {
1715
-            	// Call trigger
1716
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1717
-            	if ($result < 0) $error++;
1718
-            	// End call triggers
1719
-            }
1720
-
1721
-            if (! $error)
1722
-            {
1723
-            	$this->db->commit();
1724
-            	return 1;
1725
-            }
1726
-            else
1727
-            {
1728
-            	foreach($this->errors as $errmsg)
1729
-            	{
1730
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1731
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1732
-            	}
1733
-            	$this->db->rollback();
1734
-            	return -1*$error;
1735
-            }
1736
-        }
1737
-    }
1738
-
1739
-    /**
1740
-     *	Define end validity date
1741
-     *
1742
-     *	@param		User	$user        		Object user that modify
1743
-     *	@param      int		$date_fin_validite	End of validity date
1744
-     *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1745
-     *	@return     int         				<0 if KO, >0 if OK
1746
-     */
1747
-    function set_echeance($user, $date_fin_validite, $notrigger=0)
1748
-    {
1749
-        if (! empty($user->rights->propal->creer))
1750
-        {
1751
-        	$error=0;
1752
-
1753
-        	$this->db->begin();
1754
-
1755
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null');
1756
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1757
-
1758
-            dol_syslog(__METHOD__, LOG_DEBUG);
1759
-            $resql=$this->db->query($sql);
1760
-            if (!$resql)
1761
-            {
1762
-            	$this->errors[]=$this->db->error();
1763
-            	$error++;
1764
-            }
1765
-
1766
-
1767
-            if (! $error)
1768
-            {
1769
-            	$this->oldcopy= clone $this;
1770
-            	$this->fin_validite = $date_fin_validite;
1771
-            }
1772
-
1773
-            if (! $notrigger && empty($error))
1774
-            {
1775
-            	// Call trigger
1776
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1777
-            	if ($result < 0) $error++;
1778
-            	// End call triggers
1779
-            }
1780
-
1781
-            if (! $error)
1782
-            {
1783
-            	$this->db->commit();
1784
-            	return 1;
1785
-            }
1786
-            else
1787
-            {
1788
-            	foreach($this->errors as $errmsg)
1789
-            	{
1790
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1791
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1792
-            	}
1793
-            	$this->db->rollback();
1794
-            	return -1*$error;
1795
-            }
1796
-        }
1797
-    }
1798
-
1799
-    /**
1800
-     *	Set delivery date
1801
-     *
1802
-     *	@param      User 	$user        		Object user that modify
1803
-     *	@param      int		$date_livraison     Delivery date
1804
-     *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1805
-     *	@return     int         				<0 if ko, >0 if ok
1806
-     */
1807
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
1808
-    {
1809
-        if (! empty($user->rights->propal->creer))
1810
-        {
1811
-        	$error=0;
1812
-
1813
-        	$this->db->begin();
1814
-
1815
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1816
-            $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null');
1817
-            $sql.= " WHERE rowid = ".$this->id;
1818
-
1819
-            dol_syslog(__METHOD__, LOG_DEBUG);
1820
-            $resql=$this->db->query($sql);
1821
-            if (!$resql)
1822
-            {
1823
-            	$this->errors[]=$this->db->error();
1824
-            	$error++;
1825
-            }
1826
-
1827
-            if (! $error)
1828
-            {
1829
-            	$this->oldcopy= clone $this;
1830
-            	$this->date_livraison = $date_livraison;
1831
-            }
1832
-
1833
-            if (! $notrigger && empty($error))
1834
-            {
1835
-            	// Call trigger
1836
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1837
-            	if ($result < 0) $error++;
1838
-            	// End call triggers
1839
-            }
1840
-
1841
-            if (! $error)
1842
-            {
1843
-            	$this->db->commit();
1844
-            	return 1;
1845
-            }
1846
-            else
1847
-            {
1848
-            	foreach($this->errors as $errmsg)
1849
-            	{
1850
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1851
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1852
-            	}
1853
-            	$this->db->rollback();
1854
-            	return -1*$error;
1855
-            }
1856
-        }
1857
-    }
1858
-
1859
-    /**
1860
-     *  Set delivery
1861
-     *
1862
-     *  @param		User	$user		  	Object user that modify
1863
-     *  @param      int		$id				Availability id
1864
-     *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1865
-     *  @return     int           			<0 if KO, >0 if OK
1866
-     */
1867
-    function set_availability($user, $id, $notrigger=0)
1868
-    {
1869
-        if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1870
-        {
1871
-        	$error=0;
1872
-
1873
-        	$this->db->begin();
1874
-
1875
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1876
-            $sql.= " SET fk_availability = '".$id."'";
1877
-            $sql.= " WHERE rowid = ".$this->id;
1878
-
1879
-            dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
1880
-            $resql=$this->db->query($sql);
1881
-            if (!$resql)
1882
-            {
1883
-            	$this->errors[]=$this->db->error();
1884
-            	$error++;
1885
-            }
1886
-
1887
-            if (! $error)
1888
-            {
1889
-            	$this->oldcopy= clone $this;
1890
-            	$this->fk_availability = $id;
1891
-            	$this->availability_id = $id;
1892
-            }
1893
-
1894
-            if (! $notrigger && empty($error))
1895
-            {
1896
-            	// Call trigger
1897
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1898
-            	if ($result < 0) $error++;
1899
-            	// End call triggers
1900
-            }
1901
-
1902
-            if (! $error)
1903
-            {
1904
-            	$this->db->commit();
1905
-            	return 1;
1906
-            }
1907
-            else
1908
-            {
1909
-            	foreach($this->errors as $errmsg)
1910
-            	{
1911
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1912
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1913
-            	}
1914
-            	$this->db->rollback();
1915
-            	return -1*$error;
1916
-            }
1917
-        }
1918
-        else
1919
-        {
1920
-        	$error_str='Propal status do not meet requirement '.$this->statut;
1921
-        	dol_syslog(__METHOD__.$error_str, LOG_ERR);
1922
-        	$this->error=$error_str;
1923
-        	$this->errors[]= $this->error;
1924
-        	return -2;
1925
-        }
1926
-    }
1927
-
1928
-    /**
1929
-     *  Set source of demand
1930
-     *
1931
-     *  @param		User	$user		Object user that modify
1932
-     *  @param      int		$id			Input reason id
1933
-     *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1934
-     *  @return     int           		<0 if KO, >0 if OK
1935
-     */
1936
-    function set_demand_reason($user, $id, $notrigger=0)
1937
-    {
1938
-        if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1939
-        {
1940
-        	$error=0;
1941
-
1942
-        	$this->db->begin();
1943
-
1944
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1945
-            $sql.= " SET fk_input_reason = ".$id;
1946
-            $sql.= " WHERE rowid = ".$this->id;
1947
-
1948
-            dol_syslog(__METHOD__, LOG_DEBUG);
1949
-            $resql=$this->db->query($sql);
1950
-            if (!$resql)
1951
-            {
1952
-            	$this->errors[]=$this->db->error();
1953
-            	$error++;
1954
-            }
1955
-
1956
-
1957
-            if (! $error)
1958
-            {
1959
-            	$this->oldcopy= clone $this;
1960
-            	$this->fk_input_reason = $id;
1961
-            	$this->demand_reason_id = $id;
1962
-            }
1963
-
1964
-
1965
-            if (! $notrigger && empty($error))
1966
-            {
1967
-            	// Call trigger
1968
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1969
-            	if ($result < 0) $error++;
1970
-            	// End call triggers
1971
-            }
1972
-
1973
-            if (! $error)
1974
-            {
1975
-            	$this->db->commit();
1976
-            	return 1;
1977
-            }
1978
-            else
1979
-            {
1980
-            	foreach($this->errors as $errmsg)
1981
-            	{
1982
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1983
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1984
-            	}
1985
-            	$this->db->rollback();
1986
-            	return -1*$error;
1987
-            }
1988
-        }
1989
-        else
1990
-        {
1991
-        	$error_str='Propal status do not meet requirement '.$this->statut;
1992
-        	dol_syslog(__METHOD__.$error_str, LOG_ERR);
1993
-        	$this->error=$error_str;
1994
-        	$this->errors[]= $this->error;
1995
-        	return -2;
1996
-        }
1997
-    }
1998
-
1999
-    /**
2000
-     * Set customer reference number
2001
-     *
2002
-     *  @param      User	$user			Object user that modify
2003
-     *  @param      string	$ref_client		Customer reference
2004
-     *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2005
-     *  @return     int						<0 if ko, >0 if ok
2006
-     */
2007
-    function set_ref_client($user, $ref_client, $notrigger=0)
2008
-    {
2009
-        if (! empty($user->rights->propal->creer))
2010
-        {
2011
-            $error=0;
2012
-
2013
-            $this->db->begin();
2014
-
2015
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2016
-            $sql.= ' WHERE rowid = '.$this->id;
2017
-
2018
-            dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2019
-            $resql=$this->db->query($sql);
2020
-            if (!$resql)
2021
-            {
2022
-            	$this->errors[]=$this->db->error();
2023
-            	$error++;
2024
-            }
2025
-
2026
-            if (! $error)
2027
-            {
2028
-            	$this->oldcopy= clone $this;
2029
-            	$this->ref_client = $ref_client;
2030
-            }
2031
-
2032
-            if (! $notrigger && empty($error))
2033
-            {
2034
-            	// Call trigger
2035
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2036
-            	if ($result < 0) $error++;
2037
-            	// End call triggers
2038
-            }
2039
-
2040
-            if (! $error)
2041
-            {
2042
-            	$this->db->commit();
2043
-            	return 1;
2044
-            }
2045
-            else
2046
-            {
2047
-            	foreach($this->errors as $errmsg)
2048
-            	{
2049
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2050
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2051
-            	}
2052
-            	$this->db->rollback();
2053
-            	return -1*$error;
2054
-            }
2055
-        }
2056
-        else
2057
-        {
2058
-            return -1;
2059
-        }
2060
-    }
2061
-
2062
-    /**
2063
-     *	Set an overall discount on the proposal
2064
-     *
2065
-     *	@param      User	$user       Object user that modify
2066
-     *	@param      double	$remise     Amount discount
2067
-     *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2068
-     *	@return     int         		<0 if ko, >0 if ok
2069
-     */
2070
-    function set_remise_percent($user, $remise, $notrigger=0)
2071
-    {
2072
-        $remise=trim($remise)?trim($remise):0;
2073
-
2074
-        if (! empty($user->rights->propal->creer))
2075
-        {
2076
-            $remise = price2num($remise);
2077
-
2078
-            $error=0;
2079
-
2080
-            $this->db->begin();
2081
-
2082
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise;
2083
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2084
-
2085
-            dol_syslog(__METHOD__, LOG_DEBUG);
2086
-            $resql=$this->db->query($sql);
2087
-            if (!$resql)
2088
-            {
2089
-            	$this->errors[]=$this->db->error();
2090
-            	$error++;
2091
-            }
2092
-
2093
-            if (! $error)
2094
-            {
2095
-            	$this->oldcopy= clone $this;
2096
-            	$this->remise_percent = $remise;
2097
-            	$this->update_price(1);
2098
-            }
2099
-
2100
-            if (! $notrigger && empty($error))
2101
-            {
2102
-            	// Call trigger
2103
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2104
-            	if ($result < 0) $error++;
2105
-            	// End call triggers
2106
-            }
2107
-
2108
-            if (! $error)
2109
-            {
2110
-            	$this->db->commit();
2111
-            	return 1;
2112
-            }
2113
-            else
2114
-            {
2115
-            	foreach($this->errors as $errmsg)
2116
-            	{
2117
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2118
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2119
-            	}
2120
-            	$this->db->rollback();
2121
-            	return -1*$error;
2122
-            }
2123
-        }
2124
-    }
2125
-
2126
-
2127
-    /**
2128
-     *	Set an absolute overall discount on the proposal
2129
-     *
2130
-     *	@param      User	$user       Object user that modify
2131
-     *	@param      double	$remise     Amount discount
2132
-     *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2133
-     *	@return     int         		<0 if ko, >0 if ok
2134
-     */
2135
-    function set_remise_absolue($user, $remise, $notrigger=0)
2136
-    {
2137
-        $remise=trim($remise)?trim($remise):0;
2138
-
2139
-        if (! empty($user->rights->propal->creer))
2140
-        {
2141
-            $remise = price2num($remise);
2142
-
2143
-            $error=0;
2144
-
2145
-            $this->db->begin();
2146
-
2147
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
2148
-            $sql.= " SET remise_absolue = ".$remise;
2149
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2150
-
2151
-            dol_syslog(__METHOD__, LOG_DEBUG);
2152
-            $resql=$this->db->query($sql);
2153
-            if (!$resql)
2154
-            {
2155
-            	$this->errors[]=$this->db->error();
2156
-            	$error++;
2157
-            }
2158
-
2159
-            if (! $error)
2160
-            {
2161
-            	$this->oldcopy= clone $this;
2162
-            	$this->remise_absolue = $remise;
2163
-            	$this->update_price(1);
2164
-            }
2165
-
2166
-            if (! $notrigger && empty($error))
2167
-            {
2168
-            	// Call trigger
2169
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2170
-            	if ($result < 0) $error++;
2171
-            	// End call triggers
2172
-            }
2173
-
2174
-            if (! $error)
2175
-            {
2176
-            	$this->db->commit();
2177
-            	return 1;
2178
-            }
2179
-            else
2180
-            {
2181
-            	foreach($this->errors as $errmsg)
2182
-            	{
2183
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2184
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2185
-            	}
2186
-            	$this->db->rollback();
2187
-            	return -1*$error;
2188
-            }
2189
-        }
2190
-    }
2191
-
2192
-
2193
-
2194
-    /**
2195
-     *	Reopen the commercial proposal
2196
-     *
2197
-     *	@param      User	$user		Object user that close
2198
-     *	@param      int		$statut		Statut
2199
-     *	@param      string	$note		Comment
2200
-     *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2201
-     *	@return     int         		<0 if KO, >0 if OK
2202
-     */
2203
-    function reopen($user, $statut, $note='', $notrigger=0)
2204
-    {
2205
-
2206
-        $this->statut = $statut;
2207
-        $error=0;
2208
-
2209
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2210
-        $sql.= " SET fk_statut = ".$this->statut.",";
2211
-		if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',";
2212
-        $sql.= " date_cloture=NULL, fk_user_cloture=NULL";
2213
-        $sql.= " WHERE rowid = ".$this->id;
3237
+			$mybool=false;
2214 3238
 
2215
-    	$this->db->begin();
3239
+			$file = $conf->global->PROPALE_ADDON.".php";
3240
+			$classname = $conf->global->PROPALE_ADDON;
2216 3241
 
2217
-		dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2218
-		$resql = $this->db->query($sql);
2219
-		if (! $resql) {
2220
-			$error++; $this->errors[]="Error ".$this->db->lasterror();
2221
-		}
2222
-		if (! $error)
2223
-		{
2224
-			if (! $notrigger)
3242
+			// Include file with class
3243
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3244
+			foreach ($dirmodels as $reldir) {
3245
+
3246
+				$dir = dol_buildpath($reldir."core/modules/propale/");
3247
+
3248
+				// Load file with numbering class (if found)
3249
+				$mybool|=@include_once $dir.$file;
3250
+			}
3251
+
3252
+			if (! $mybool)
2225 3253
 			{
2226
-                // Call trigger
2227
-                $result=$this->call_trigger('PROPAL_REOPEN',$user);
2228
-                if ($result < 0) { $error++; }
2229
-                // End call triggers
3254
+				dol_print_error('',"Failed to include file ".$file);
3255
+				return '';
2230 3256
 			}
2231
-		}
2232 3257
 
2233
-		// Commit or rollback
2234
-		if ($error)
2235
-		{
2236
-		    if (!empty($this->errors))
2237
-		    {
2238
-    			foreach($this->errors as $errmsg)
2239
-    			{
2240
-    				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2241
-    				$this->error.=($this->error?', '.$errmsg:$errmsg);
2242
-    			}
2243
-		    }
2244
-			$this->db->rollback();
2245
-			return -1*$error;
3258
+			$obj = new $classname();
3259
+			$numref = "";
3260
+			$numref = $obj->getNextValue($soc,$this);
3261
+
3262
+			if ($numref != "")
3263
+			{
3264
+				return $numref;
3265
+			}
3266
+			else
3267
+			{
3268
+				$this->error=$obj->error;
3269
+				//dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3270
+				return "";
3271
+			}
2246 3272
 		}
2247 3273
 		else
2248 3274
 		{
2249
-			$this->db->commit();
2250
-			return 1;
3275
+			$langs->load("errors");
3276
+			print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
3277
+			return "";
2251 3278
 		}
2252
-    }
2253
-
2254
-
2255
-    /**
2256
-     *	Close the commercial proposal
2257
-     *
2258
-     *	@param      User	$user		Object user that close
2259
-     *	@param      int		$statut		Statut
2260
-     *	@param      string	$note		Comment
2261
-     *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2262
-     *	@return     int         		<0 if KO, >0 if OK
2263
-     */
2264
-    function cloture($user, $statut, $note, $notrigger=0)
2265
-    {
2266
-        global $langs,$conf;
3279
+	}
2267 3280
 
2268
-        $error=0;
2269
-        $now=dol_now();
3281
+	/**
3282
+	 *	Return clicable link of object (with eventually picto)
3283
+	 *
3284
+	 *	@param      int		$withpicto		          Add picto into link
3285
+	 *	@param      string	$option			          Where point the link ('expedition', 'document', ...)
3286
+	 *	@param      string	$get_params    	          Parametres added to url
3287
+	 *  @param	    int   	$notooltip		          1=Disable tooltip
3288
+	 *  @param      int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3289
+	 *	@return     string          		          String with URL
3290
+	 */
3291
+	function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1)
3292
+	{
3293
+		global $langs, $conf, $user;
2270 3294
 
2271
-        $this->db->begin();
3295
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
2272 3296
 
2273
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2274
-        $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
2275
-        $sql.= " WHERE rowid = ".$this->id;
3297
+		$result='';
3298
+		$label='';
3299
+		$url='';
2276 3300
 
2277
-        $resql=$this->db->query($sql);
2278
-        if ($resql)
2279
-        {
2280
-        	$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf;
2281
-        	$trigger_name='PROPAL_CLOSE_REFUSED';
3301
+		if ($user->rights->propal->lire)
3302
+		{
3303
+			$label = '<u>' . $langs->trans("ShowPropal") . '</u>';
3304
+			if (! empty($this->ref))
3305
+				$label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3306
+			if (! empty($this->ref_client))
3307
+				$label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3308
+			if (! empty($this->total_ht))
3309
+				$label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3310
+			if (! empty($this->total_tva))
3311
+				$label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3312
+			if (! empty($this->total_ttc))
3313
+				$label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3314
+			if ($option == '') {
3315
+				$url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3316
+			}
3317
+			if ($option == 'compta') {  // deprecated
3318
+				$url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3319
+			}
3320
+			if ($option == 'expedition') {
3321
+				$url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params;
3322
+			}
3323
+			if ($option == 'document') {
3324
+				$url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params;
3325
+			}
2282 3326
 
2283
-            if ($statut == self::STATUS_SIGNED)
2284
-            {
2285
-            	$trigger_name='PROPAL_CLOSE_SIGNED';
2286
-				$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf;
3327
+			if ($option != 'nolink')
3328
+			{
3329
+				// Add param to save lastsearch_values or not
3330
+				$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3331
+				if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3332
+				if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3333
+			}
3334
+		}
2287 3335
 
2288
-                // The connected company is classified as a client
2289
-                $soc=new Societe($this->db);
2290
-                $soc->id = $this->socid;
2291
-                $result=$soc->set_as_client();
3336
+		$linkclose='';
3337
+		if (empty($notooltip) && $user->rights->propal->lire)
3338
+		{
3339
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3340
+			{
3341
+				$label=$langs->trans("ShowPropal");
3342
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3343
+			}
3344
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3345
+			$linkclose.=' class="classfortooltip"';
3346
+		}
2292 3347
 
2293
-                if ($result < 0)
2294
-                {
2295
-                    $this->error=$this->db->lasterror();
2296
-                    $this->db->rollback();
2297
-                    return -2;
2298
-                }
2299
-            }
2300
-            if ($statut == self::STATUS_BILLED)
2301
-            {
2302
-            	$trigger_name='PROPAL_CLASSIFY_BILLED';
2303
-            }
2304
-
2305
-            if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
2306
-            {
2307
-             	// Define output language
2308
-              	$outputlangs = $langs;
2309
-               	if (! empty($conf->global->MAIN_MULTILANGS))
2310
-               	{
2311
-               		$outputlangs = new Translate("",$conf);
2312
-               		$newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang);
2313
-               		$outputlangs->setDefaultLang($newlang);
2314
-               	}
2315
-               	//$ret=$object->fetch($id);    // Reload to get new records
2316
-	               $this->generateDocument($modelpdf, $outputlangs);
2317
-            }
2318
-
2319
-            if (! $error)
2320
-            {
2321
-            	$this->oldcopy= clone $this;
2322
-            	$this->statut = $statut;
2323
-            	$this->date_cloture = $now;
2324
-            	$this->note_private = $note;
2325
-            }
2326
-
2327
-            if (! $notrigger && empty($error))
2328
-            {
2329
-	            // Call trigger
2330
-	            $result=$this->call_trigger($trigger_name,$user);
2331
-	            if ($result < 0) { $error++; }
2332
-	            // End call triggers
2333
-            }
2334
-
2335
-            if ( ! $error )
2336
-            {
2337
-		        $this->db->commit();
2338
-                return 1;
2339
-            }
2340
-            else
2341
-            {
2342
-                $this->db->rollback();
2343
-                return -1;
2344
-            }
2345
-        }
2346
-        else
2347
-        {
2348
-            $this->error=$this->db->lasterror();
2349
-            $this->db->rollback();
2350
-            return -1;
2351
-        }
2352
-    }
2353
-
2354
-    /**
2355
-     *	Class invoiced the Propal
2356
-     *
2357
-     *	@param  	User	$user    	Object user
2358
-     *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2359
-     *	@return     int     			<0 si ko, >0 si ok
2360
-     */
2361
-    function classifyBilled(User $user, $notrigger=0)
2362
-    {
2363
-    	$error=0;
2364
-
2365
-    	$this->db->begin();
2366
-
2367
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED;
2368
-        $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2369
-
2370
-        dol_syslog(__METHOD__, LOG_DEBUG);
2371
-        $resql=$this->db->query($sql);
2372
-        if (!$resql)
2373
-        {
2374
-        	$this->errors[]=$this->db->error();
2375
-        	$error++;
2376
-        }
2377
-
2378
-        if (! $error)
2379
-        {
2380
-        	$this->oldcopy= clone $this;
2381
-        	$this->statut=self::STATUS_BILLED;
2382
-        }
2383
-
2384
-        if (! $notrigger && empty($error))
2385
-        {
2386
-        	// Call trigger
2387
-        	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2388
-        	if ($result < 0) $error++;
2389
-        	// End call triggers
2390
-        }
2391
-
2392
-        if (! $error)
2393
-        {
2394
-        	$this->db->commit();
2395
-        	return 1;
2396
-        }
2397
-        else
2398
-        {
2399
-        	foreach($this->errors as $errmsg)
2400
-        	{
2401
-        		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2402
-        		$this->error.=($this->error?', '.$errmsg:$errmsg);
2403
-        	}
2404
-        	$this->db->rollback();
2405
-        	return -1*$error;
2406
-        }
2407
-    }
2408
-
2409
-    /**
2410
-     *	Class invoiced the Propal
2411
-     *
2412
-     *	@return     int     	<0 si ko, >0 si ok
2413
-     *  @deprecated
2414
-     *  @see classifyBilled()
2415
-     */
2416
-    function classer_facturee()
2417
-    {
2418
-        global $user;
2419
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
3348
+		$linkstart = '<a href="'.$url.'"';
3349
+		$linkstart.=$linkclose.'>';
3350
+		$linkend='</a>';
2420 3351
 
2421
-    	return $this->classifyBilled($user);
2422
-    }
2423
-
2424
-    /**
2425
-     *	Set draft status
2426
-     *
2427
-     *	@param		User	$user		Object user that modify
2428
-     *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2429
-     *	@return		int					<0 if KO, >0 if OK
2430
-     */
2431
-    function set_draft($user, $notrigger=0)
2432
-    {
2433
-    	$error=0;
2434
-
2435
-    	$this->db->begin();
2436
-
2437
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT;
2438
-        $sql.= " WHERE rowid = ".$this->id;
2439
-
2440
-        dol_syslog(__METHOD__, LOG_DEBUG);
2441
-        $resql=$this->db->query($sql);
2442
-        if (!$resql)
2443
-        {
2444
-        	$this->errors[]=$this->db->error();
2445
-        	$error++;
2446
-        }
2447
-
2448
-        if (! $error)
2449
-        {
2450
-        	$this->oldcopy= clone $this;
2451
-        	$this->statut = self::STATUS_DRAFT;
2452
-            $this->brouillon = 1;
2453
-        }
2454
-
2455
-        if (! $notrigger && empty($error))
2456
-        {
2457
-        	// Call trigger
2458
-        	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2459
-        	if ($result < 0) $error++;
2460
-        	// End call triggers
2461
-        }
2462
-
2463
-        if (! $error)
2464
-        {
2465
-        	$this->db->commit();
2466
-        	return 1;
2467
-        }
2468
-        else
2469
-        {
2470
-        	foreach($this->errors as $errmsg)
2471
-        	{
2472
-        		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2473
-        		$this->error.=($this->error?', '.$errmsg:$errmsg);
2474
-        	}
2475
-        	$this->db->rollback();
2476
-        	return -1*$error;
2477
-        }
2478
-    }
2479
-
2480
-
2481
-    /**
2482
-     *    Return list of proposal (eventually filtered on user) into an array
2483
-     *
2484
-     *    @param	int		$shortlist			0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
2485
-     *    @param	int		$draft				0=not draft, 1=draft
2486
-     *    @param	int		$notcurrentuser		0=all user, 1=not current user
2487
-     *    @param    int		$socid				Id third pary
2488
-     *    @param    int		$limit				For pagination
2489
-     *    @param    int		$offset				For pagination
2490
-     *    @param    string	$sortfield			Sort criteria
2491
-     *    @param    string	$sortorder			Sort order
2492
-     *    @return	int		       				-1 if KO, array with result if OK
2493
-     */
2494
-    function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC')
2495
-    {
2496
-        global $user;
2497
-
2498
-        $ga = array();
2499
-
2500
-        $sql = "SELECT s.rowid, s.nom as name, s.client,";
2501
-        $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2502
-        $sql.= " p.datep as dp, p.fin_validite as datelimite";
2503
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2504
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2505
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2506
-        $sql.= " WHERE p.entity IN (".getEntity('propal').")";
2507
-        $sql.= " AND p.fk_soc = s.rowid";
2508
-        $sql.= " AND p.fk_statut = c.id";
2509
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2510
-        {
2511
-        	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2512
-        }
2513
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2514
-        if ($draft)	$sql.= " AND p.fk_statut = ".self::STATUS_DRAFT;
2515
-        if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id;
2516
-        $sql.= $this->db->order($sortfield,$sortorder);
2517
-        $sql.= $this->db->plimit($limit,$offset);
2518
-
2519
-        $result=$this->db->query($sql);
2520
-        if ($result)
2521
-        {
2522
-            $num = $this->db->num_rows($result);
2523
-            if ($num)
2524
-            {
2525
-                $i = 0;
2526
-                while ($i < $num)
2527
-                {
2528
-                    $obj = $this->db->fetch_object($result);
2529
-
2530
-                    if ($shortlist == 1)
2531
-                    {
2532
-                        $ga[$obj->propalid] = $obj->ref;
2533
-                    }
2534
-                    else if ($shortlist == 2)
2535
-                    {
2536
-                        $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
2537
-                    }
2538
-                    else
2539
-					{
2540
-                        $ga[$i]['id']	= $obj->propalid;
2541
-                        $ga[$i]['ref'] 	= $obj->ref;
2542
-                        $ga[$i]['name'] = $obj->name;
2543
-                    }
2544
-
2545
-                    $i++;
2546
-                }
2547
-            }
2548
-            return $ga;
2549
-        }
2550
-        else
2551
-        {
2552
-            dol_print_error($this->db);
2553
-            return -1;
2554
-        }
2555
-    }
2556
-
2557
-    /**
2558
-     *  Returns an array with the numbers of related invoices
2559
-     *
2560
-     *	@return	array		Array of invoices
2561
-     */
2562
-    function getInvoiceArrayList()
2563
-    {
2564
-        return $this->InvoiceArrayList($this->id);
2565
-    }
2566
-
2567
-    /**
2568
-     *  Returns an array with id and ref of related invoices
2569
-     *
2570
-     *	@param		int		$id			Id propal
2571
-     *	@return		array				Array of invoices id
2572
-     */
2573
-    function InvoiceArrayList($id)
2574
-    {
2575
-        $ga = array();
2576
-        $linkedInvoices = array();
2577
-
2578
-        $this->fetchObjectLinked($id,$this->element);
2579
-        foreach($this->linkedObjectsIds as $objecttype => $objectid)
2580
-        {
2581
-        	// Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n
2582
-        	// On parcourt donc une liste d'objets en tant qu'objet unique
2583
-			foreach($objectid as $key => $object)
2584
-            {
2585
-                // Cas des factures liees directement
2586
-                if ($objecttype == 'facture')
2587
-                {
2588
-                    $linkedInvoices[] = $object;
2589
-                }
2590
-                // Cas des factures liees par un autre objet (ex: commande)
2591
-                else
2592
-				{
2593
-                    $this->fetchObjectLinked($object,$objecttype);
2594
-                    foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid)
2595
-                    {
2596
-						foreach($subobjectid as $subkey => $subobject)
2597
-                        {
2598
-                        	if ($subobjecttype == 'facture')
2599
-                        	{
2600
-                            	$linkedInvoices[] = $subobject;
2601
-                        	}
2602
-                        }
2603
-                    }
2604
-                }
2605
-            }
2606
-        }
2607
-
2608
-        if (count($linkedInvoices) > 0)
2609
-        {
2610
-            $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye";
2611
-            $sql.= " FROM ".MAIN_DB_PREFIX."facture";
2612
-            $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")";
2613
-
2614
-            dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
2615
-            $resql=$this->db->query($sql);
2616
-
2617
-            if ($resql)
2618
-            {
2619
-                $tab_sqlobj=array();
2620
-                $nump = $this->db->num_rows($resql);
2621
-                for ($i = 0;$i < $nump;$i++)
2622
-                {
2623
-                    $sqlobj = $this->db->fetch_object($resql);
2624
-                    $tab_sqlobj[] = $sqlobj;
2625
-                }
2626
-                $this->db->free($resql);
3352
+		if ($withpicto)
3353
+			$result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3354
+		if ($withpicto && $withpicto != 2)
3355
+			$result.=' ';
3356
+		$result.=$linkstart.$this->ref.$linkend;
3357
+		return $result;
3358
+	}
2627 3359
 
2628
-                $nump = count($tab_sqlobj);
3360
+	/**
3361
+	 * 	Retrieve an array of propal lines
3362
+	 *
3363
+	 * 	@return int		>0 if OK, <0 if KO
3364
+	 */
3365
+	function getLinesArray()
3366
+	{
3367
+		// TODO Duplicate with fetch_lines ? Wich one to keep ?
2629 3368
 
2630
-                if ($nump)
2631
-                {
2632
-                    $i = 0;
2633
-                    while ($i < $nump)
2634
-                    {
2635
-                        $obj = array_shift($tab_sqlobj);
2636
-
2637
-                        $ga[$i] = $obj;
2638
-
2639
-                        $i++;
2640
-                    }
2641
-                }
2642
-                return $ga;
2643
-            }
2644
-            else
2645
-            {
2646
-                return -1;
2647
-            }
2648
-        }
2649
-        else return $ga;
2650
-    }
2651
-
2652
-    /**
2653
-     *	Delete proposal
2654
-     *
2655
-     *	@param	User	$user        	Object user that delete
2656
-     *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2657
-     *	@return	int						1 if ok, otherwise if error
2658
-     */
2659
-    function delete($user, $notrigger=0)
2660
-    {
2661
-        global $conf;
2662
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2663
-
2664
-        $error=0;
2665
-
2666
-        $this->db->begin();
2667
-
2668
-        if (! $notrigger)
2669
-        {
2670
-            // Call trigger
2671
-            $result=$this->call_trigger('PROPAL_DELETE',$user);
2672
-            if ($result < 0) { $error++; }
2673
-            // End call triggers
2674
-        }
2675
-
2676
-        if (! $error)
2677
-        {
2678
-            $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id;
2679
-            if ($this->db->query($sql))
2680
-            {
2681
-                $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id;
2682
-                if ($this->db->query($sql))
2683
-                {
2684
-                    // Delete linked object
2685
-                    $res = $this->deleteObjectLinked();
2686
-                    if ($res < 0) $error++;
2687
-
2688
-                    // Delete linked contacts
2689
-                    $res = $this->delete_linked_contact();
2690
-                    if ($res < 0) $error++;
2691
-
2692
-                    if (! $error)
2693
-                    {
2694
-                        // We remove directory
2695
-                        $ref = dol_sanitizeFileName($this->ref);
2696
-                        if ($conf->propal->dir_output && !empty($this->ref))
2697
-                        {
2698
-                            $dir = $conf->propal->dir_output . "/" . $ref ;
2699
-                            $file = $dir . "/" . $ref . ".pdf";
2700
-                            if (file_exists($file))
2701
-                            {
2702
-                                dol_delete_preview($this);
2703
-
2704
-                                if (! dol_delete_file($file,0,0,0,$this)) // For triggers
2705
-                                {
2706
-                                    $this->error='ErrorFailToDeleteFile';
2707
-                                    $this->errors=array('ErrorFailToDeleteFile');
2708
-                                	$this->db->rollback();
2709
-                                    return 0;
2710
-                                }
2711
-                            }
2712
-                            if (file_exists($dir))
2713
-                            {
2714
-                                $res=@dol_delete_dir_recursive($dir);
2715
-                                if (! $res)
2716
-                                {
2717
-                                    $this->error='ErrorFailToDeleteDir';
2718
-                                    $this->errors=array('ErrorFailToDeleteDir');
2719
-                                    $this->db->rollback();
2720
-                                    return 0;
2721
-                                }
2722
-                            }
2723
-                        }
2724
-                    }
2725
-
2726
-                    // Removed extrafields
2727
-                    if (! $error)
2728
-                    {
2729
-                    	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2730
-                    	{
2731
-                    		$result=$this->deleteExtraFields();
2732
-                    		if ($result < 0)
2733
-                    		{
2734
-                    			$error++;
2735
-                    			$errorflag=-4;
2736
-                    			dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
2737
-                    		}
2738
-                    	}
2739
-                    }
2740
-
2741
-                    if (! $error)
2742
-                    {
2743
-                        dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
2744
-                        $this->db->commit();
2745
-                        return 1;
2746
-                    }
2747
-                    else
2748
-                    {
2749
-                        $this->error=$this->db->lasterror();
2750
-                        $this->db->rollback();
2751
-                        return 0;
2752
-                    }
2753
-                }
2754
-                else
2755
-                {
2756
-                    $this->error=$this->db->lasterror();
2757
-                    $this->db->rollback();
2758
-                    return -3;
2759
-                }
2760
-            }
2761
-            else
2762
-            {
2763
-                $this->error=$this->db->lasterror();
2764
-                $this->db->rollback();
2765
-                return -2;
2766
-            }
2767
-        }
2768
-        else
2769
-        {
2770
-            $this->db->rollback();
2771
-            return -1;
2772
-        }
2773
-    }
2774
-
2775
-    /**
2776
-     *  Change the delivery time
2777
-     *
2778
-     *  @param	int	$availability_id	Id of new delivery time
2779
-     * 	@param	int	$notrigger			1=Does not execute triggers, 0= execute triggers
2780
-     *  @return int                  	>0 if OK, <0 if KO
2781
-     *  @deprecated  use set_availability
2782
-     */
2783
-    function availability($availability_id, $notrigger=0)
2784
-    {
2785
-        global $user;
2786
-
2787
-        if ($this->statut >= self::STATUS_DRAFT)
2788
-        {
2789
-        	$error=0;
2790
-
2791
-        	$this->db->begin();
2792
-
2793
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
2794
-            $sql .= ' SET fk_availability = '.$availability_id;
2795
-            $sql .= ' WHERE rowid='.$this->id;
2796
-
2797
-            dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
2798
-            $resql=$this->db->query($sql);
2799
-            if (!$resql)
2800
-            {
2801
-            	$this->errors[]=$this->db->error();
2802
-            	$error++;
2803
-            }
2804
-
2805
-            if (! $error)
2806
-            {
2807
-            	$this->oldcopy= clone $this;
2808
-            	$this->availability_id = $availability_id;
2809
-            }
2810
-
2811
-            if (! $notrigger && empty($error))
2812
-            {
2813
-            	// Call trigger
2814
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2815
-            	if ($result < 0) $error++;
2816
-            	// End call triggers
2817
-            }
2818
-
2819
-            if (! $error)
2820
-            {
2821
-            	$this->db->commit();
2822
-            	return 1;
2823
-            }
2824
-            else
2825
-            {
2826
-            	foreach($this->errors as $errmsg)
2827
-            	{
2828
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2829
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2830
-            	}
2831
-            	$this->db->rollback();
2832
-            	return -1*$error;
2833
-            }
2834
-        }
2835
-        else
2836
-        {
2837
-        	$error_str='Propal status do not meet requirement '.$this->statut;
2838
-        	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2839
-        	$this->error=$error_str;
2840
-        	$this->errors[]= $this->error;
2841
-            return -2;
2842
-        }
2843
-    }
2844
-
2845
-    /**
2846
-     *	Change source demand
2847
-     *
2848
-     *	@param	int $demand_reason_id 	Id of new source demand
2849
-     * 	@param	int	$notrigger			1=Does not execute triggers, 0= execute triggers
2850
-     *	@return int						>0 si ok, <0 si ko
2851
-     *	@deprecated use set_demand_reason
2852
-     */
2853
-    function demand_reason($demand_reason_id, $notrigger=0)
2854
-    {
2855
-        if ($this->statut >= self::STATUS_DRAFT)
2856
-        {
2857
-        	$error=0;
2858
-
2859
-        	$this->db->begin();
2860
-
2861
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
2862
-            $sql .= ' SET fk_input_reason = '.$demand_reason_id;
2863
-            $sql .= ' WHERE rowid='.$this->id;
2864
-
2865
-            dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
2866
-            $resql=$this->db->query($sql);
2867
-            if (!$resql)
2868
-            {
2869
-            	$this->errors[]=$this->db->error();
2870
-            	$error++;
2871
-            }
2872
-
2873
-            if (! $error)
2874
-            {
2875
-            	$this->oldcopy= clone $this;
2876
-            	$this->demand_reason_id = $demand_reason_id;
2877
-            }
2878
-
2879
-            if (! $notrigger && empty($error))
2880
-            {
2881
-            	// Call trigger
2882
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2883
-            	if ($result < 0) $error++;
2884
-            	// End call triggers
2885
-            }
2886
-
2887
-            if (! $error)
2888
-            {
2889
-            	$this->db->commit();
2890
-            	return 1;
2891
-            }
2892
-            else
2893
-            {
2894
-            	foreach($this->errors as $errmsg)
2895
-            	{
2896
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2897
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2898
-            	}
2899
-            	$this->db->rollback();
2900
-            	return -1*$error;
2901
-            }
2902
-        }
2903
-        else
2904
-        {
2905
-        	$error_str='Propal status do not meet requirement '.$this->statut;
2906
-        	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2907
-        	$this->error=$error_str;
2908
-        	$this->errors[]= $this->error;
2909
-            return -2;
2910
-        }
2911
-    }
2912
-
2913
-
2914
-    /**
2915
-     *	Object Proposal Information
2916
-     *
2917
-     * 	@param	int		$id		Proposal id
2918
-     *  @return	void
2919
-     */
2920
-    function info($id)
2921
-    {
2922
-        $sql = "SELECT c.rowid, ";
2923
-        $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
2924
-        $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
2925
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as c";
2926
-        $sql.= " WHERE c.rowid = ".$id;
2927
-
2928
-        $result = $this->db->query($sql);
2929
-
2930
-        if ($result)
2931
-        {
2932
-            if ($this->db->num_rows($result))
2933
-            {
2934
-                $obj = $this->db->fetch_object($result);
2935
-
2936
-                $this->id                = $obj->rowid;
2937
-
2938
-                $this->date_creation     = $this->db->jdate($obj->datec);
2939
-                $this->date_validation   = $this->db->jdate($obj->datev);
2940
-                $this->date_cloture      = $this->db->jdate($obj->dateo);
2941
-
2942
-                $cuser = new User($this->db);
2943
-                $cuser->fetch($obj->fk_user_author);
2944
-                $this->user_creation     = $cuser;
2945
-
2946
-                if ($obj->fk_user_valid)
2947
-                {
2948
-                    $vuser = new User($this->db);
2949
-                    $vuser->fetch($obj->fk_user_valid);
2950
-                    $this->user_validation     = $vuser;
2951
-                }
3369
+		$this->lines = array();
2952 3370
 
2953
-                if ($obj->fk_user_cloture)
2954
-                {
2955
-                    $cluser = new User($this->db);
2956
-                    $cluser->fetch($obj->fk_user_cloture);
2957
-                    $this->user_cloture     = $cluser;
2958
-                }
2959
-
2960
-
2961
-            }
2962
-            $this->db->free($result);
2963
-
2964
-        }
2965
-        else
2966
-        {
2967
-            dol_print_error($this->db);
2968
-        }
2969
-    }
2970
-
2971
-
2972
-    /**
2973
-     *    	Return label of status of proposal (draft, validated, ...)
2974
-     *
2975
-     *    	@param      int			$mode        0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
2976
-     *    	@return     string		Label
2977
-     */
2978
-    function getLibStatut($mode=0)
2979
-    {
2980
-        return $this->LibStatut($this->statut, $mode);
2981
-    }
2982
-
2983
-    /**
2984
-     *    	Return label of a status (draft, validated, ...)
2985
-     *
2986
-     *    	@param      int			$statut		id statut
2987
-     *    	@param      int			$mode      	0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2988
-     *    	@return     string		Label
2989
-     */
2990
-     function LibStatut($statut,$mode=1)
2991
-    {
2992
-		global $langs;
2993
-		$langs->load("propal");
3371
+		$sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
3372
+		$sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,';
3373
+		$sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,';
3374
+		$sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,';
3375
+		$sql.= ' pt.fk_unit,';
3376
+		$sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,';
3377
+		$sql.= ' p.entity,';
3378
+		$sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc';
3379
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt';
3380
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
3381
+		$sql.= ' WHERE pt.fk_propal = '.$this->id;
3382
+		$sql.= ' ORDER BY pt.rang ASC, pt.rowid';
2994 3383
 
2995
-		if ($statut==self::STATUS_DRAFT) $statuttrans='statut0';
2996
-		if ($statut==self::STATUS_VALIDATED) $statuttrans='statut1';
2997
-		if ($statut==self::STATUS_SIGNED) $statuttrans='statut3';
2998
-		if ($statut==self::STATUS_NOTSIGNED) $statuttrans='statut5';
2999
-		if ($statut==self::STATUS_BILLED) $statuttrans='statut6';
3384
+		dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
3385
+		$resql = $this->db->query($sql);
3386
+		if ($resql)
3387
+		{
3388
+			$num = $this->db->num_rows($resql);
3389
+			$i = 0;
3000 3390
 
3001
-		if ($mode == 0)	return $this->labelstatut[$statut];
3002
-		if ($mode == 1)	return $this->labelstatut_short[$statut];
3003
-		if ($mode == 2)	return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut];
3004
-		if ($mode == 3)	return img_picto($this->labelstatut[$statut], $statuttrans);
3005
-		if ($mode == 4)	return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut];
3006
-		if ($mode == 5)	return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3007
-		if ($mode == 6)	return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3008
-     }
3009
-
3010
-
3011
-    /**
3012
-     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
3013
-     *
3014
-     *      @param          User	$user   Object user
3015
-     *      @param          int		$mode   "opened" for proposal to close, "signed" for proposal to invoice
3016
-     *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
3017
-     */
3018
-    function load_board($user,$mode)
3019
-    {
3020
-        global $conf, $langs;
3021
-
3022
-        $clause = " WHERE";
3023
-
3024
-        $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin";
3025
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3026
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
3027
-        {
3028
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3029
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3030
-            $clause = " AND";
3031
-        }
3032
-        $sql.= $clause." p.entity IN (".getEntity('propal').")";
3033
-        if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3034
-        if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED;
3035
-        if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id;
3036
-
3037
-        $resql=$this->db->query($sql);
3038
-        if ($resql)
3039
-        {
3040
-	        $langs->load("propal");
3041
-	        $now=dol_now();
3042
-
3043
-            if ($mode == 'opened') {
3044
-	            $delay_warning=$conf->propal->cloture->warning_delay;
3045
-	            $statut = self::STATUS_VALIDATED;
3046
-	            $label = $langs->trans("PropalsToClose");
3047
-            }
3048
-            if ($mode == 'signed') {
3049
-	            $delay_warning=$conf->propal->facturation->warning_delay;
3050
-	            $statut = self::STATUS_SIGNED;
3051
-	            $label = $langs->trans("PropalsToBill");         // We set here bill but may be billed or ordered
3052
-            }
3053
-
3054
-	        $response = new WorkboardResponse();
3055
-	        $response->warning_delay = $delay_warning/60/60/24;
3056
-	        $response->label = $label;
3057
-	        $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals';
3058
-	        $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
3059
-	        $response->img = img_object('',"propal");
3060
-
3061
-            // This assignment in condition is not a bug. It allows walking the results.
3062
-            while ($obj=$this->db->fetch_object($resql))
3063
-            {
3064
-                $response->nbtodo++;
3065
-                if ($mode == 'opened')
3066
-                {
3067
-                    $datelimit = $this->db->jdate($obj->datefin);
3068
-                    if ($datelimit < ($now - $delay_warning))
3069
-                    {
3070
-	                    $response->nbtodolate++;
3071
-                    }
3072
-                }
3073
-                // TODO Definir regle des propales a facturer en retard
3074
-                // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
3075
-            }
3076
-
3077
-            return $response;
3078
-        }
3079
-        else
3080
-        {
3081
-            $this->error=$this->db->error();
3082
-            return -1;
3083
-        }
3084
-    }
3085
-
3086
-
3087
-    /**
3088
-     *  Initialise an instance with random values.
3089
-     *  Used to build previews or test instances.
3090
-     *	id must be 0 if object instance is a specimen.
3091
-     *
3092
-     *  @return	void
3093
-     */
3094
-    function initAsSpecimen()
3095
-    {
3096
-        global $langs;
3097
-
3098
-        // Load array of products prodids
3099
-        $num_prods = 0;
3100
-        $prodids = array();
3101
-        $sql = "SELECT rowid";
3102
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
3103
-        $sql.= " WHERE entity IN (".getEntity('product').")";
3104
-        $resql = $this->db->query($sql);
3105
-        if ($resql)
3106
-        {
3107
-            $num_prods = $this->db->num_rows($resql);
3108
-            $i = 0;
3109
-            while ($i < $num_prods)
3110
-            {
3111
-                $i++;
3112
-                $row = $this->db->fetch_row($resql);
3113
-                $prodids[$i] = $row[0];
3114
-            }
3115
-        }
3116
-
3117
-        // Initialise parametres
3118
-        $this->id=0;
3119
-        $this->ref = 'SPECIMEN';
3120
-        $this->ref_client='NEMICEPS';
3121
-        $this->specimen=1;
3122
-        $this->socid = 1;
3123
-        $this->date = time();
3124
-        $this->fin_validite = $this->date+3600*24*30;
3125
-        $this->cond_reglement_id   = 1;
3126
-        $this->cond_reglement_code = 'RECEP';
3127
-        $this->mode_reglement_id   = 7;
3128
-        $this->mode_reglement_code = 'CHQ';
3129
-        $this->availability_id     = 1;
3130
-        $this->availability_code   = 'AV_NOW';
3131
-        $this->demand_reason_id    = 1;
3132
-        $this->demand_reason_code  = 'SRC_00';
3133
-        $this->note_public='This is a comment (public)';
3134
-        $this->note_private='This is a comment (private)';
3135
-        // Lines
3136
-        $nbp = 5;
3137
-        $xnbp = 0;
3138
-        while ($xnbp < $nbp)
3139
-        {
3140
-            $line=new PropaleLigne($this->db);
3141
-            $line->desc=$langs->trans("Description")." ".$xnbp;
3142
-            $line->qty=1;
3143
-            $line->subprice=100;
3144
-            $line->price=100;
3145
-            $line->tva_tx=20;
3146
-            $line->localtax1_tx=0;
3147
-            $line->localtax2_tx=0;
3148
-            if ($xnbp == 2)
3149
-            {
3150
-                $line->total_ht=50;
3151
-                $line->total_ttc=60;
3152
-                $line->total_tva=10;
3153
-                $line->remise_percent=50;
3154
-            }
3155
-            else
3156
-            {
3157
-                $line->total_ht=100;
3158
-                $line->total_ttc=120;
3159
-                $line->total_tva=20;
3160
-                $line->remise_percent=00;
3161
-            }
3162
-
3163
-            if ($num_prods > 0)
3164
-            {
3165
-            	$prodid = mt_rand(1, $num_prods);
3166
-            	$line->fk_product=$prodids[$prodid];
3167
-		$line->product_ref='SPECIMEN';
3168
-            }
3169
-
3170
-            $this->lines[$xnbp]=$line;
3171
-
3172
-            $this->total_ht       += $line->total_ht;
3173
-            $this->total_tva      += $line->total_tva;
3174
-            $this->total_ttc      += $line->total_ttc;
3175
-
3176
-            $xnbp++;
3177
-        }
3178
-    }
3179
-
3180
-    /**
3181
-     *      Charge indicateurs this->nb de tableau de bord
3182
-     *
3183
-     *      @return     int         <0 if ko, >0 if ok
3184
-     */
3185
-    function load_state_board()
3186
-    {
3187
-        global $user;
3188
-
3189
-        $this->nb=array();
3190
-        $clause = "WHERE";
3191
-
3192
-        $sql = "SELECT count(p.rowid) as nb";
3193
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3194
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3195
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
3196
-        {
3197
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3198
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3199
-            $clause = "AND";
3200
-        }
3201
-        $sql.= " ".$clause." p.entity IN (".getEntity('propal').")";
3202
-
3203
-        $resql=$this->db->query($sql);
3204
-        if ($resql)
3205
-        {
3206
-            // This assignment in condition is not a bug. It allows walking the results.
3207
-            while ($obj=$this->db->fetch_object($resql))
3208
-            {
3209
-                $this->nb["proposals"]=$obj->nb;
3210
-            }
3211
-            $this->db->free($resql);
3212
-            return 1;
3213
-        }
3214
-        else
3215
-        {
3216
-            dol_print_error($this->db);
3217
-            $this->error=$this->db->error();
3218
-            return -1;
3219
-        }
3220
-    }
3221
-
3222
-
3223
-    /**
3224
-     *  Returns the reference to the following non used Proposal used depending on the active numbering module
3225
-     *  defined into PROPALE_ADDON
3226
-     *
3227
-     *  @param	Societe		$soc  	Object thirdparty
3228
-     *  @return string      		Reference libre pour la propale
3229
-     */
3230
-    function getNextNumRef($soc)
3231
-    {
3232
-        global $conf,$langs;
3233
-        $langs->load("propal");
3234
-
3235
-        if (! empty($conf->global->PROPALE_ADDON))
3236
-        {
3237
-        	$mybool=false;
3238
-
3239
-            $file = $conf->global->PROPALE_ADDON.".php";
3240
-            $classname = $conf->global->PROPALE_ADDON;
3241
-
3242
-            // Include file with class
3243
-            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3244
-            foreach ($dirmodels as $reldir) {
3245
-
3246
-                $dir = dol_buildpath($reldir."core/modules/propale/");
3247
-
3248
-                // Load file with numbering class (if found)
3249
-                $mybool|=@include_once $dir.$file;
3250
-            }
3251
-
3252
-            if (! $mybool)
3253
-            {
3254
-            	dol_print_error('',"Failed to include file ".$file);
3255
-            	return '';
3256
-            }
3257
-
3258
-            $obj = new $classname();
3259
-            $numref = "";
3260
-            $numref = $obj->getNextValue($soc,$this);
3261
-
3262
-            if ($numref != "")
3263
-            {
3264
-                return $numref;
3265
-            }
3266
-            else
3267
-			{
3268
-                $this->error=$obj->error;
3269
-                //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3270
-                return "";
3271
-            }
3272
-        }
3273
-        else
3274
-		{
3275
-            $langs->load("errors");
3276
-            print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
3277
-            return "";
3278
-        }
3279
-    }
3280
-
3281
-    /**
3282
-     *	Return clicable link of object (with eventually picto)
3283
-     *
3284
-     *	@param      int		$withpicto		          Add picto into link
3285
-     *	@param      string	$option			          Where point the link ('expedition', 'document', ...)
3286
-     *	@param      string	$get_params    	          Parametres added to url
3287
-     *  @param	    int   	$notooltip		          1=Disable tooltip
3288
-     *  @param      int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3289
-     *	@return     string          		          String with URL
3290
-     */
3291
-    function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1)
3292
-    {
3293
-        global $langs, $conf, $user;
3294
-
3295
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3296
-
3297
-        $result='';
3298
-        $label='';
3299
-        $url='';
3300
-
3301
-        if ($user->rights->propal->lire)
3302
-        {
3303
-            $label = '<u>' . $langs->trans("ShowPropal") . '</u>';
3304
-            if (! empty($this->ref))
3305
-                $label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3306
-            if (! empty($this->ref_client))
3307
-                $label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3308
-            if (! empty($this->total_ht))
3309
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3310
-            if (! empty($this->total_tva))
3311
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3312
-            if (! empty($this->total_ttc))
3313
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3314
-            if ($option == '') {
3315
-                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3316
-            }
3317
-            if ($option == 'compta') {  // deprecated
3318
-                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3319
-            }
3320
-            if ($option == 'expedition') {
3321
-                $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params;
3322
-            }
3323
-            if ($option == 'document') {
3324
-                $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params;
3325
-            }
3326
-
3327
-            if ($option != 'nolink')
3328
-            {
3329
-                // Add param to save lastsearch_values or not
3330
-                $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3331
-                if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3332
-                if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3333
-            }
3334
-        }
3335
-
3336
-        $linkclose='';
3337
-        if (empty($notooltip) && $user->rights->propal->lire)
3338
-        {
3339
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3340
-            {
3341
-                $label=$langs->trans("ShowPropal");
3342
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3343
-            }
3344
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3345
-            $linkclose.=' class="classfortooltip"';
3346
-        }
3347
-
3348
-        $linkstart = '<a href="'.$url.'"';
3349
-        $linkstart.=$linkclose.'>';
3350
-        $linkend='</a>';
3351
-
3352
-        if ($withpicto)
3353
-            $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3354
-        if ($withpicto && $withpicto != 2)
3355
-            $result.=' ';
3356
-        $result.=$linkstart.$this->ref.$linkend;
3357
-        return $result;
3358
-    }
3359
-
3360
-    /**
3361
-     * 	Retrieve an array of propal lines
3362
-	 *
3363
-	 * 	@return int		>0 if OK, <0 if KO
3364
-     */
3365
-    function getLinesArray()
3366
-    {
3367
-        // TODO Duplicate with fetch_lines ? Wich one to keep ?
3368
-
3369
-        $this->lines = array();
3370
-
3371
-        $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
3372
-        $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,';
3373
-        $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,';
3374
-        $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,';
3375
-	    $sql.= ' pt.fk_unit,';
3376
-        $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,';
3377
-        $sql.= ' p.entity,';
3378
-		$sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc';
3379
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt';
3380
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
3381
-        $sql.= ' WHERE pt.fk_propal = '.$this->id;
3382
-        $sql.= ' ORDER BY pt.rang ASC, pt.rowid';
3383
-
3384
-        dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
3385
-        $resql = $this->db->query($sql);
3386
-        if ($resql)
3387
-        {
3388
-            $num = $this->db->num_rows($resql);
3389
-            $i = 0;
3390
-
3391
-            while ($i < $num)
3392
-            {
3393
-                $obj = $this->db->fetch_object($resql);
3394
-
3395
-                $this->lines[$i]					= new PropaleLigne($this->db);
3396
-                $this->lines[$i]->id				= $obj->rowid; // for backward compatibility
3397
-                $this->lines[$i]->rowid				= $obj->rowid;
3398
-                $this->lines[$i]->label 			= $obj->custom_label;
3399
-                $this->lines[$i]->desc       		= $obj->description;
3400
-                $this->lines[$i]->description 		= $obj->description;
3401
-                $this->lines[$i]->fk_product		= $obj->fk_product;
3402
-                $this->lines[$i]->ref				= $obj->ref;
3403
-                $this->lines[$i]->product_ref		= $obj->ref;
3404
-                $this->lines[$i]->entity            = $obj->entity;             // Product entity
3405
-                $this->lines[$i]->product_label		= $obj->product_label;
3406
-                $this->lines[$i]->product_desc		= $obj->product_desc;
3407
-                $this->lines[$i]->product_tobatch   = $obj->product_tobatch;
3408
-                $this->lines[$i]->fk_product_type	= $obj->fk_product_type;    // deprecated
3409
-                $this->lines[$i]->product_type		= $obj->product_type;
3410
-                $this->lines[$i]->qty				= $obj->qty;
3411
-                $this->lines[$i]->subprice			= $obj->subprice;
3412
-                $this->lines[$i]->fk_remise_except 	= $obj->fk_remise_except;
3413
-                $this->lines[$i]->remise_percent	= $obj->remise_percent;
3414
-
3415
-                $this->lines[$i]->vat_src_code      = $obj->vat_src_code;
3416
-                $this->lines[$i]->tva_tx			= $obj->tva_tx;
3417
-                $this->lines[$i]->localtax1_tx		= $obj->localtax1_tx;
3418
-                $this->lines[$i]->localtax2_tx		= $obj->localtax2_tx;
3419
-                $this->lines[$i]->localtax1_type	= $obj->localtax1_type;
3420
-                $this->lines[$i]->localtax2_type	= $obj->localtax2_type;
3421
-                $this->lines[$i]->info_bits			= $obj->info_bits;
3422
-                $this->lines[$i]->total_ht			= $obj->total_ht;
3423
-                $this->lines[$i]->total_tva			= $obj->total_tva;
3424
-                $this->lines[$i]->total_ttc			= $obj->total_ttc;
3425
-                $this->lines[$i]->total_localtax1	= $obj->total_localtax1;
3426
-                $this->lines[$i]->total_localtax2	= $obj->total_localtax2;
3427
-                $this->lines[$i]->fk_fournprice		= $obj->fk_fournprice;
3391
+			while ($i < $num)
3392
+			{
3393
+				$obj = $this->db->fetch_object($resql);
3394
+
3395
+				$this->lines[$i]					= new PropaleLigne($this->db);
3396
+				$this->lines[$i]->id				= $obj->rowid; // for backward compatibility
3397
+				$this->lines[$i]->rowid				= $obj->rowid;
3398
+				$this->lines[$i]->label 			= $obj->custom_label;
3399
+				$this->lines[$i]->desc       		= $obj->description;
3400
+				$this->lines[$i]->description 		= $obj->description;
3401
+				$this->lines[$i]->fk_product		= $obj->fk_product;
3402
+				$this->lines[$i]->ref				= $obj->ref;
3403
+				$this->lines[$i]->product_ref		= $obj->ref;
3404
+				$this->lines[$i]->entity            = $obj->entity;             // Product entity
3405
+				$this->lines[$i]->product_label		= $obj->product_label;
3406
+				$this->lines[$i]->product_desc		= $obj->product_desc;
3407
+				$this->lines[$i]->product_tobatch   = $obj->product_tobatch;
3408
+				$this->lines[$i]->fk_product_type	= $obj->fk_product_type;    // deprecated
3409
+				$this->lines[$i]->product_type		= $obj->product_type;
3410
+				$this->lines[$i]->qty				= $obj->qty;
3411
+				$this->lines[$i]->subprice			= $obj->subprice;
3412
+				$this->lines[$i]->fk_remise_except 	= $obj->fk_remise_except;
3413
+				$this->lines[$i]->remise_percent	= $obj->remise_percent;
3414
+
3415
+				$this->lines[$i]->vat_src_code      = $obj->vat_src_code;
3416
+				$this->lines[$i]->tva_tx			= $obj->tva_tx;
3417
+				$this->lines[$i]->localtax1_tx		= $obj->localtax1_tx;
3418
+				$this->lines[$i]->localtax2_tx		= $obj->localtax2_tx;
3419
+				$this->lines[$i]->localtax1_type	= $obj->localtax1_type;
3420
+				$this->lines[$i]->localtax2_type	= $obj->localtax2_type;
3421
+				$this->lines[$i]->info_bits			= $obj->info_bits;
3422
+				$this->lines[$i]->total_ht			= $obj->total_ht;
3423
+				$this->lines[$i]->total_tva			= $obj->total_tva;
3424
+				$this->lines[$i]->total_ttc			= $obj->total_ttc;
3425
+				$this->lines[$i]->total_localtax1	= $obj->total_localtax1;
3426
+				$this->lines[$i]->total_localtax2	= $obj->total_localtax2;
3427
+				$this->lines[$i]->fk_fournprice		= $obj->fk_fournprice;
3428 3428
 				$marginInfos						= getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
3429 3429
 				$this->lines[$i]->pa_ht				= $marginInfos[0];
3430 3430
 				$this->lines[$i]->marge_tx			= $marginInfos[1];
3431 3431
 				$this->lines[$i]->marque_tx			= $marginInfos[2];
3432 3432
 				$this->lines[$i]->fk_parent_line	= $obj->fk_parent_line;
3433
-                $this->lines[$i]->special_code		= $obj->special_code;
3434
-                $this->lines[$i]->rang				= $obj->rang;
3435
-                $this->lines[$i]->date_start		= $this->db->jdate($obj->date_start);
3436
-                $this->lines[$i]->date_end			= $this->db->jdate($obj->date_end);
3437
-	            $this->lines[$i]->fk_unit			= $obj->fk_unit;
3433
+				$this->lines[$i]->special_code		= $obj->special_code;
3434
+				$this->lines[$i]->rang				= $obj->rang;
3435
+				$this->lines[$i]->date_start		= $this->db->jdate($obj->date_start);
3436
+				$this->lines[$i]->date_end			= $this->db->jdate($obj->date_end);
3437
+				$this->lines[$i]->fk_unit			= $obj->fk_unit;
3438 3438
 
3439 3439
 				// Multicurrency
3440 3440
 				$this->lines[$i]->fk_multicurrency 			= $obj->fk_multicurrency;
@@ -3444,18 +3444,18 @@  discard block
 block discarded – undo
3444 3444
 				$this->lines[$i]->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
3445 3445
 				$this->lines[$i]->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
3446 3446
 
3447
-                $i++;
3448
-            }
3449
-            $this->db->free($resql);
3447
+				$i++;
3448
+			}
3449
+			$this->db->free($resql);
3450 3450
 
3451
-            return 1;
3452
-        }
3453
-        else
3454
-        {
3455
-            $this->error=$this->db->error();
3456
-            return -1;
3457
-        }
3458
-    }
3451
+			return 1;
3452
+		}
3453
+		else
3454
+		{
3455
+			$this->error=$this->db->error();
3456
+			return -1;
3457
+		}
3458
+	}
3459 3459
 
3460 3460
 	/**
3461 3461
 	 *  Create a document onto disk according to template module.
@@ -3513,16 +3513,16 @@  discard block
 block discarded – undo
3513 3513
  */
3514 3514
 class PropaleLigne extends CommonObjectLine
3515 3515
 {
3516
-    public $element='propaldet';
3517
-    public $table_element='propaldet';
3516
+	public $element='propaldet';
3517
+	public $table_element='propaldet';
3518 3518
 
3519
-    var $oldline;
3519
+	var $oldline;
3520 3520
 
3521
-    // From llx_propaldet
3522
-    var $fk_propal;
3523
-    var $fk_parent_line;
3524
-    var $desc;          	// Description ligne
3525
-    var $fk_product;		// Id produit predefini
3521
+	// From llx_propaldet
3522
+	var $fk_propal;
3523
+	var $fk_parent_line;
3524
+	var $desc;          	// Description ligne
3525
+	var $fk_product;		// Id produit predefini
3526 3526
 	/**
3527 3527
 	 * @deprecated
3528 3528
 	 * @see product_type
@@ -3533,51 +3533,51 @@  discard block
 block discarded – undo
3533 3533
 	 * @var int
3534 3534
 	 * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE
3535 3535
 	 */
3536
-    var $product_type = Product::TYPE_PRODUCT;
3536
+	var $product_type = Product::TYPE_PRODUCT;
3537 3537
 
3538
-    var $qty;
3539
-    var $tva_tx;
3540
-    var $subprice;
3541
-    var $remise_percent;
3542
-    var $fk_remise_except;
3538
+	var $qty;
3539
+	var $tva_tx;
3540
+	var $subprice;
3541
+	var $remise_percent;
3542
+	var $fk_remise_except;
3543 3543
 
3544
-    var $rang = 0;
3544
+	var $rang = 0;
3545 3545
 
3546 3546
 	var $fk_fournprice;
3547 3547
 	var $pa_ht;
3548 3548
 	var $marge_tx;
3549 3549
 	var $marque_tx;
3550 3550
 
3551
-    var $special_code;	// Tag for special lines (exlusive tags)
3552
-    // 1: frais de port
3553
-    // 2: ecotaxe
3554
-    // 3: option line (when qty = 0)
3551
+	var $special_code;	// Tag for special lines (exlusive tags)
3552
+	// 1: frais de port
3553
+	// 2: ecotaxe
3554
+	// 3: option line (when qty = 0)
3555 3555
 
3556
-    var $info_bits = 0;	// Liste d'options cumulables:
3557
-    // Bit 0: 	0 si TVA normal - 1 si TVA NPR
3558
-    // Bit 1:	0 ligne normale - 1 si ligne de remise fixe
3556
+	var $info_bits = 0;	// Liste d'options cumulables:
3557
+	// Bit 0: 	0 si TVA normal - 1 si TVA NPR
3558
+	// Bit 1:	0 ligne normale - 1 si ligne de remise fixe
3559 3559
 
3560
-    var $total_ht;			// Total HT  de la ligne toute quantite et incluant la remise ligne
3561
-    var $total_tva;			// Total TVA  de la ligne toute quantite et incluant la remise ligne
3562
-    var $total_ttc;			// Total TTC de la ligne toute quantite et incluant la remise ligne
3560
+	var $total_ht;			// Total HT  de la ligne toute quantite et incluant la remise ligne
3561
+	var $total_tva;			// Total TVA  de la ligne toute quantite et incluant la remise ligne
3562
+	var $total_ttc;			// Total TTC de la ligne toute quantite et incluant la remise ligne
3563 3563
 
3564 3564
 	/**
3565 3565
 	 * @deprecated
3566 3566
 	 * @see $remise_percent, $fk_remise_except
3567 3567
 	 */
3568
-    var $remise;
3568
+	var $remise;
3569 3569
 	/**
3570 3570
 	 * @deprecated
3571 3571
 	 * @see subprice
3572 3572
 	 */
3573
-    var $price;
3573
+	var $price;
3574 3574
 
3575
-    // From llx_product
3575
+	// From llx_product
3576 3576
 	/**
3577 3577
 	 * @deprecated
3578 3578
 	 * @see product_ref
3579 3579
 	 */
3580
-    var $ref;
3580
+	var $ref;
3581 3581
 	/**
3582 3582
 	 * Product reference
3583 3583
 	 * @var string
@@ -3587,7 +3587,7 @@  discard block
 block discarded – undo
3587 3587
 	 * @deprecated
3588 3588
 	 * @see product_label
3589 3589
 	 */
3590
-    var $libelle;
3590
+	var $libelle;
3591 3591
 	/**
3592 3592
 	 *  Product label
3593 3593
 	 * @var string
@@ -3597,21 +3597,21 @@  discard block
 block discarded – undo
3597 3597
 	 * Product description
3598 3598
 	 * @var string
3599 3599
 	 */
3600
-    public $product_desc;
3600
+	public $product_desc;
3601 3601
 
3602
-    var $localtax1_tx;		// Local tax 1
3603
-    var $localtax2_tx;		// Local tax 2
3604
-    var $localtax1_type;	// Local tax 1 type
3602
+	var $localtax1_tx;		// Local tax 1
3603
+	var $localtax2_tx;		// Local tax 2
3604
+	var $localtax1_type;	// Local tax 1 type
3605 3605
 	var $localtax2_type;	// Local tax 2 type
3606
-    var $total_localtax1;  	// Line total local tax 1
3607
-    var $total_localtax2;	// Line total local tax 2
3606
+	var $total_localtax1;  	// Line total local tax 1
3607
+	var $total_localtax2;	// Line total local tax 2
3608 3608
 
3609
-    var $date_start;
3610
-    var $date_end;
3609
+	var $date_start;
3610
+	var $date_end;
3611 3611
 
3612
-    var $skip_update_total; // Skip update price total for special lines
3612
+	var $skip_update_total; // Skip update price total for special lines
3613 3613
 
3614
-    // Multicurrency
3614
+	// Multicurrency
3615 3615
 	var $fk_multicurrency;
3616 3616
 	var $multicurrency_code;
3617 3617
 	var $multicurrency_subprice;
@@ -3619,22 +3619,22 @@  discard block
 block discarded – undo
3619 3619
 	var $multicurrency_total_tva;
3620 3620
 	var $multicurrency_total_ttc;
3621 3621
 
3622
-    /**
3623
-     * 	Class line Contructor
3624
-     *
3625
-     * 	@param	DoliDB	$db	Database handler
3626
-     */
3627
-    function __construct($db)
3628
-    {
3629
-        $this->db= $db;
3630
-    }
3631
-
3632
-    /**
3633
-     *	Retrieve the propal line object
3634
-     *
3635
-     *	@param	int		$rowid		Propal line id
3636
-     *	@return	int					<0 if KO, >0 if OK
3637
-     */
3622
+	/**
3623
+	 * 	Class line Contructor
3624
+	 *
3625
+	 * 	@param	DoliDB	$db	Database handler
3626
+	 */
3627
+	function __construct($db)
3628
+	{
3629
+		$this->db= $db;
3630
+	}
3631
+
3632
+	/**
3633
+	 *	Retrieve the propal line object
3634
+	 *
3635
+	 *	@param	int		$rowid		Propal line id
3636
+	 *	@return	int					<0 if KO, >0 if OK
3637
+	 */
3638 3638
 	function fetch($rowid)
3639 3639
 	{
3640 3640
 		$sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,';
@@ -3694,7 +3694,7 @@  discard block
 block discarded – undo
3694 3694
 			$this->fk_unit          = $objp->fk_unit;
3695 3695
 
3696 3696
 			$this->date_start       = $this->db->jdate($objp->date_start);
3697
-            $this->date_end         = $this->db->jdate($objp->date_end);
3697
+			$this->date_end         = $this->db->jdate($objp->date_end);
3698 3698
 
3699 3699
 			// Multicurrency
3700 3700
 			$this->fk_multicurrency 		= $objp->fk_multicurrency;
@@ -3706,7 +3706,7 @@  discard block
 block discarded – undo
3706 3706
 
3707 3707
 			$this->db->free($result);
3708 3708
 
3709
-            return 1;
3709
+			return 1;
3710 3710
 		}
3711 3711
 		else
3712 3712
 		{
@@ -3714,45 +3714,45 @@  discard block
 block discarded – undo
3714 3714
 		}
3715 3715
 	}
3716 3716
 
3717
-    /**
3718
-     *  Insert object line propal in database
3719
-     *
3720
-     *	@param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
3721
-     *	@return		int						<0 if KO, >0 if OK
3722
-     */
3723
-    function insert($notrigger=0)
3724
-    {
3725
-        global $conf,$user;
3717
+	/**
3718
+	 *  Insert object line propal in database
3719
+	 *
3720
+	 *	@param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
3721
+	 *	@return		int						<0 if KO, >0 if OK
3722
+	 */
3723
+	function insert($notrigger=0)
3724
+	{
3725
+		global $conf,$user;
3726 3726
 
3727
-        $error=0;
3727
+		$error=0;
3728 3728
 
3729
-        dol_syslog(get_class($this)."::insert rang=".$this->rang);
3729
+		dol_syslog(get_class($this)."::insert rang=".$this->rang);
3730 3730
 
3731
-        $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3731
+		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3732 3732
 
3733
-        // Clean parameters
3734
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3735
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3736
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3737
-        if (empty($this->localtax1_type)) $this->localtax1_type=0;
3733
+		// Clean parameters
3734
+		if (empty($this->tva_tx)) $this->tva_tx=0;
3735
+		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3736
+		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3737
+		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3738 3738
 		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3739
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3740
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3741
-        if (empty($this->rang)) $this->rang=0;
3742
-        if (empty($this->remise)) $this->remise=0;
3743
-        if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0;
3744
-        if (empty($this->info_bits)) $this->info_bits=0;
3745
-        if (empty($this->special_code)) $this->special_code=0;
3746
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3747
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3739
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
3740
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
3741
+		if (empty($this->rang)) $this->rang=0;
3742
+		if (empty($this->remise)) $this->remise=0;
3743
+		if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0;
3744
+		if (empty($this->info_bits)) $this->info_bits=0;
3745
+		if (empty($this->special_code)) $this->special_code=0;
3746
+		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3747
+		if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3748 3748
 		if (! is_numeric($this->qty)) $this->qty = 0;
3749
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3750
-        if (empty($this->multicurrency_subprice))  $this->multicurrency_subprice=0;
3751
-        if (empty($this->multicurrency_total_ht))  $this->multicurrency_total_ht=0;
3752
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
3753
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
3749
+		if (empty($this->pa_ht)) $this->pa_ht=0;
3750
+		if (empty($this->multicurrency_subprice))  $this->multicurrency_subprice=0;
3751
+		if (empty($this->multicurrency_total_ht))  $this->multicurrency_total_ht=0;
3752
+		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
3753
+		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
3754 3754
 
3755
-       // if buy price not defined, define buyprice as configured in margin admin
3755
+	   // if buy price not defined, define buyprice as configured in margin admin
3756 3756
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
3757 3757
 		{
3758 3758
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
@@ -3765,183 +3765,183 @@  discard block
 block discarded – undo
3765 3765
 			}
3766 3766
 		}
3767 3767
 
3768
-        // Check parameters
3769
-        if ($this->product_type < 0) return -1;
3768
+		// Check parameters
3769
+		if ($this->product_type < 0) return -1;
3770 3770
 
3771
-        $this->db->begin();
3771
+		$this->db->begin();
3772 3772
 
3773
-        // Insert line into database
3774
-        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet';
3775
-        $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
3773
+		// Insert line into database
3774
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet';
3775
+		$sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
3776 3776
 		$sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3777
-        $sql.= ' subprice, remise_percent, ';
3778
-        $sql.= ' info_bits, ';
3779
-        $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
3780
-	    $sql.= ' fk_unit,';
3781
-        $sql.= ' date_start, date_end';
3777
+		$sql.= ' subprice, remise_percent, ';
3778
+		$sql.= ' info_bits, ';
3779
+		$sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
3780
+		$sql.= ' fk_unit,';
3781
+		$sql.= ' date_start, date_end';
3782 3782
 		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)';
3783
-        $sql.= " VALUES (".$this->fk_propal.",";
3784
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3785
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
3786
-        $sql.= " '".$this->db->escape($this->desc)."',";
3787
-        $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").",";
3788
-        $sql.= " '".$this->db->escape($this->product_type)."',";
3789
-        $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").",";
3790
-        $sql.= " ".price2num($this->qty).",";
3791
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3792
-        $sql.= " ".price2num($this->tva_tx).",";
3793
-        $sql.= " ".price2num($this->localtax1_tx).",";
3794
-        $sql.= " ".price2num($this->localtax2_tx).",";
3783
+		$sql.= " VALUES (".$this->fk_propal.",";
3784
+		$sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3785
+		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
3786
+		$sql.= " '".$this->db->escape($this->desc)."',";
3787
+		$sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").",";
3788
+		$sql.= " '".$this->db->escape($this->product_type)."',";
3789
+		$sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").",";
3790
+		$sql.= " ".price2num($this->qty).",";
3791
+		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3792
+		$sql.= " ".price2num($this->tva_tx).",";
3793
+		$sql.= " ".price2num($this->localtax1_tx).",";
3794
+		$sql.= " ".price2num($this->localtax2_tx).",";
3795 3795
 		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
3796 3796
 		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
3797
-        $sql.= " ".($this->subprice?price2num($this->subprice):"null").",";
3798
-        $sql.= " ".price2num($this->remise_percent).",";
3799
-        $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").",";
3800
-        $sql.= " ".price2num($this->total_ht).",";
3801
-        $sql.= " ".price2num($this->total_tva).",";
3802
-        $sql.= " ".price2num($this->total_localtax1).",";
3803
-        $sql.= " ".price2num($this->total_localtax2).",";
3804
-        $sql.= " ".price2num($this->total_ttc).",";
3805
-        $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").",";
3806
-        $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").",";
3807
-        $sql.= ' '.$this->special_code.',';
3808
-        $sql.= ' '.$this->rang.',';
3809
-	    $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).',';
3810
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
3811
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3797
+		$sql.= " ".($this->subprice?price2num($this->subprice):"null").",";
3798
+		$sql.= " ".price2num($this->remise_percent).",";
3799
+		$sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").",";
3800
+		$sql.= " ".price2num($this->total_ht).",";
3801
+		$sql.= " ".price2num($this->total_tva).",";
3802
+		$sql.= " ".price2num($this->total_localtax1).",";
3803
+		$sql.= " ".price2num($this->total_localtax2).",";
3804
+		$sql.= " ".price2num($this->total_ttc).",";
3805
+		$sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").",";
3806
+		$sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").",";
3807
+		$sql.= ' '.$this->special_code.',';
3808
+		$sql.= ' '.$this->rang.',';
3809
+		$sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).',';
3810
+		$sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
3811
+		$sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3812 3812
 		$sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null');
3813 3813
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3814 3814
 		$sql.= ", ".$this->multicurrency_subprice;
3815 3815
 		$sql.= ", ".$this->multicurrency_total_ht;
3816 3816
 		$sql.= ", ".$this->multicurrency_total_tva;
3817 3817
 		$sql.= ", ".$this->multicurrency_total_ttc;
3818
-        $sql.= ')';
3819
-
3820
-        dol_syslog(get_class($this).'::insert', LOG_DEBUG);
3821
-        $resql=$this->db->query($sql);
3822
-        if ($resql)
3823
-        {
3824
-            $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
3825
-
3826
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3827
-            {
3828
-            	$this->id=$this->rowid;
3829
-            	$result=$this->insertExtraFields();
3830
-            	if ($result < 0)
3831
-            	{
3832
-            		$error++;
3833
-            	}
3834
-            }
3835
-
3836
-            if (! $notrigger)
3837
-            {
3838
-                // Call trigger
3839
-                $result=$this->call_trigger('LINEPROPAL_INSERT',$user);
3840
-                if ($result < 0)
3841
-                {
3842
-                    $this->db->rollback();
3843
-                    return -1;
3844
-                }
3845
-                // End call triggers
3846
-            }
3847
-
3848
-            $this->db->commit();
3849
-            return 1;
3850
-        }
3851
-        else
3852
-        {
3853
-            $this->error=$this->db->error()." sql=".$sql;
3854
-            $this->db->rollback();
3855
-            return -1;
3856
-        }
3857
-    }
3858
-
3859
-    /**
3860
-     * 	Delete line in database
3861
-     *
3862
-     *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3863
-     *	@return	 int  <0 if ko, >0 if ok
3864
-     */
3865
-    function delete($notrigger=0)
3866
-    {
3867
-        global $conf,$user;
3868
-
3869
-        $error=0;
3870
-        $this->db->begin();
3871
-
3872
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid;
3873
-        dol_syslog("PropaleLigne::delete", LOG_DEBUG);
3874
-        if ($this->db->query($sql) )
3875
-        {
3876
-
3877
-        	// Remove extrafields
3878
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3879
-        	{
3880
-        		$this->id=$this->rowid;
3881
-        		$result=$this->deleteExtraFields();
3882
-        		if ($result < 0)
3883
-        		{
3884
-        			$error++;
3885
-        			dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3886
-        		}
3887
-        	}
3888
-
3889
-        	if (! $error && ! $notrigger)
3890
-        	{
3891
-	            // Call trigger
3892
-	            $result=$this->call_trigger('LINEPROPAL_DELETE',$user);
3893
-	            if ($result < 0)
3894
-	            {
3895
-	                $this->db->rollback();
3896
-	                return -1;
3897
-	            }
3898
-        	}
3899
-            // End call triggers
3900
-
3901
-            $this->db->commit();
3902
-
3903
-            return 1;
3904
-        }
3905
-        else
3906
-        {
3907
-            $this->error=$this->db->error()." sql=".$sql;
3908
-            $this->db->rollback();
3909
-            return -1;
3910
-        }
3911
-    }
3912
-
3913
-    /**
3914
-     *	Update propal line object into DB
3915
-     *
3916
-     *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3917
-     *	@return	int					<0 if ko, >0 if ok
3918
-     */
3919
-    function update($notrigger=0)
3920
-    {
3921
-        global $conf,$user;
3922
-
3923
-        $error=0;
3924
-
3925
-        $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3926
-
3927
-        // Clean parameters
3928
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3929
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3930
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3931
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3932
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3818
+		$sql.= ')';
3819
+
3820
+		dol_syslog(get_class($this).'::insert', LOG_DEBUG);
3821
+		$resql=$this->db->query($sql);
3822
+		if ($resql)
3823
+		{
3824
+			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
3825
+
3826
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3827
+			{
3828
+				$this->id=$this->rowid;
3829
+				$result=$this->insertExtraFields();
3830
+				if ($result < 0)
3831
+				{
3832
+					$error++;
3833
+				}
3834
+			}
3835
+
3836
+			if (! $notrigger)
3837
+			{
3838
+				// Call trigger
3839
+				$result=$this->call_trigger('LINEPROPAL_INSERT',$user);
3840
+				if ($result < 0)
3841
+				{
3842
+					$this->db->rollback();
3843
+					return -1;
3844
+				}
3845
+				// End call triggers
3846
+			}
3847
+
3848
+			$this->db->commit();
3849
+			return 1;
3850
+		}
3851
+		else
3852
+		{
3853
+			$this->error=$this->db->error()." sql=".$sql;
3854
+			$this->db->rollback();
3855
+			return -1;
3856
+		}
3857
+	}
3858
+
3859
+	/**
3860
+	 * 	Delete line in database
3861
+	 *
3862
+	 *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3863
+	 *	@return	 int  <0 if ko, >0 if ok
3864
+	 */
3865
+	function delete($notrigger=0)
3866
+	{
3867
+		global $conf,$user;
3868
+
3869
+		$error=0;
3870
+		$this->db->begin();
3871
+
3872
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid;
3873
+		dol_syslog("PropaleLigne::delete", LOG_DEBUG);
3874
+		if ($this->db->query($sql) )
3875
+		{
3876
+
3877
+			// Remove extrafields
3878
+			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3879
+			{
3880
+				$this->id=$this->rowid;
3881
+				$result=$this->deleteExtraFields();
3882
+				if ($result < 0)
3883
+				{
3884
+					$error++;
3885
+					dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3886
+				}
3887
+			}
3888
+
3889
+			if (! $error && ! $notrigger)
3890
+			{
3891
+				// Call trigger
3892
+				$result=$this->call_trigger('LINEPROPAL_DELETE',$user);
3893
+				if ($result < 0)
3894
+				{
3895
+					$this->db->rollback();
3896
+					return -1;
3897
+				}
3898
+			}
3899
+			// End call triggers
3900
+
3901
+			$this->db->commit();
3902
+
3903
+			return 1;
3904
+		}
3905
+		else
3906
+		{
3907
+			$this->error=$this->db->error()." sql=".$sql;
3908
+			$this->db->rollback();
3909
+			return -1;
3910
+		}
3911
+	}
3912
+
3913
+	/**
3914
+	 *	Update propal line object into DB
3915
+	 *
3916
+	 *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3917
+	 *	@return	int					<0 if ko, >0 if ok
3918
+	 */
3919
+	function update($notrigger=0)
3920
+	{
3921
+		global $conf,$user;
3922
+
3923
+		$error=0;
3924
+
3925
+		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3926
+
3927
+		// Clean parameters
3928
+		if (empty($this->tva_tx)) $this->tva_tx=0;
3929
+		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3930
+		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3931
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
3932
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
3933 3933
 		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3934 3934
 		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3935
-        if (empty($this->marque_tx)) $this->marque_tx=0;
3936
-        if (empty($this->marge_tx)) $this->marge_tx=0;
3937
-        if (empty($this->price)) $this->price=0;	// TODO A virer
3938
-        if (empty($this->remise)) $this->remise=0;	// TODO A virer
3939
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3940
-        if (empty($this->info_bits)) $this->info_bits=0;
3941
-        if (empty($this->special_code)) $this->special_code=0;
3942
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3943
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3944
-        if (empty($this->subprice)) $this->subprice=0;
3935
+		if (empty($this->marque_tx)) $this->marque_tx=0;
3936
+		if (empty($this->marge_tx)) $this->marge_tx=0;
3937
+		if (empty($this->price)) $this->price=0;	// TODO A virer
3938
+		if (empty($this->remise)) $this->remise=0;	// TODO A virer
3939
+		if (empty($this->remise_percent)) $this->remise_percent=0;
3940
+		if (empty($this->info_bits)) $this->info_bits=0;
3941
+		if (empty($this->special_code)) $this->special_code=0;
3942
+		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3943
+		if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3944
+		if (empty($this->subprice)) $this->subprice=0;
3945 3945
 		if (empty($this->pa_ht)) $this->pa_ht=0;
3946 3946
 
3947 3947
 		// if buy price not defined, define buyprice as configured in margin admin
@@ -3957,119 +3957,119 @@  discard block
 block discarded – undo
3957 3957
 			}
3958 3958
 		}
3959 3959
 
3960
-        $this->db->begin();
3960
+		$this->db->begin();
3961 3961
 
3962
-        // Mise a jour ligne en base
3963
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
3964
-        $sql.= " description='".$this->db->escape($this->desc)."'";
3965
-        $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
3966
-        $sql.= ", product_type=".$this->product_type;
3962
+		// Mise a jour ligne en base
3963
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
3964
+		$sql.= " description='".$this->db->escape($this->desc)."'";
3965
+		$sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
3966
+		$sql.= ", product_type=".$this->product_type;
3967 3967
 		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
3968
-        $sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3969
-        $sql.= ", localtax1_tx=".price2num($this->localtax1_tx);
3970
-        $sql.= ", localtax2_tx=".price2num($this->localtax2_tx);
3968
+		$sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3969
+		$sql.= ", localtax1_tx=".price2num($this->localtax1_tx);
3970
+		$sql.= ", localtax2_tx=".price2num($this->localtax2_tx);
3971 3971
 		$sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3972 3972
 		$sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3973
-        $sql.= ", qty='".price2num($this->qty)."'";
3974
-        $sql.= ", subprice=".price2num($this->subprice)."";
3975
-        $sql.= ", remise_percent=".price2num($this->remise_percent)."";
3976
-        $sql.= ", price=".price2num($this->price)."";					// TODO A virer
3977
-        $sql.= ", remise=".price2num($this->remise)."";				// TODO A virer
3978
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3979
-        if (empty($this->skip_update_total))
3980
-        {
3981
-            $sql.= ", total_ht=".price2num($this->total_ht)."";
3982
-            $sql.= ", total_tva=".price2num($this->total_tva)."";
3983
-            $sql.= ", total_ttc=".price2num($this->total_ttc)."";
3984
-            $sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
3985
-            $sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
3986
-        }
3973
+		$sql.= ", qty='".price2num($this->qty)."'";
3974
+		$sql.= ", subprice=".price2num($this->subprice)."";
3975
+		$sql.= ", remise_percent=".price2num($this->remise_percent)."";
3976
+		$sql.= ", price=".price2num($this->price)."";					// TODO A virer
3977
+		$sql.= ", remise=".price2num($this->remise)."";				// TODO A virer
3978
+		$sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3979
+		if (empty($this->skip_update_total))
3980
+		{
3981
+			$sql.= ", total_ht=".price2num($this->total_ht)."";
3982
+			$sql.= ", total_tva=".price2num($this->total_tva)."";
3983
+			$sql.= ", total_ttc=".price2num($this->total_ttc)."";
3984
+			$sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
3985
+			$sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
3986
+		}
3987 3987
 		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
3988 3988
 		$sql.= ", buy_price_ht=".price2num($this->pa_ht);
3989
-        if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code;
3990
-        $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
3991
-        if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
3992
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3993
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3994
-	    $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3989
+		if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code;
3990
+		$sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
3991
+		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
3992
+		$sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3993
+		$sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3994
+		$sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3995 3995
 
3996 3996
 		// Multicurrency
3997 3997
 		$sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3998
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3999
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4000
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4001
-
4002
-        $sql.= " WHERE rowid = ".$this->rowid;
4003
-
4004
-        dol_syslog(get_class($this)."::update", LOG_DEBUG);
4005
-        $resql=$this->db->query($sql);
4006
-        if ($resql)
4007
-        {
4008
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4009
-        	{
4010
-        		$this->id=$this->rowid;
4011
-        		$result=$this->insertExtraFields();
4012
-        		if ($result < 0)
4013
-        		{
4014
-        			$error++;
4015
-        		}
4016
-        	}
4017
-
4018
-            if (! $notrigger)
4019
-            {
4020
-                // Call trigger
4021
-                $result=$this->call_trigger('LINEPROPAL_UPDATE',$user);
4022
-                if ($result < 0)
4023
-                {
4024
-                    $this->db->rollback();
4025
-                    return -1;
4026
-                }
4027
-                // End call triggers
4028
-            }
4029
-
4030
-            $this->db->commit();
4031
-            return 1;
4032
-        }
4033
-        else
4034
-        {
4035
-            $this->error=$this->db->error();
4036
-            $this->db->rollback();
4037
-            return -2;
4038
-        }
4039
-    }
4040
-
4041
-    /**
4042
-     *	Update DB line fields total_xxx
4043
-     *	Used by migration
4044
-     *
4045
-     *	@return		int		<0 if ko, >0 if ok
4046
-     */
4047
-    function update_total()
4048
-    {
4049
-        $this->db->begin();
4050
-
4051
-        // Mise a jour ligne en base
4052
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
4053
-        $sql.= " total_ht=".price2num($this->total_ht,'MT')."";
4054
-        $sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
4055
-        $sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
4056
-        $sql.= " WHERE rowid = ".$this->rowid;
4057
-
4058
-        dol_syslog("PropaleLigne::update_total", LOG_DEBUG);
4059
-
4060
-        $resql=$this->db->query($sql);
4061
-        if ($resql)
4062
-        {
4063
-            $this->db->commit();
4064
-            return 1;
4065
-        }
4066
-        else
4067
-        {
4068
-            $this->error=$this->db->error();
4069
-            $this->db->rollback();
4070
-            return -2;
4071
-        }
4072
-    }
3998
+		$sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3999
+		$sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4000
+		$sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4001
+
4002
+		$sql.= " WHERE rowid = ".$this->rowid;
4003
+
4004
+		dol_syslog(get_class($this)."::update", LOG_DEBUG);
4005
+		$resql=$this->db->query($sql);
4006
+		if ($resql)
4007
+		{
4008
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4009
+			{
4010
+				$this->id=$this->rowid;
4011
+				$result=$this->insertExtraFields();
4012
+				if ($result < 0)
4013
+				{
4014
+					$error++;
4015
+				}
4016
+			}
4017
+
4018
+			if (! $notrigger)
4019
+			{
4020
+				// Call trigger
4021
+				$result=$this->call_trigger('LINEPROPAL_UPDATE',$user);
4022
+				if ($result < 0)
4023
+				{
4024
+					$this->db->rollback();
4025
+					return -1;
4026
+				}
4027
+				// End call triggers
4028
+			}
4029
+
4030
+			$this->db->commit();
4031
+			return 1;
4032
+		}
4033
+		else
4034
+		{
4035
+			$this->error=$this->db->error();
4036
+			$this->db->rollback();
4037
+			return -2;
4038
+		}
4039
+	}
4040
+
4041
+	/**
4042
+	 *	Update DB line fields total_xxx
4043
+	 *	Used by migration
4044
+	 *
4045
+	 *	@return		int		<0 if ko, >0 if ok
4046
+	 */
4047
+	function update_total()
4048
+	{
4049
+		$this->db->begin();
4050
+
4051
+		// Mise a jour ligne en base
4052
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
4053
+		$sql.= " total_ht=".price2num($this->total_ht,'MT')."";
4054
+		$sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
4055
+		$sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
4056
+		$sql.= " WHERE rowid = ".$this->rowid;
4057
+
4058
+		dol_syslog("PropaleLigne::update_total", LOG_DEBUG);
4059
+
4060
+		$resql=$this->db->query($sql);
4061
+		if ($resql)
4062
+		{
4063
+			$this->db->commit();
4064
+			return 1;
4065
+		}
4066
+		else
4067
+		{
4068
+			$this->error=$this->db->error();
4069
+			$this->db->rollback();
4070
+			return -2;
4071
+		}
4072
+	}
4073 4073
 
4074 4074
 }
4075 4075
 
Please login to merge, or discard this patch.
Spacing   +1050 added lines, -1050 removed lines patch added patch discarded remove patch
@@ -32,24 +32,24 @@  discard block
 block discarded – undo
32 32
  *	\brief      File of class to manage proposals
33 33
  */
34 34
 
35
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
36
-require_once DOL_DOCUMENT_ROOT ."/core/class/commonobjectline.class.php";
37
-require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php';
38
-require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
39
-require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php';
40
-require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php';
35
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
36
+require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
37
+require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
38
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
39
+require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
40
+require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
41 41
 
42 42
 /**
43 43
  *	Class to manage proposals
44 44
  */
45 45
 class Propal extends CommonObject
46 46
 {
47
-    public $element='propal';
48
-    public $table_element='propal';
49
-    public $table_element_line='propaldet';
50
-    public $fk_element='fk_propal';
51
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
-    public $picto='propal';
47
+    public $element = 'propal';
48
+    public $table_element = 'propal';
49
+    public $table_element_line = 'propaldet';
50
+    public $fk_element = 'fk_propal';
51
+    protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
+    public $picto = 'propal';
53 53
 
54 54
     /**
55 55
      * {@inheritdoc}
@@ -144,8 +144,8 @@  discard block
 block discarded – undo
144 144
     public $demand_reason_id;
145 145
     public $demand_reason_code;
146 146
 
147
-    public $products=array();
148
-    public $extraparams=array();
147
+    public $products = array();
148
+    public $extraparams = array();
149 149
 
150 150
 	/**
151 151
 	 * @var PropaleLigne[]
@@ -153,8 +153,8 @@  discard block
 block discarded – undo
153 153
     public $lines = array();
154 154
     public $line;
155 155
 
156
-    public $labelstatut=array();
157
-    public $labelstatut_short=array();
156
+    public $labelstatut = array();
157
+    public $labelstatut_short = array();
158 158
 
159 159
     public $specimen;
160 160
 
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	/**
188 188
 	 * Billed or processed quote
189 189
 	 */
190
-	const STATUS_BILLED = 4;   // Todo rename into STATUS_CLOSE ?
190
+	const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
191 191
 
192 192
     /**
193 193
      *	Constructor
@@ -196,9 +196,9 @@  discard block
 block discarded – undo
196 196
      *	@param      int		$socid		Id third party
197 197
      *	@param      int		$propalid   Id proposal
198 198
      */
199
-    function __construct($db, $socid="", $propalid=0)
199
+    function __construct($db, $socid = "", $propalid = 0)
200 200
     {
201
-        global $conf,$langs;
201
+        global $conf, $langs;
202 202
 
203 203
         $this->db = $db;
204 204
         $this->socid = $socid;
@@ -208,19 +208,19 @@  discard block
 block discarded – undo
208 208
         $this->remise_percent = 0;
209 209
         $this->remise_absolue = 0;
210 210
 
211
-        $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION;
211
+        $this->duree_validite = $conf->global->PROPALE_VALIDITY_DURATION;
212 212
 
213 213
         $langs->load("propal");
214
-        $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft"));
215
-        $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated"));
216
-        $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned"));
217
-        $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned"));
218
-        $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled"));
219
-        $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort"));
220
-        $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened"));
221
-        $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort"));
222
-        $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort"));
223
-        $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort"));
214
+        $this->labelstatut[0] = (!empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft"));
215
+        $this->labelstatut[1] = (!empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated"));
216
+        $this->labelstatut[2] = (!empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned"));
217
+        $this->labelstatut[3] = (!empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned"));
218
+        $this->labelstatut[4] = (!empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled"));
219
+        $this->labelstatut_short[0] = (!empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort"));
220
+        $this->labelstatut_short[1] = (!empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened"));
221
+        $this->labelstatut_short[2] = (!empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort"));
222
+        $this->labelstatut_short[3] = (!empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort"));
223
+        $this->labelstatut_short[4] = (!empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort"));
224 224
     }
225 225
 
226 226
 
@@ -236,30 +236,30 @@  discard block
 block discarded – undo
236 236
      *	TODO	Replace calls to this function by generation objet Ligne
237 237
      *			inserted into table $this->products
238 238
      */
239
-    function add_product($idproduct, $qty, $remise_percent=0)
239
+    function add_product($idproduct, $qty, $remise_percent = 0)
240 240
     {
241 241
         global $conf, $mysoc;
242 242
 
243
-        if (! $qty) $qty = 1;
243
+        if (!$qty) $qty = 1;
244 244
 
245 245
         dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
246 246
         if ($idproduct > 0)
247 247
         {
248
-            $prod=new Product($this->db);
248
+            $prod = new Product($this->db);
249 249
             $prod->fetch($idproduct);
250 250
 
251 251
             $productdesc = $prod->description;
252 252
 
253
-            $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
254
-            $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
255
-            if (empty($tva_tx)) $tva_npr=0;
256
-            $vat_src_code = '';     // May be defined into tva_tx
253
+            $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
254
+            $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
255
+            if (empty($tva_tx)) $tva_npr = 0;
256
+            $vat_src_code = ''; // May be defined into tva_tx
257 257
 
258
-            $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr);
259
-            $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr);
258
+            $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
259
+            $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
260 260
 
261 261
             // multiprices
262
-            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
262
+            if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
263 263
             {
264 264
                 $price = $prod->multiprices[$this->thirdparty->price_level];
265 265
             }
@@ -270,17 +270,17 @@  discard block
 block discarded – undo
270 270
 
271 271
             $line = new PropaleLigne($this->db);
272 272
 
273
-            $line->fk_product=$idproduct;
274
-            $line->desc=$productdesc;
275
-            $line->qty=$qty;
276
-            $line->subprice=$price;
277
-            $line->remise_percent=$remise_percent;
278
-            $line->vat_src_code=$vat_src_code;
279
-            $line->tva_tx=$tva_tx;
280
-	        $line->fk_unit=$prod->fk_unit;
273
+            $line->fk_product = $idproduct;
274
+            $line->desc = $productdesc;
275
+            $line->qty = $qty;
276
+            $line->subprice = $price;
277
+            $line->remise_percent = $remise_percent;
278
+            $line->vat_src_code = $vat_src_code;
279
+            $line->tva_tx = $tva_tx;
280
+	        $line->fk_unit = $prod->fk_unit;
281 281
 			if ($tva_npr) $line->info_bits = 1;
282 282
 
283
-            $this->lines[]=$line;
283
+            $this->lines[] = $line;
284 284
         }
285 285
     }
286 286
 
@@ -299,46 +299,46 @@  discard block
 block discarded – undo
299 299
 
300 300
         $this->db->begin();
301 301
 
302
-        $remise=new DiscountAbsolute($this->db);
303
-        $result=$remise->fetch($idremise);
302
+        $remise = new DiscountAbsolute($this->db);
303
+        $result = $remise->fetch($idremise);
304 304
 
305 305
         if ($result > 0)
306 306
         {
307 307
             if ($remise->fk_facture)	// Protection against multiple submission
308 308
             {
309
-                $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
309
+                $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
310 310
                 $this->db->rollback();
311 311
                 return -5;
312 312
             }
313 313
 
314
-            $line=new PropaleLigne($this->db);
314
+            $line = new PropaleLigne($this->db);
315 315
 
316 316
             $this->line->context = $this->context;
317 317
 
318
-            $line->fk_propal=$this->id;
319
-            $line->fk_remise_except=$remise->id;
320
-            $line->desc=$remise->description;   	// Description ligne
321
-            $line->vat_src_code=$remise->vat_src_code;
322
-            $line->tva_tx=$remise->tva_tx;
323
-            $line->subprice=-$remise->amount_ht;
324
-            $line->fk_product=0;					// Id produit predefined
325
-            $line->qty=1;
326
-            $line->remise=0;
327
-            $line->remise_percent=0;
328
-            $line->rang=-1;
329
-            $line->info_bits=2;
318
+            $line->fk_propal = $this->id;
319
+            $line->fk_remise_except = $remise->id;
320
+            $line->desc = $remise->description; // Description ligne
321
+            $line->vat_src_code = $remise->vat_src_code;
322
+            $line->tva_tx = $remise->tva_tx;
323
+            $line->subprice = -$remise->amount_ht;
324
+            $line->fk_product = 0; // Id produit predefined
325
+            $line->qty = 1;
326
+            $line->remise = 0;
327
+            $line->remise_percent = 0;
328
+            $line->rang = -1;
329
+            $line->info_bits = 2;
330 330
 
331 331
             // TODO deprecated
332
-            $line->price=-$remise->amount_ht;
332
+            $line->price = -$remise->amount_ht;
333 333
 
334 334
             $line->total_ht  = -$remise->amount_ht;
335 335
             $line->total_tva = -$remise->amount_tva;
336 336
             $line->total_ttc = -$remise->amount_ttc;
337 337
 
338
-            $result=$line->insert();
338
+            $result = $line->insert();
339 339
             if ($result > 0)
340 340
             {
341
-                $result=$this->update_price(1);
341
+                $result = $this->update_price(1);
342 342
                 if ($result > 0)
343 343
                 {
344 344
                     $this->db->commit();
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
             }
353 353
             else
354 354
             {
355
-                $this->error=$line->error;
355
+                $this->error = $line->error;
356 356
                 $this->db->rollback();
357 357
                 return -2;
358 358
             }
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
      *    	@return    	int         	    			>0 if OK, <0 if KO
401 401
      *    	@see       	add_product
402 402
      */
403
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0)
403
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $fk_remise_except = 0)
404 404
     {
405 405
     	global $mysoc, $conf, $langs;
406 406
 
@@ -408,27 +408,27 @@  discard block
 block discarded – undo
408 408
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
409 409
 
410 410
         // Clean parameters
411
-        if (empty($remise_percent)) $remise_percent=0;
412
-        if (empty($qty)) $qty=0;
413
-        if (empty($info_bits)) $info_bits=0;
414
-        if (empty($rang)) $rang=0;
415
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
416
-
417
-        $remise_percent=price2num($remise_percent);
418
-        $qty=price2num($qty);
419
-        $pu_ht=price2num($pu_ht);
420
-        $pu_ttc=price2num($pu_ttc);
421
-        $txtva=price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
422
-        $txlocaltax1=price2num($txlocaltax1);
423
-        $txlocaltax2=price2num($txlocaltax2);
424
-    	$pa_ht=price2num($pa_ht);
425
-        if ($price_base_type=='HT')
426
-        {
427
-            $pu=$pu_ht;
411
+        if (empty($remise_percent)) $remise_percent = 0;
412
+        if (empty($qty)) $qty = 0;
413
+        if (empty($info_bits)) $info_bits = 0;
414
+        if (empty($rang)) $rang = 0;
415
+        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
416
+
417
+        $remise_percent = price2num($remise_percent);
418
+        $qty = price2num($qty);
419
+        $pu_ht = price2num($pu_ht);
420
+        $pu_ttc = price2num($pu_ttc);
421
+        $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
422
+        $txlocaltax1 = price2num($txlocaltax1);
423
+        $txlocaltax2 = price2num($txlocaltax2);
424
+    	$pa_ht = price2num($pa_ht);
425
+        if ($price_base_type == 'HT')
426
+        {
427
+            $pu = $pu_ht;
428 428
         }
429 429
         else
430 430
         {
431
-            $pu=$pu_ttc;
431
+            $pu = $pu_ttc;
432 432
         }
433 433
 
434 434
         // Check parameters
@@ -438,16 +438,16 @@  discard block
 block discarded – undo
438 438
         {
439 439
             $this->db->begin();
440 440
 
441
-        	$product_type=$type;
441
+        	$product_type = $type;
442 442
 			if (!empty($fk_product))
443 443
 			{
444
-				$product=new Product($this->db);
445
-				$result=$product->fetch($fk_product);
446
-				$product_type=$product->type;
444
+				$product = new Product($this->db);
445
+				$result = $product->fetch($fk_product);
446
+				$product_type = $product->type;
447 447
 
448
-				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) {
448
+				if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) {
449 449
                     $langs->load("errors");
450
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
450
+				    $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
451 451
 					$this->db->rollback();
452 452
 					return -3;
453 453
 				}
@@ -458,17 +458,17 @@  discard block
 block discarded – undo
458 458
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
459 459
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
460 460
 
461
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
461
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
462 462
 
463 463
             // Clean vat code
464
-            $vat_src_code='';
464
+            $vat_src_code = '';
465 465
             if (preg_match('/\((.*)\)/', $txtva, $reg))
466 466
             {
467 467
                 $vat_src_code = $reg[1];
468
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
468
+                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
469 469
             }
470 470
 
471
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
471
+            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
472 472
 
473 473
             $total_ht  = $tabprice[0];
474 474
             $total_tva = $tabprice[1];
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
 			$pu_ttc = $tabprice[5];
481 481
 
482 482
 			// MultiCurrency
483
-			$multicurrency_total_ht  = $tabprice[16];
483
+			$multicurrency_total_ht = $tabprice[16];
484 484
             $multicurrency_total_tva = $tabprice[17];
485 485
             $multicurrency_total_ttc = $tabprice[18];
486 486
 			$pu_ht_devise = $tabprice[19];
@@ -504,39 +504,39 @@  discard block
 block discarded – undo
504 504
             }
505 505
 
506 506
             // Insert line
507
-            $this->line=new PropaleLigne($this->db);
507
+            $this->line = new PropaleLigne($this->db);
508 508
 
509 509
             $this->line->context = $this->context;
510 510
 
511
-            $this->line->fk_propal=$this->id;
512
-            $this->line->label=$label;
513
-            $this->line->desc=$desc;
514
-            $this->line->qty=$qty;
511
+            $this->line->fk_propal = $this->id;
512
+            $this->line->label = $label;
513
+            $this->line->desc = $desc;
514
+            $this->line->qty = $qty;
515 515
 
516
-			$this->line->vat_src_code=$vat_src_code;
517
-            $this->line->tva_tx=$txtva;
518
-            $this->line->localtax1_tx=$txlocaltax1;
519
-            $this->line->localtax2_tx=$txlocaltax2;
516
+			$this->line->vat_src_code = $vat_src_code;
517
+            $this->line->tva_tx = $txtva;
518
+            $this->line->localtax1_tx = $txlocaltax1;
519
+            $this->line->localtax2_tx = $txlocaltax2;
520 520
 			$this->line->localtax1_type = $localtaxes_type[0];
521 521
 			$this->line->localtax2_type = $localtaxes_type[2];
522
-            $this->line->fk_product=$fk_product;
523
-            $this->line->product_type=$type;
524
-            $this->line->fk_remise_except=$fk_remise_except;
525
-            $this->line->remise_percent=$remise_percent;
526
-            $this->line->subprice=$pu_ht;
527
-            $this->line->rang=$rangtouse;
528
-            $this->line->info_bits=$info_bits;
529
-            $this->line->total_ht=$total_ht;
530
-            $this->line->total_tva=$total_tva;
531
-            $this->line->total_localtax1=$total_localtax1;
532
-            $this->line->total_localtax2=$total_localtax2;
533
-            $this->line->total_ttc=$total_ttc;
534
-            $this->line->special_code=$special_code;
535
-            $this->line->fk_parent_line=$fk_parent_line;
536
-            $this->line->fk_unit=$fk_unit;
537
-
538
-            $this->line->date_start=$date_start;
539
-            $this->line->date_end=$date_end;
522
+            $this->line->fk_product = $fk_product;
523
+            $this->line->product_type = $type;
524
+            $this->line->fk_remise_except = $fk_remise_except;
525
+            $this->line->remise_percent = $remise_percent;
526
+            $this->line->subprice = $pu_ht;
527
+            $this->line->rang = $rangtouse;
528
+            $this->line->info_bits = $info_bits;
529
+            $this->line->total_ht = $total_ht;
530
+            $this->line->total_tva = $total_tva;
531
+            $this->line->total_localtax1 = $total_localtax1;
532
+            $this->line->total_localtax2 = $total_localtax2;
533
+            $this->line->total_ttc = $total_ttc;
534
+            $this->line->special_code = $special_code;
535
+            $this->line->fk_parent_line = $fk_parent_line;
536
+            $this->line->fk_unit = $fk_unit;
537
+
538
+            $this->line->date_start = $date_start;
539
+            $this->line->date_end = $date_end;
540 540
 
541 541
 			$this->line->fk_fournprice = $fk_fournprice;
542 542
 			$this->line->pa_ht = $pa_ht;
@@ -545,32 +545,32 @@  discard block
 block discarded – undo
545 545
             $this->line->origin = $origin;
546 546
 
547 547
 			// Multicurrency
548
-			$this->line->fk_multicurrency			= $this->fk_multicurrency;
549
-			$this->line->multicurrency_code			= $this->multicurrency_code;
548
+			$this->line->fk_multicurrency = $this->fk_multicurrency;
549
+			$this->line->multicurrency_code = $this->multicurrency_code;
550 550
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
551 551
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
552 552
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
553 553
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
554 554
 
555 555
             // Mise en option de la ligne
556
-            if (empty($qty) && empty($special_code)) $this->line->special_code=3;
556
+            if (empty($qty) && empty($special_code)) $this->line->special_code = 3;
557 557
 
558 558
             // TODO deprecated
559
-            $this->line->price=$price;
560
-            $this->line->remise=$remise;
559
+            $this->line->price = $price;
560
+            $this->line->remise = $remise;
561 561
 
562
-            if (is_array($array_options) && count($array_options)>0) {
563
-            	$this->line->array_options=$array_options;
562
+            if (is_array($array_options) && count($array_options) > 0) {
563
+            	$this->line->array_options = $array_options;
564 564
             }
565 565
 
566
-            $result=$this->line->insert();
566
+            $result = $this->line->insert();
567 567
             if ($result > 0)
568 568
             {
569 569
                 // Reorder if child line
570
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
570
+                if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
571 571
 
572 572
                 // Mise a jour informations denormalisees au niveau de la propale meme
573
-                $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
573
+                $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
574 574
                 if ($result > 0)
575 575
                 {
576 576
                     $this->db->commit();
@@ -578,14 +578,14 @@  discard block
 block discarded – undo
578 578
                 }
579 579
                 else
580 580
                 {
581
-                    $this->error=$this->db->error();
581
+                    $this->error = $this->db->error();
582 582
                     $this->db->rollback();
583 583
                     return -1;
584 584
                 }
585 585
             }
586 586
             else
587 587
             {
588
-                $this->error=$this->line->error;
588
+                $this->error = $this->line->error;
589 589
                 $this->db->rollback();
590 590
                 return -2;
591 591
             }
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
 	 * 	@param		int			$notrigger			disable line update trigger
622 622
      *  @return     int     		        		0 if OK, <0 if KO
623 623
      */
624
-	function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
624
+	function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0)
625 625
     {
626 626
         global $mysoc;
627 627
 
@@ -630,16 +630,16 @@  discard block
 block discarded – undo
630 630
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
631 631
 
632 632
         // Clean parameters
633
-        $remise_percent=price2num($remise_percent);
634
-        $qty=price2num($qty);
633
+        $remise_percent = price2num($remise_percent);
634
+        $qty = price2num($qty);
635 635
         $pu = price2num($pu);
636 636
         $txtva = price2num($txtva);
637
-        $txlocaltax1=price2num($txlocaltax1);
638
-        $txlocaltax2=price2num($txlocaltax2);
639
-    	$pa_ht=price2num($pa_ht);
640
-        if (empty($qty) && empty($special_code)) $special_code=3;    // Set option tag
641
-        if (! empty($qty) && $special_code == 3) $special_code=0;    // Remove option tag
642
-        if (empty($type)) $type=0;
637
+        $txlocaltax1 = price2num($txlocaltax1);
638
+        $txlocaltax2 = price2num($txlocaltax2);
639
+    	$pa_ht = price2num($pa_ht);
640
+        if (empty($qty) && empty($special_code)) $special_code = 3; // Set option tag
641
+        if (!empty($qty) && $special_code == 3) $special_code = 0; // Remove option tag
642
+        if (empty($type)) $type = 0;
643 643
 
644 644
         if ($this->statut == self::STATUS_DRAFT)
645 645
         {
@@ -650,17 +650,17 @@  discard block
 block discarded – undo
650 650
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
651 651
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
652 652
 
653
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
653
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
654 654
 
655 655
             // Clean vat code
656
-            $vat_src_code='';
656
+            $vat_src_code = '';
657 657
             if (preg_match('/\((.*)\)/', $txtva, $reg))
658 658
             {
659 659
                 $vat_src_code = $reg[1];
660
-                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
660
+                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
661 661
             }
662 662
 
663
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
663
+            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
664 664
             $total_ht  = $tabprice[0];
665 665
             $total_tva = $tabprice[1];
666 666
             $total_ttc = $tabprice[2];
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 			$pu_ttc = $tabprice[5];
672 672
 
673 673
 			// MultiCurrency
674
-			$multicurrency_total_ht  = $tabprice[16];
674
+			$multicurrency_total_ht = $tabprice[16];
675 675
             $multicurrency_total_tva = $tabprice[17];
676 676
             $multicurrency_total_ttc = $tabprice[18];
677 677
 			$pu_ht_devise = $tabprice[19];
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
             $this->line->context = $this->context;
697 697
 
698 698
             // Reorder if fk_parent_line change
699
-            if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
699
+            if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
700 700
             {
701 701
                 $rangmax = $this->line_max($fk_parent_line);
702 702
                 $this->line->rang = $rangmax + 1;
@@ -704,16 +704,16 @@  discard block
 block discarded – undo
704 704
 
705 705
             $this->line->rowid				= $rowid;
706 706
             $this->line->label				= $label;
707
-            $this->line->desc				= $desc;
708
-            $this->line->qty				= $qty;
707
+            $this->line->desc = $desc;
708
+            $this->line->qty = $qty;
709 709
             $this->line->product_type		= $type;
710 710
             $this->line->vat_src_code		= $vat_src_code;
711
-            $this->line->tva_tx				= $txtva;
711
+            $this->line->tva_tx = $txtva;
712 712
             $this->line->localtax1_tx		= $txlocaltax1;
713 713
             $this->line->localtax2_tx		= $txlocaltax2;
714 714
 			$this->line->localtax1_type		= $localtaxes_type[0];
715 715
 			$this->line->localtax2_type		= $localtaxes_type[2];
716
-            $this->line->remise_percent		= $remise_percent;
716
+            $this->line->remise_percent = $remise_percent;
717 717
             $this->line->subprice			= $pu_ht;
718 718
             $this->line->info_bits			= $info_bits;
719 719
 
@@ -722,23 +722,23 @@  discard block
 block discarded – undo
722 722
             $this->line->total_localtax1	= $total_localtax1;
723 723
             $this->line->total_localtax2	= $total_localtax2;
724 724
             $this->line->total_ttc			= $total_ttc;
725
-            $this->line->special_code		= $special_code;
725
+            $this->line->special_code = $special_code;
726 726
             $this->line->fk_parent_line		= $fk_parent_line;
727
-            $this->line->skip_update_total	= $skip_update_total;
728
-            $this->line->fk_unit	= $fk_unit;
727
+            $this->line->skip_update_total = $skip_update_total;
728
+            $this->line->fk_unit = $fk_unit;
729 729
 
730 730
 			$this->line->fk_fournprice = $fk_fournprice;
731 731
             $this->line->pa_ht = $pa_ht;
732 732
 
733
-            $this->line->date_start=$date_start;
734
-            $this->line->date_end=$date_end;
733
+            $this->line->date_start = $date_start;
734
+            $this->line->date_end = $date_end;
735 735
 
736 736
             // TODO deprecated
737
-            $this->line->price=$price;
738
-            $this->line->remise=$remise;
737
+            $this->line->price = $price;
738
+            $this->line->remise = $remise;
739 739
 
740
-            if (is_array($array_options) && count($array_options)>0) {
741
-            	$this->line->array_options=$array_options;
740
+            if (is_array($array_options) && count($array_options) > 0) {
741
+            	$this->line->array_options = $array_options;
742 742
             }
743 743
 
744 744
 			// Multicurrency
@@ -747,11 +747,11 @@  discard block
 block discarded – undo
747 747
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
748 748
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
749 749
 
750
-            $result=$this->line->update($notrigger);
750
+            $result = $this->line->update($notrigger);
751 751
             if ($result > 0)
752 752
             {
753 753
                 // Reorder if child line
754
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
754
+                if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
755 755
 
756 756
                 $this->update_price(1);
757 757
 
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
             }
764 764
             else
765 765
             {
766
-                $this->error=$this->line->error;
766
+                $this->error = $this->line->error;
767 767
 
768 768
                 $this->db->rollback();
769 769
                 return -1;
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
     {
788 788
         if ($this->statut == self::STATUS_DRAFT)
789 789
         {
790
-            $line=new PropaleLigne($this->db);
790
+            $line = new PropaleLigne($this->db);
791 791
 
792 792
             // For triggers
793 793
             $line->fetch($lineid);
@@ -818,21 +818,21 @@  discard block
 block discarded – undo
818 818
      * 	@param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
819 819
      *  @return     int     			<0 if KO, >=0 if OK
820 820
      */
821
-    function create($user, $notrigger=0)
821
+    function create($user, $notrigger = 0)
822 822
     {
823
-        global $conf,$hookmanager;
824
-        $error=0;
823
+        global $conf, $hookmanager;
824
+        $error = 0;
825 825
 
826
-        $now=dol_now();
826
+        $now = dol_now();
827 827
 
828 828
         // Clean parameters
829
-        if (empty($this->date)) $this->date=$this->datep;
829
+        if (empty($this->date)) $this->date = $this->datep;
830 830
         $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
831
-        if (empty($this->availability_id)) $this->availability_id=0;
832
-        if (empty($this->demand_reason_id)) $this->demand_reason_id=0;
831
+        if (empty($this->availability_id)) $this->availability_id = 0;
832
+        if (empty($this->demand_reason_id)) $this->demand_reason_id = 0;
833 833
 
834 834
 		// Multicurrency
835
-		if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
835
+		if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
836 836
 		if (empty($this->fk_multicurrency))
837 837
 		{
838 838
 			$this->multicurrency_code = $conf->currency;
@@ -843,22 +843,22 @@  discard block
 block discarded – undo
843 843
         dol_syslog(get_class($this)."::create");
844 844
 
845 845
         // Check parameters
846
-        $result=$this->fetch_thirdparty();
846
+        $result = $this->fetch_thirdparty();
847 847
         if ($result < 0)
848 848
         {
849
-            $this->error="Failed to fetch company";
849
+            $this->error = "Failed to fetch company";
850 850
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
851 851
             return -3;
852 852
         }
853 853
 
854 854
         // Check parameters
855
-		if (! empty($this->ref))	// We check that ref is not already used
855
+		if (!empty($this->ref))	// We check that ref is not already used
856 856
 		{
857
-			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
857
+			$result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
858 858
 			if ($result > 0)
859 859
 			{
860
-				$this->error='ErrorRefAlreadyExists';
861
-				dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
860
+				$this->error = 'ErrorRefAlreadyExists';
861
+				dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
862 862
 				$this->db->rollback();
863 863
 				return -1;
864 864
 			}
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 
867 867
         if (empty($this->date))
868 868
         {
869
-            $this->error="Date of proposal is required";
869
+            $this->error = "Date of proposal is required";
870 870
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
871 871
             return -4;
872 872
         }
@@ -876,94 +876,94 @@  discard block
 block discarded – undo
876 876
 
877 877
         // Insert into database
878 878
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal (";
879
-        $sql.= "fk_soc";
880
-        $sql.= ", price";
881
-        $sql.= ", remise";
882
-        $sql.= ", remise_percent";
883
-        $sql.= ", remise_absolue";
884
-        $sql.= ", tva";
885
-        $sql.= ", total";
886
-        $sql.= ", datep";
887
-        $sql.= ", datec";
888
-        $sql.= ", ref";
889
-        $sql.= ", fk_user_author";
890
-        $sql.= ", note_private";
891
-        $sql.= ", note_public";
892
-        $sql.= ", model_pdf";
893
-        $sql.= ", fin_validite";
894
-        $sql.= ", fk_cond_reglement";
895
-        $sql.= ", fk_mode_reglement";
896
-        $sql.= ", fk_account";
897
-        $sql.= ", ref_client";
898
-        $sql.= ", date_livraison";
899
-        $sql.= ", fk_shipping_method";
900
-        $sql.= ", fk_availability";
901
-        $sql.= ", fk_input_reason";
902
-        $sql.= ", fk_projet";
903
-        $sql.= ", fk_incoterms";
904
-        $sql.= ", location_incoterms";
905
-        $sql.= ", entity";
906
-        $sql.= ", fk_multicurrency";
907
-        $sql.= ", multicurrency_code";
908
-        $sql.= ", multicurrency_tx";
909
-        $sql.= ") ";
910
-        $sql.= " VALUES (";
911
-        $sql.= $this->socid;
912
-        $sql.= ", 0";
913
-        $sql.= ", ".$this->remise;
914
-        $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL');
915
-        $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL');
916
-        $sql.= ", 0";
917
-        $sql.= ", 0";
918
-        $sql.= ", '".$this->db->idate($this->date)."'";
919
-        $sql.= ", '".$this->db->idate($now)."'";
920
-        $sql.= ", '(PROV)'";
921
-        $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL");
922
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
923
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
924
-        $sql.= ", '".$this->db->escape($this->modelpdf)."'";
925
-        $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL");
926
-        $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
927
-        $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
928
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
929
-        $sql.= ", '".$this->db->escape($this->ref_client)."'";
930
-        $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL");
931
-        $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
932
-        $sql.= ", ".$this->availability_id;
933
-        $sql.= ", ".$this->demand_reason_id;
934
-        $sql.= ", ".($this->fk_project?$this->fk_project:"null");
935
-        $sql.= ", ".(int) $this->fk_incoterms;
936
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
937
-        $sql.= ", ".$conf->entity;
938
-		$sql.= ", ".(int) $this->fk_multicurrency;
939
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
940
-		$sql.= ", ".(double) $this->multicurrency_tx;
941
-        $sql.= ")";
879
+        $sql .= "fk_soc";
880
+        $sql .= ", price";
881
+        $sql .= ", remise";
882
+        $sql .= ", remise_percent";
883
+        $sql .= ", remise_absolue";
884
+        $sql .= ", tva";
885
+        $sql .= ", total";
886
+        $sql .= ", datep";
887
+        $sql .= ", datec";
888
+        $sql .= ", ref";
889
+        $sql .= ", fk_user_author";
890
+        $sql .= ", note_private";
891
+        $sql .= ", note_public";
892
+        $sql .= ", model_pdf";
893
+        $sql .= ", fin_validite";
894
+        $sql .= ", fk_cond_reglement";
895
+        $sql .= ", fk_mode_reglement";
896
+        $sql .= ", fk_account";
897
+        $sql .= ", ref_client";
898
+        $sql .= ", date_livraison";
899
+        $sql .= ", fk_shipping_method";
900
+        $sql .= ", fk_availability";
901
+        $sql .= ", fk_input_reason";
902
+        $sql .= ", fk_projet";
903
+        $sql .= ", fk_incoterms";
904
+        $sql .= ", location_incoterms";
905
+        $sql .= ", entity";
906
+        $sql .= ", fk_multicurrency";
907
+        $sql .= ", multicurrency_code";
908
+        $sql .= ", multicurrency_tx";
909
+        $sql .= ") ";
910
+        $sql .= " VALUES (";
911
+        $sql .= $this->socid;
912
+        $sql .= ", 0";
913
+        $sql .= ", ".$this->remise;
914
+        $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'NULL');
915
+        $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'NULL');
916
+        $sql .= ", 0";
917
+        $sql .= ", 0";
918
+        $sql .= ", '".$this->db->idate($this->date)."'";
919
+        $sql .= ", '".$this->db->idate($now)."'";
920
+        $sql .= ", '(PROV)'";
921
+        $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "NULL");
922
+        $sql .= ", '".$this->db->escape($this->note_private)."'";
923
+        $sql .= ", '".$this->db->escape($this->note_public)."'";
924
+        $sql .= ", '".$this->db->escape($this->modelpdf)."'";
925
+        $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
926
+        $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
927
+        $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
928
+        $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
929
+        $sql .= ", '".$this->db->escape($this->ref_client)."'";
930
+        $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "NULL");
931
+        $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
932
+        $sql .= ", ".$this->availability_id;
933
+        $sql .= ", ".$this->demand_reason_id;
934
+        $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
935
+        $sql .= ", ".(int) $this->fk_incoterms;
936
+        $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
937
+        $sql .= ", ".$conf->entity;
938
+		$sql .= ", ".(int) $this->fk_multicurrency;
939
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
940
+		$sql .= ", ".(double) $this->multicurrency_tx;
941
+        $sql .= ")";
942 942
 
943 943
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
944
-        $resql=$this->db->query($sql);
944
+        $resql = $this->db->query($sql);
945 945
         if ($resql)
946 946
         {
947 947
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal");
948 948
 
949 949
             if ($this->id)
950 950
             {
951
-                $this->ref='(PROV'.$this->id.')';
951
+                $this->ref = '(PROV'.$this->id.')';
952 952
                 $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
953 953
 
954 954
                 dol_syslog(get_class($this)."::create", LOG_DEBUG);
955
-                $resql=$this->db->query($sql);
956
-                if (! $resql) $error++;
955
+                $resql = $this->db->query($sql);
956
+                if (!$resql) $error++;
957 957
 
958 958
                 /*
959 959
                  *  Insertion du detail des produits dans la base
960 960
                 */
961
-                if (! $error)
961
+                if (!$error)
962 962
                 {
963
-                    $fk_parent_line=0;
964
-                    $num=count($this->lines);
963
+                    $fk_parent_line = 0;
964
+                    $num = count($this->lines);
965 965
 
966
-                    for ($i=0;$i<$num;$i++)
966
+                    for ($i = 0; $i < $num; $i++)
967 967
                     {
968 968
                         // Reset fk_parent_line for line that are not child lines or special product
969 969
                         if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
                         if ($result < 0)
1001 1001
                         {
1002 1002
                             $error++;
1003
-                            $this->error=$this->db->error;
1003
+                            $this->error = $this->db->error;
1004 1004
                             dol_print_error($this->db);
1005 1005
                             break;
1006 1006
                         }
@@ -1012,41 +1012,41 @@  discard block
 block discarded – undo
1012 1012
                 }
1013 1013
 
1014 1014
                 // Add linked object
1015
-                if (! $error && $this->origin && $this->origin_id)
1015
+                if (!$error && $this->origin && $this->origin_id)
1016 1016
                 {
1017 1017
                     $ret = $this->add_object_linked();
1018
-                    if (! $ret)	dol_print_error($this->db);
1018
+                    if (!$ret)	dol_print_error($this->db);
1019 1019
                 }
1020 1020
 
1021 1021
                 // Set delivery address
1022
-                if (! $error && $this->fk_delivery_address)
1022
+                if (!$error && $this->fk_delivery_address)
1023 1023
                 {
1024 1024
                     $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1025
-                    $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address;
1026
-                    $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'";
1027
-                    $sql.= " AND entity = ".$conf->entity;
1025
+                    $sql .= " SET fk_delivery_address = ".$this->fk_delivery_address;
1026
+                    $sql .= " WHERE ref = '".$this->db->escape($this->ref)."'";
1027
+                    $sql .= " AND entity = ".$conf->entity;
1028 1028
 
1029
-                    $result=$this->db->query($sql);
1029
+                    $result = $this->db->query($sql);
1030 1030
                 }
1031 1031
 
1032
-                if (! $error)
1032
+                if (!$error)
1033 1033
                 {
1034 1034
                     // Mise a jour infos denormalisees
1035
-                    $resql=$this->update_price(1);
1035
+                    $resql = $this->update_price(1);
1036 1036
                     if ($resql)
1037 1037
                     {
1038
-                    	$action='update';
1038
+                    	$action = 'update';
1039 1039
 
1040 1040
                     	// Actions on extra fields (by external module or standard code)
1041 1041
                     	// TODO le hook fait double emploi avec le trigger !!
1042 1042
                     	$hookmanager->initHooks(array('propaldao'));
1043
-                    	$parameters=array('socid'=>$this->id);
1044
-                    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1043
+                    	$parameters = array('socid'=>$this->id);
1044
+                    	$reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1045 1045
                     	if (empty($reshook))
1046 1046
                     	{
1047 1047
                     		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1048 1048
                     		{
1049
-                    			$result=$this->insertExtraFields();
1049
+                    			$result = $this->insertExtraFields();
1050 1050
                     			if ($result < 0)
1051 1051
                     			{
1052 1052
                     				$error++;
@@ -1055,28 +1055,28 @@  discard block
 block discarded – undo
1055 1055
                     	}
1056 1056
                     	else if ($reshook < 0) $error++;
1057 1057
 
1058
-                        if (! $notrigger)
1058
+                        if (!$notrigger)
1059 1059
                         {
1060 1060
                             // Call trigger
1061
-                            $result=$this->call_trigger('PROPAL_CREATE',$user);
1061
+                            $result = $this->call_trigger('PROPAL_CREATE', $user);
1062 1062
                             if ($result < 0) { $error++; }
1063 1063
                             // End call triggers
1064 1064
                         }
1065 1065
                     }
1066 1066
                     else
1067 1067
 					{
1068
-                        $this->error=$this->db->lasterror();
1068
+                        $this->error = $this->db->lasterror();
1069 1069
                         $error++;
1070 1070
                     }
1071 1071
                 }
1072 1072
             }
1073 1073
             else
1074 1074
 			{
1075
-                $this->error=$this->db->lasterror();
1075
+                $this->error = $this->db->lasterror();
1076 1076
                 $error++;
1077 1077
             }
1078 1078
 
1079
-            if (! $error)
1079
+            if (!$error)
1080 1080
             {
1081 1081
                 $this->db->commit();
1082 1082
                 dol_syslog(get_class($this)."::create done id=".$this->id);
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
         }
1091 1091
         else
1092 1092
         {
1093
-            $this->error=$this->db->lasterror();
1093
+            $this->error = $this->db->lasterror();
1094 1094
             $this->db->rollback();
1095 1095
             return -1;
1096 1096
         }
@@ -1107,7 +1107,7 @@  discard block
 block discarded – undo
1107 1107
     function create_from($user)
1108 1108
     {
1109 1109
     	// i love this function because $this->products is not used in create function...
1110
-        $this->products=$this->lines;
1110
+        $this->products = $this->lines;
1111 1111
 
1112 1112
         return $this->create($user);
1113 1113
     }
@@ -1118,37 +1118,37 @@  discard block
 block discarded – undo
1118 1118
      *		@param		int				$socid			Id of thirdparty
1119 1119
      * 	 	@return		int								New id of clone
1120 1120
      */
1121
-    function createFromClone($socid=0)
1121
+    function createFromClone($socid = 0)
1122 1122
     {
1123
-        global $user,$conf,$hookmanager;
1123
+        global $user, $conf, $hookmanager;
1124 1124
 
1125 1125
 		dol_include_once('/projet/class/project.class.php');
1126 1126
 
1127
-        $this->context['createfromclone']='createfromclone';
1127
+        $this->context['createfromclone'] = 'createfromclone';
1128 1128
 
1129
-        $error=0;
1130
-        $now=dol_now();
1129
+        $error = 0;
1130
+        $now = dol_now();
1131 1131
 
1132 1132
         $this->db->begin();
1133 1133
 
1134 1134
 		// get extrafields so they will be clone
1135
-		foreach($this->lines as $line)
1135
+		foreach ($this->lines as $line)
1136 1136
 			$line->fetch_optionals($line->rowid);
1137 1137
 
1138 1138
         // Load dest object
1139 1139
         $clonedObj = clone $this;
1140 1140
 
1141
-        $objsoc=new Societe($this->db);
1141
+        $objsoc = new Societe($this->db);
1142 1142
 
1143 1143
         // Change socid if needed
1144
-        if (! empty($socid) && $socid != $clonedObj->socid)
1144
+        if (!empty($socid) && $socid != $clonedObj->socid)
1145 1145
         {
1146 1146
             if ($objsoc->fetch($socid) > 0)
1147 1147
             {
1148
-                $clonedObj->socid 				= $objsoc->id;
1149
-                $clonedObj->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1150
-                $clonedObj->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1151
-                $clonedObj->fk_delivery_address	= '';
1148
+                $clonedObj->socid = $objsoc->id;
1149
+                $clonedObj->cond_reglement_id	= (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1150
+                $clonedObj->mode_reglement_id	= (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1151
+                $clonedObj->fk_delivery_address = '';
1152 1152
 
1153 1153
                 /*if (!empty($conf->projet->enabled))
1154 1154
                 {
@@ -1160,11 +1160,11 @@  discard block
 block discarded – undo
1160 1160
     					$clonedObj->fk_project = '';
1161 1161
     				}
1162 1162
                 }*/
1163
-                $clonedObj->fk_project = '';    // A cloned proposal is set by default to no project.
1163
+                $clonedObj->fk_project = ''; // A cloned proposal is set by default to no project.
1164 1164
             }
1165 1165
 
1166 1166
             // reset ref_client
1167
-            $clonedObj->ref_client  = '';
1167
+            $clonedObj->ref_client = '';
1168 1168
 
1169 1169
             // TODO Change product price if multi-prices
1170 1170
         }
@@ -1173,21 +1173,21 @@  discard block
 block discarded – undo
1173 1173
             $objsoc->fetch($clonedObj->socid);
1174 1174
         }
1175 1175
 
1176
-        $clonedObj->id=0;
1177
-        $clonedObj->ref='';
1178
-        $clonedObj->statut=self::STATUS_DRAFT;
1176
+        $clonedObj->id = 0;
1177
+        $clonedObj->ref = '';
1178
+        $clonedObj->statut = self::STATUS_DRAFT;
1179 1179
 
1180 1180
         // Clear fields
1181
-        $clonedObj->user_author	= $user->id;
1182
-        $clonedObj->user_valid	= '';
1183
-        $clonedObj->date		= $now;
1184
-        $clonedObj->datep		= $now;    // deprecated
1185
-        $clonedObj->fin_validite	= $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600);
1186
-        if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client	= '';
1181
+        $clonedObj->user_author = $user->id;
1182
+        $clonedObj->user_valid = '';
1183
+        $clonedObj->date = $now;
1184
+        $clonedObj->datep = $now; // deprecated
1185
+        $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600);
1186
+        if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = '';
1187 1187
 
1188 1188
         // Create clone
1189 1189
 
1190
-        $result=$clonedObj->create($user);
1190
+        $result = $clonedObj->create($user);
1191 1191
         if ($result < 0) $error++;
1192 1192
         else
1193 1193
         {
@@ -1203,19 +1203,19 @@  discard block
 block discarded – undo
1203 1203
             }
1204 1204
         }
1205 1205
 
1206
-        if (! $error)
1206
+        if (!$error)
1207 1207
         {
1208 1208
             // Hook of thirdparty module
1209 1209
             if (is_object($hookmanager))
1210 1210
             {
1211
-                $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj);
1212
-                $action='';
1213
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action);    // Note that $action and $object may have been modified by some hooks
1211
+                $parameters = array('objFrom'=>$this, 'clonedObj'=>$clonedObj);
1212
+                $action = '';
1213
+                $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
1214 1214
                 if ($reshook < 0) $error++;
1215 1215
             }
1216 1216
 
1217 1217
             // Call trigger
1218
-            $result=$clonedObj->call_trigger('PROPAL_CLONE',$user);
1218
+            $result = $clonedObj->call_trigger('PROPAL_CLONE', $user);
1219 1219
             if ($result < 0) { $error++; }
1220 1220
             // End call triggers
1221 1221
         }
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
         unset($this->context['createfromclone']);
1224 1224
 
1225 1225
         // End
1226
-        if (! $error)
1226
+        if (!$error)
1227 1227
         {
1228 1228
             $this->db->commit();
1229 1229
             return $clonedObj->id;
@@ -1242,48 +1242,48 @@  discard block
 block discarded – undo
1242 1242
      *	@param		string		$ref		Ref of proposal
1243 1243
      *	@return     int         			>0 if OK, <0 if KO
1244 1244
      */
1245
-    function fetch($rowid,$ref='')
1245
+    function fetch($rowid, $ref = '')
1246 1246
     {
1247 1247
 
1248 1248
         $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
1249
-        $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
1250
-        $sql.= ", p.datec";
1251
-        $sql.= ", p.date_valid as datev";
1252
-        $sql.= ", p.datep as dp";
1253
-        $sql.= ", p.fin_validite as dfv";
1254
-        $sql.= ", p.date_livraison as date_livraison";
1255
-        $sql.= ", p.model_pdf, p.ref_client, p.extraparams";
1256
-        $sql.= ", p.note_private, p.note_public";
1257
-        $sql.= ", p.fk_projet, p.fk_statut";
1258
-        $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1259
-        $sql.= ", p.fk_delivery_address";
1260
-        $sql.= ", p.fk_availability";
1261
-        $sql.= ", p.fk_input_reason";
1262
-        $sql.= ", p.fk_cond_reglement";
1263
-        $sql.= ", p.fk_mode_reglement";
1264
-        $sql.= ', p.fk_account';
1265
-        $sql.= ", p.fk_shipping_method";
1266
-        $sql.= ", p.fk_incoterms, p.location_incoterms";
1267
-		$sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1268
-        $sql.= ", i.libelle as libelle_incoterms";
1269
-        $sql.= ", c.label as statut_label";
1270
-        $sql.= ", ca.code as availability_code, ca.label as availability";
1271
-        $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason";
1272
-        $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
1273
-        $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1274
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p";
1275
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')';
1276
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')';
1277
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1278
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1279
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1280
-        $sql.= " WHERE p.fk_statut = c.id";
1281
-        $sql.= " AND p.entity IN (".getEntity('propal').")";
1282
-        if ($ref) $sql.= " AND p.ref='".$ref."'";
1283
-        else $sql.= " AND p.rowid=".$rowid;
1249
+        $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
1250
+        $sql .= ", p.datec";
1251
+        $sql .= ", p.date_valid as datev";
1252
+        $sql .= ", p.datep as dp";
1253
+        $sql .= ", p.fin_validite as dfv";
1254
+        $sql .= ", p.date_livraison as date_livraison";
1255
+        $sql .= ", p.model_pdf, p.ref_client, p.extraparams";
1256
+        $sql .= ", p.note_private, p.note_public";
1257
+        $sql .= ", p.fk_projet, p.fk_statut";
1258
+        $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1259
+        $sql .= ", p.fk_delivery_address";
1260
+        $sql .= ", p.fk_availability";
1261
+        $sql .= ", p.fk_input_reason";
1262
+        $sql .= ", p.fk_cond_reglement";
1263
+        $sql .= ", p.fk_mode_reglement";
1264
+        $sql .= ', p.fk_account';
1265
+        $sql .= ", p.fk_shipping_method";
1266
+        $sql .= ", p.fk_incoterms, p.location_incoterms";
1267
+		$sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1268
+        $sql .= ", i.libelle as libelle_incoterms";
1269
+        $sql .= ", c.label as statut_label";
1270
+        $sql .= ", ca.code as availability_code, ca.label as availability";
1271
+        $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
1272
+        $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
1273
+        $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1274
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p";
1275
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
1276
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
1277
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1278
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1279
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1280
+        $sql .= " WHERE p.fk_statut = c.id";
1281
+        $sql .= " AND p.entity IN (".getEntity('propal').")";
1282
+        if ($ref) $sql .= " AND p.ref='".$ref."'";
1283
+        else $sql .= " AND p.rowid=".$rowid;
1284 1284
 
1285 1285
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1286
-        $resql=$this->db->query($sql);
1286
+        $resql = $this->db->query($sql);
1287 1287
         if ($resql)
1288 1288
         {
1289 1289
             if ($this->db->num_rows($resql))
@@ -1314,31 +1314,31 @@  discard block
 block discarded – undo
1314 1314
 
1315 1315
                 $this->datec                = $this->db->jdate($obj->datec); // TODO deprecated
1316 1316
                 $this->datev                = $this->db->jdate($obj->datev); // TODO deprecated
1317
-                $this->date_creation		= $this->db->jdate($obj->datec); //Creation date
1318
-                $this->date_validation		= $this->db->jdate($obj->datev); //Validation date
1319
-                $this->date                 = $this->db->jdate($obj->dp);	// Proposal date
1320
-                $this->datep                = $this->db->jdate($obj->dp);    // deprecated
1317
+                $this->date_creation = $this->db->jdate($obj->datec); //Creation date
1318
+                $this->date_validation = $this->db->jdate($obj->datev); //Validation date
1319
+                $this->date                 = $this->db->jdate($obj->dp); // Proposal date
1320
+                $this->datep                = $this->db->jdate($obj->dp); // deprecated
1321 1321
                 $this->fin_validite         = $this->db->jdate($obj->dfv);
1322 1322
                 $this->date_livraison       = $this->db->jdate($obj->date_livraison);
1323
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1323
+                $this->shipping_method_id   = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1324 1324
                 $this->availability_id      = $obj->fk_availability;
1325 1325
                 $this->availability_code    = $obj->availability_code;
1326 1326
                 $this->availability         = $obj->availability;
1327 1327
                 $this->demand_reason_id     = $obj->fk_input_reason;
1328 1328
                 $this->demand_reason_code   = $obj->demand_reason_code;
1329 1329
                 $this->demand_reason        = $obj->demand_reason;
1330
-                $this->fk_address  			= $obj->fk_delivery_address;
1330
+                $this->fk_address = $obj->fk_delivery_address;
1331 1331
 
1332 1332
                 $this->mode_reglement_id    = $obj->fk_mode_reglement;
1333 1333
                 $this->mode_reglement_code  = $obj->mode_reglement_code;
1334 1334
                 $this->mode_reglement       = $obj->mode_reglement;
1335
-                $this->fk_account           = ($obj->fk_account>0)?$obj->fk_account:null;
1335
+                $this->fk_account           = ($obj->fk_account > 0) ? $obj->fk_account : null;
1336 1336
                 $this->cond_reglement_id    = $obj->fk_cond_reglement;
1337 1337
                 $this->cond_reglement_code  = $obj->cond_reglement_code;
1338 1338
                 $this->cond_reglement       = $obj->cond_reglement;
1339 1339
                 $this->cond_reglement_doc   = $obj->cond_reglement_libelle_doc;
1340 1340
 
1341
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
1341
+                $this->extraparams = (array) json_decode($obj->extraparams, true);
1342 1342
 
1343 1343
                 $this->user_author_id = $obj->fk_user_author;
1344 1344
                 $this->user_valid_id  = $obj->fk_user_valid;
@@ -1351,9 +1351,9 @@  discard block
 block discarded – undo
1351 1351
 
1352 1352
 				// Multicurrency
1353 1353
 				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1354
-				$this->multicurrency_code 		= $obj->multicurrency_code;
1354
+				$this->multicurrency_code = $obj->multicurrency_code;
1355 1355
 				$this->multicurrency_tx 		= $obj->multicurrency_tx;
1356
-				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1356
+				$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1357 1357
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1358 1358
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1359 1359
 
@@ -1365,9 +1365,9 @@  discard block
 block discarded – undo
1365 1365
                 // Retreive all extrafield for invoice
1366 1366
                 // fetch optionals attributes and labels
1367 1367
                 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1368
-                $extrafields=new ExtraFields($this->db);
1369
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1370
-                $this->fetch_optionals($this->id,$extralabels);
1368
+                $extrafields = new ExtraFields($this->db);
1369
+                $extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true);
1370
+                $this->fetch_optionals($this->id, $extralabels);
1371 1371
 
1372 1372
                 $this->db->free($resql);
1373 1373
 
@@ -1376,7 +1376,7 @@  discard block
 block discarded – undo
1376 1376
                 /*
1377 1377
                  * Lines
1378 1378
                  */
1379
-                $result=$this->fetch_lines();
1379
+                $result = $this->fetch_lines();
1380 1380
                 if ($result < 0)
1381 1381
                 {
1382 1382
                     return -3;
@@ -1385,12 +1385,12 @@  discard block
 block discarded – undo
1385 1385
                 return 1;
1386 1386
             }
1387 1387
 
1388
-            $this->error="Record Not Found";
1388
+            $this->error = "Record Not Found";
1389 1389
             return 0;
1390 1390
         }
1391 1391
         else
1392 1392
         {
1393
-            $this->error=$this->db->lasterror();
1393
+            $this->error = $this->db->lasterror();
1394 1394
             return -1;
1395 1395
         }
1396 1396
     }
@@ -1401,21 +1401,21 @@  discard block
 block discarded – undo
1401 1401
 	 * @param		int		$only_product	Return only physical products
1402 1402
 	 * @return		int						<0 if KO, >0 if OK
1403 1403
 	 */
1404
-	function fetch_lines($only_product=0)
1404
+	function fetch_lines($only_product = 0)
1405 1405
 	{
1406
-		$this->lines=array();
1406
+		$this->lines = array();
1407 1407
 
1408 1408
 		$sql = 'SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,';
1409
-		$sql.= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,';
1410
-		$sql.= ' d.fk_unit,';
1411
-		$sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
1412
-		$sql.= ' d.date_start, d.date_end';
1413
-		$sql.= ' ,d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
1414
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
1415
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
1416
-		$sql.= ' WHERE d.fk_propal = '.$this->id;
1409
+		$sql .= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,';
1410
+		$sql .= ' d.fk_unit,';
1411
+		$sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
1412
+		$sql .= ' d.date_start, d.date_end';
1413
+		$sql .= ' ,d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
1414
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
1415
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
1416
+		$sql .= ' WHERE d.fk_propal = '.$this->id;
1417 1417
 		if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1418
-		$sql.= ' ORDER by d.rang';
1418
+		$sql .= ' ORDER by d.rang';
1419 1419
 
1420 1420
 		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1421 1421
 		$result = $this->db->query($sql);
@@ -1432,13 +1432,13 @@  discard block
 block discarded – undo
1432 1432
 
1433 1433
 				$line                   = new PropaleLigne($this->db);
1434 1434
 
1435
-				$line->rowid			= $objp->rowid; //Deprecated
1436
-				$line->id				= $objp->rowid;
1437
-				$line->fk_propal		= $objp->fk_propal;
1438
-				$line->fk_parent_line	= $objp->fk_parent_line;
1435
+				$line->rowid = $objp->rowid; //Deprecated
1436
+				$line->id = $objp->rowid;
1437
+				$line->fk_propal = $objp->fk_propal;
1438
+				$line->fk_parent_line = $objp->fk_parent_line;
1439 1439
 				$line->product_type     = $objp->product_type;
1440 1440
 				$line->label            = $objp->custom_label;
1441
-				$line->desc             = $objp->description;  // Description ligne
1441
+				$line->desc             = $objp->description; // Description ligne
1442 1442
 				$line->qty              = $objp->qty;
1443 1443
 				$line->vat_src_code     = $objp->vat_src_code;
1444 1444
 				$line->tva_tx           = $objp->tva_tx;
@@ -1449,7 +1449,7 @@  discard block
 block discarded – undo
1449 1449
 				$line->subprice         = $objp->subprice;
1450 1450
 				$line->fk_remise_except = $objp->fk_remise_except;
1451 1451
 				$line->remise_percent   = $objp->remise_percent;
1452
-				$line->price            = $objp->price;		// TODO deprecated
1452
+				$line->price            = $objp->price; // TODO deprecated
1453 1453
 
1454 1454
 				$line->info_bits        = $objp->info_bits;
1455 1455
 				$line->total_ht         = $objp->total_ht;
@@ -1457,9 +1457,9 @@  discard block
 block discarded – undo
1457 1457
 				$line->total_localtax1	= $objp->total_localtax1;
1458 1458
 				$line->total_localtax2	= $objp->total_localtax2;
1459 1459
 				$line->total_ttc        = $objp->total_ttc;
1460
-				$line->fk_fournprice 	= $objp->fk_fournprice;
1461
-				$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1462
-				$line->pa_ht 			= $marginInfos[0];
1460
+				$line->fk_fournprice = $objp->fk_fournprice;
1461
+				$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1462
+				$line->pa_ht = $marginInfos[0];
1463 1463
 				$line->marge_tx			= $marginInfos[1];
1464 1464
 				$line->marque_tx		= $marginInfos[2];
1465 1465
 				$line->special_code     = $objp->special_code;
@@ -1467,20 +1467,20 @@  discard block
 block discarded – undo
1467 1467
 
1468 1468
 				$line->fk_product       = $objp->fk_product;
1469 1469
 
1470
-				$line->ref				= $objp->product_ref;		// TODO deprecated
1471
-				$line->product_ref		= $objp->product_ref;
1472
-				$line->libelle			= $objp->product_label;		// TODO deprecated
1473
-				$line->product_label	= $objp->product_label;
1474
-				$line->product_desc     = $objp->product_desc; 		// Description produit
1470
+				$line->ref = $objp->product_ref; // TODO deprecated
1471
+				$line->product_ref = $objp->product_ref;
1472
+				$line->libelle = $objp->product_label; // TODO deprecated
1473
+				$line->product_label = $objp->product_label;
1474
+				$line->product_desc     = $objp->product_desc; // Description produit
1475 1475
 				$line->fk_product_type  = $objp->fk_product_type;
1476 1476
 				$line->fk_unit          = $objp->fk_unit;
1477 1477
 
1478
-				$line->date_start  		= $this->db->jdate($objp->date_start);
1479
-				$line->date_end  		= $this->db->jdate($objp->date_end);
1478
+				$line->date_start = $this->db->jdate($objp->date_start);
1479
+				$line->date_end = $this->db->jdate($objp->date_end);
1480 1480
 
1481 1481
 				// Multicurrency
1482
-				$line->fk_multicurrency 		= $objp->fk_multicurrency;
1483
-				$line->multicurrency_code 		= $objp->multicurrency_code;
1482
+				$line->fk_multicurrency = $objp->fk_multicurrency;
1483
+				$line->multicurrency_code = $objp->multicurrency_code;
1484 1484
 				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
1485 1485
 				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
1486 1486
 				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
@@ -1488,7 +1488,7 @@  discard block
 block discarded – undo
1488 1488
 
1489 1489
 				$line->fetch_optionals();
1490 1490
 
1491
-				$this->lines[$i]        = $line;
1491
+				$this->lines[$i] = $line;
1492 1492
 				//dol_syslog("1 ".$line->fk_product);
1493 1493
 				//print "xx $i ".$this->lines[$i]->fk_product;
1494 1494
 				$i++;
@@ -1500,7 +1500,7 @@  discard block
 block discarded – undo
1500 1500
 		}
1501 1501
 		else
1502 1502
 		{
1503
-			$this->error=$this->db->lasterror();
1503
+			$this->error = $this->db->lasterror();
1504 1504
 			return -3;
1505 1505
 		}
1506 1506
 	}
@@ -1515,19 +1515,19 @@  discard block
 block discarded – undo
1515 1515
     {
1516 1516
         global $conf, $hookmanager;
1517 1517
 
1518
-    	$action='update';
1518
+    	$action = 'update';
1519 1519
         $error = 0;
1520 1520
 
1521 1521
     	// Actions on extra fields (by external module or standard code)
1522 1522
     	// TODO le hook fait double emploi avec le trigger !!
1523 1523
     	$hookmanager->initHooks(array('propaldao'));
1524
-    	$parameters=array('id'=>$this->id);
1525
-    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1524
+    	$parameters = array('id'=>$this->id);
1525
+    	$reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1526 1526
     	if (empty($reshook))
1527 1527
     	{
1528 1528
     		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1529 1529
     		{
1530
-    			$result=$this->insertExtraFields();
1530
+    			$result = $this->insertExtraFields();
1531 1531
     			if ($result < 0)
1532 1532
     			{
1533 1533
     				$error++;
@@ -1554,13 +1554,13 @@  discard block
 block discarded – undo
1554 1554
      *  @param	int		$notrigger	1=Does not execute triggers, 0=execute triggers
1555 1555
      *  @return int         		<0 if KO, 0=Nothing done, >=0 if OK
1556 1556
      */
1557
-    function valid($user, $notrigger=0)
1557
+    function valid($user, $notrigger = 0)
1558 1558
     {
1559 1559
     	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1560 1560
 
1561 1561
     	global $conf;
1562 1562
 
1563
-        $error=0;
1563
+        $error = 0;
1564 1564
 
1565 1565
         // Protection
1566 1566
         if ($this->statut == self::STATUS_VALIDATED)
@@ -1569,15 +1569,15 @@  discard block
 block discarded – undo
1569 1569
             return 0;
1570 1570
         }
1571 1571
 
1572
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer))
1573
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))))
1572
+        if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->creer))
1573
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate))))
1574 1574
         {
1575
-            $this->error='ErrorPermissionDenied';
1575
+            $this->error = 'ErrorPermissionDenied';
1576 1576
             dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1577 1577
             return -1;
1578 1578
         }
1579 1579
 
1580
-        $now=dol_now();
1580
+        $now = dol_now();
1581 1581
 
1582 1582
         $this->db->begin();
1583 1583
 
@@ -1586,7 +1586,7 @@  discard block
 block discarded – undo
1586 1586
         $soc->fetch($this->socid);
1587 1587
 
1588 1588
         // Define new ref
1589
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1589
+        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1590 1590
         {
1591 1591
         	$num = $this->getNextNumRef($soc);
1592 1592
         }
@@ -1597,28 +1597,28 @@  discard block
 block discarded – undo
1597 1597
         $this->newref = $num;
1598 1598
 
1599 1599
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1600
-        $sql.= " SET ref = '".$num."',";
1601
-        $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
1602
-        $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1600
+        $sql .= " SET ref = '".$num."',";
1601
+        $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
1602
+        $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1603 1603
 
1604 1604
         dol_syslog(get_class($this)."::valid", LOG_DEBUG);
1605
-		$resql=$this->db->query($sql);
1606
-		if (! $resql)
1605
+		$resql = $this->db->query($sql);
1606
+		if (!$resql)
1607 1607
 		{
1608 1608
 			dol_print_error($this->db);
1609 1609
 			$error++;
1610 1610
 		}
1611 1611
 
1612 1612
 		// Trigger calls
1613
-		if (! $error && ! $notrigger)
1613
+		if (!$error && !$notrigger)
1614 1614
 		{
1615 1615
             // Call trigger
1616
-            $result=$this->call_trigger('PROPAL_VALIDATE',$user);
1616
+            $result = $this->call_trigger('PROPAL_VALIDATE', $user);
1617 1617
             if ($result < 0) { $error++; }
1618 1618
             // End call triggers
1619 1619
         }
1620 1620
 
1621
-        if (! $error)
1621
+        if (!$error)
1622 1622
         {
1623 1623
         	$this->oldref = $this->ref;
1624 1624
 
@@ -1639,24 +1639,24 @@  discard block
 block discarded – undo
1639 1639
         			{
1640 1640
         				dol_syslog("Rename ok");
1641 1641
         				// Rename docs starting with $oldref with $newref
1642
-        				$listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
1643
-        				foreach($listoffiles as $fileentry)
1642
+        				$listoffiles = dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1643
+        				foreach ($listoffiles as $fileentry)
1644 1644
         				{
1645
-        					$dirsource=$fileentry['name'];
1646
-        					$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
1647
-        					$dirsource=$fileentry['path'].'/'.$dirsource;
1648
-        					$dirdest=$fileentry['path'].'/'.$dirdest;
1645
+        					$dirsource = $fileentry['name'];
1646
+        					$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1647
+        					$dirsource = $fileentry['path'].'/'.$dirsource;
1648
+        					$dirdest = $fileentry['path'].'/'.$dirdest;
1649 1649
         					@rename($dirsource, $dirdest);
1650 1650
         				}
1651 1651
         			}
1652 1652
         		}
1653 1653
         	}
1654 1654
 
1655
-        	$this->ref=$num;
1656
-        	$this->brouillon=0;
1655
+        	$this->ref = $num;
1656
+        	$this->brouillon = 0;
1657 1657
         	$this->statut = self::STATUS_VALIDATED;
1658
-        	$this->user_valid_id=$user->id;
1659
-        	$this->datev=$now;
1658
+        	$this->user_valid_id = $user->id;
1659
+        	$this->datev = $now;
1660 1660
 
1661 1661
         	$this->db->commit();
1662 1662
         	return 1;
@@ -1677,61 +1677,61 @@  discard block
 block discarded – undo
1677 1677
      *  @param  int			$notrigger	1=Does not execute triggers, 0= execute triggers
1678 1678
      *  @return	int         			<0 if KO, >0 if OK
1679 1679
      */
1680
-    function set_date($user, $date, $notrigger=0)
1680
+    function set_date($user, $date, $notrigger = 0)
1681 1681
     {
1682 1682
         if (empty($date))
1683 1683
         {
1684
-            $this->error='ErrorBadParameter';
1684
+            $this->error = 'ErrorBadParameter';
1685 1685
             dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
1686 1686
             return -1;
1687 1687
         }
1688 1688
 
1689
-        if (! empty($user->rights->propal->creer))
1689
+        if (!empty($user->rights->propal->creer))
1690 1690
         {
1691
-        	$error=0;
1691
+        	$error = 0;
1692 1692
 
1693 1693
         	$this->db->begin();
1694 1694
 
1695 1695
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'";
1696
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1696
+            $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1697 1697
 
1698 1698
             dol_syslog(__METHOD__, LOG_DEBUG);
1699
-            $resql=$this->db->query($sql);
1699
+            $resql = $this->db->query($sql);
1700 1700
             if (!$resql)
1701 1701
             {
1702
-            	$this->errors[]=$this->db->error();
1702
+            	$this->errors[] = $this->db->error();
1703 1703
             	$error++;
1704 1704
             }
1705 1705
 
1706
-            if (! $error)
1706
+            if (!$error)
1707 1707
             {
1708
-            	$this->oldcopy= clone $this;
1708
+            	$this->oldcopy = clone $this;
1709 1709
             	$this->date = $date;
1710
-            	$this->datep = $date;    // deprecated
1710
+            	$this->datep = $date; // deprecated
1711 1711
             }
1712 1712
 
1713
-            if (! $notrigger && empty($error))
1713
+            if (!$notrigger && empty($error))
1714 1714
             {
1715 1715
             	// Call trigger
1716
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1716
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
1717 1717
             	if ($result < 0) $error++;
1718 1718
             	// End call triggers
1719 1719
             }
1720 1720
 
1721
-            if (! $error)
1721
+            if (!$error)
1722 1722
             {
1723 1723
             	$this->db->commit();
1724 1724
             	return 1;
1725 1725
             }
1726 1726
             else
1727 1727
             {
1728
-            	foreach($this->errors as $errmsg)
1728
+            	foreach ($this->errors as $errmsg)
1729 1729
             	{
1730 1730
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1731
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1731
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1732 1732
             	}
1733 1733
             	$this->db->rollback();
1734
-            	return -1*$error;
1734
+            	return -1 * $error;
1735 1735
             }
1736 1736
         }
1737 1737
     }
@@ -1744,54 +1744,54 @@  discard block
 block discarded – undo
1744 1744
      *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1745 1745
      *	@return     int         				<0 if KO, >0 if OK
1746 1746
      */
1747
-    function set_echeance($user, $date_fin_validite, $notrigger=0)
1747
+    function set_echeance($user, $date_fin_validite, $notrigger = 0)
1748 1748
     {
1749
-        if (! empty($user->rights->propal->creer))
1749
+        if (!empty($user->rights->propal->creer))
1750 1750
         {
1751
-        	$error=0;
1751
+        	$error = 0;
1752 1752
 
1753 1753
         	$this->db->begin();
1754 1754
 
1755
-            $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null');
1756
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1755
+            $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite != '' ? "'".$this->db->idate($date_fin_validite)."'" : 'null');
1756
+            $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
1757 1757
 
1758 1758
             dol_syslog(__METHOD__, LOG_DEBUG);
1759
-            $resql=$this->db->query($sql);
1759
+            $resql = $this->db->query($sql);
1760 1760
             if (!$resql)
1761 1761
             {
1762
-            	$this->errors[]=$this->db->error();
1762
+            	$this->errors[] = $this->db->error();
1763 1763
             	$error++;
1764 1764
             }
1765 1765
 
1766 1766
 
1767
-            if (! $error)
1767
+            if (!$error)
1768 1768
             {
1769
-            	$this->oldcopy= clone $this;
1769
+            	$this->oldcopy = clone $this;
1770 1770
             	$this->fin_validite = $date_fin_validite;
1771 1771
             }
1772 1772
 
1773
-            if (! $notrigger && empty($error))
1773
+            if (!$notrigger && empty($error))
1774 1774
             {
1775 1775
             	// Call trigger
1776
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1776
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
1777 1777
             	if ($result < 0) $error++;
1778 1778
             	// End call triggers
1779 1779
             }
1780 1780
 
1781
-            if (! $error)
1781
+            if (!$error)
1782 1782
             {
1783 1783
             	$this->db->commit();
1784 1784
             	return 1;
1785 1785
             }
1786 1786
             else
1787 1787
             {
1788
-            	foreach($this->errors as $errmsg)
1788
+            	foreach ($this->errors as $errmsg)
1789 1789
             	{
1790 1790
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1791
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1791
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1792 1792
             	}
1793 1793
             	$this->db->rollback();
1794
-            	return -1*$error;
1794
+            	return -1 * $error;
1795 1795
             }
1796 1796
         }
1797 1797
     }
@@ -1804,54 +1804,54 @@  discard block
 block discarded – undo
1804 1804
      *  @param  	int		$notrigger			1=Does not execute triggers, 0= execute triggers
1805 1805
      *	@return     int         				<0 if ko, >0 if ok
1806 1806
      */
1807
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
1807
+    function set_date_livraison($user, $date_livraison, $notrigger = 0)
1808 1808
     {
1809
-        if (! empty($user->rights->propal->creer))
1809
+        if (!empty($user->rights->propal->creer))
1810 1810
         {
1811
-        	$error=0;
1811
+        	$error = 0;
1812 1812
 
1813 1813
         	$this->db->begin();
1814 1814
 
1815 1815
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1816
-            $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null');
1817
-            $sql.= " WHERE rowid = ".$this->id;
1816
+            $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null');
1817
+            $sql .= " WHERE rowid = ".$this->id;
1818 1818
 
1819 1819
             dol_syslog(__METHOD__, LOG_DEBUG);
1820
-            $resql=$this->db->query($sql);
1820
+            $resql = $this->db->query($sql);
1821 1821
             if (!$resql)
1822 1822
             {
1823
-            	$this->errors[]=$this->db->error();
1823
+            	$this->errors[] = $this->db->error();
1824 1824
             	$error++;
1825 1825
             }
1826 1826
 
1827
-            if (! $error)
1827
+            if (!$error)
1828 1828
             {
1829
-            	$this->oldcopy= clone $this;
1829
+            	$this->oldcopy = clone $this;
1830 1830
             	$this->date_livraison = $date_livraison;
1831 1831
             }
1832 1832
 
1833
-            if (! $notrigger && empty($error))
1833
+            if (!$notrigger && empty($error))
1834 1834
             {
1835 1835
             	// Call trigger
1836
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1836
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
1837 1837
             	if ($result < 0) $error++;
1838 1838
             	// End call triggers
1839 1839
             }
1840 1840
 
1841
-            if (! $error)
1841
+            if (!$error)
1842 1842
             {
1843 1843
             	$this->db->commit();
1844 1844
             	return 1;
1845 1845
             }
1846 1846
             else
1847 1847
             {
1848
-            	foreach($this->errors as $errmsg)
1848
+            	foreach ($this->errors as $errmsg)
1849 1849
             	{
1850 1850
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1851
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1851
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1852 1852
             	}
1853 1853
             	$this->db->rollback();
1854
-            	return -1*$error;
1854
+            	return -1 * $error;
1855 1855
             }
1856 1856
         }
1857 1857
     }
@@ -1864,63 +1864,63 @@  discard block
 block discarded – undo
1864 1864
      *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1865 1865
      *  @return     int           			<0 if KO, >0 if OK
1866 1866
      */
1867
-    function set_availability($user, $id, $notrigger=0)
1867
+    function set_availability($user, $id, $notrigger = 0)
1868 1868
     {
1869
-        if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1869
+        if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1870 1870
         {
1871
-        	$error=0;
1871
+        	$error = 0;
1872 1872
 
1873 1873
         	$this->db->begin();
1874 1874
 
1875 1875
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1876
-            $sql.= " SET fk_availability = '".$id."'";
1877
-            $sql.= " WHERE rowid = ".$this->id;
1876
+            $sql .= " SET fk_availability = '".$id."'";
1877
+            $sql .= " WHERE rowid = ".$this->id;
1878 1878
 
1879 1879
             dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
1880
-            $resql=$this->db->query($sql);
1880
+            $resql = $this->db->query($sql);
1881 1881
             if (!$resql)
1882 1882
             {
1883
-            	$this->errors[]=$this->db->error();
1883
+            	$this->errors[] = $this->db->error();
1884 1884
             	$error++;
1885 1885
             }
1886 1886
 
1887
-            if (! $error)
1887
+            if (!$error)
1888 1888
             {
1889
-            	$this->oldcopy= clone $this;
1889
+            	$this->oldcopy = clone $this;
1890 1890
             	$this->fk_availability = $id;
1891 1891
             	$this->availability_id = $id;
1892 1892
             }
1893 1893
 
1894
-            if (! $notrigger && empty($error))
1894
+            if (!$notrigger && empty($error))
1895 1895
             {
1896 1896
             	// Call trigger
1897
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1897
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
1898 1898
             	if ($result < 0) $error++;
1899 1899
             	// End call triggers
1900 1900
             }
1901 1901
 
1902
-            if (! $error)
1902
+            if (!$error)
1903 1903
             {
1904 1904
             	$this->db->commit();
1905 1905
             	return 1;
1906 1906
             }
1907 1907
             else
1908 1908
             {
1909
-            	foreach($this->errors as $errmsg)
1909
+            	foreach ($this->errors as $errmsg)
1910 1910
             	{
1911 1911
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1912
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1912
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1913 1913
             	}
1914 1914
             	$this->db->rollback();
1915
-            	return -1*$error;
1915
+            	return -1 * $error;
1916 1916
             }
1917 1917
         }
1918 1918
         else
1919 1919
         {
1920
-        	$error_str='Propal status do not meet requirement '.$this->statut;
1920
+        	$error_str = 'Propal status do not meet requirement '.$this->statut;
1921 1921
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
1922
-        	$this->error=$error_str;
1923
-        	$this->errors[]= $this->error;
1922
+        	$this->error = $error_str;
1923
+        	$this->errors[] = $this->error;
1924 1924
         	return -2;
1925 1925
         }
1926 1926
     }
@@ -1933,65 +1933,65 @@  discard block
 block discarded – undo
1933 1933
      *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
1934 1934
      *  @return     int           		<0 if KO, >0 if OK
1935 1935
      */
1936
-    function set_demand_reason($user, $id, $notrigger=0)
1936
+    function set_demand_reason($user, $id, $notrigger = 0)
1937 1937
     {
1938
-        if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1938
+        if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT)
1939 1939
         {
1940
-        	$error=0;
1940
+        	$error = 0;
1941 1941
 
1942 1942
         	$this->db->begin();
1943 1943
 
1944 1944
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
1945
-            $sql.= " SET fk_input_reason = ".$id;
1946
-            $sql.= " WHERE rowid = ".$this->id;
1945
+            $sql .= " SET fk_input_reason = ".$id;
1946
+            $sql .= " WHERE rowid = ".$this->id;
1947 1947
 
1948 1948
             dol_syslog(__METHOD__, LOG_DEBUG);
1949
-            $resql=$this->db->query($sql);
1949
+            $resql = $this->db->query($sql);
1950 1950
             if (!$resql)
1951 1951
             {
1952
-            	$this->errors[]=$this->db->error();
1952
+            	$this->errors[] = $this->db->error();
1953 1953
             	$error++;
1954 1954
             }
1955 1955
 
1956 1956
 
1957
-            if (! $error)
1957
+            if (!$error)
1958 1958
             {
1959
-            	$this->oldcopy= clone $this;
1959
+            	$this->oldcopy = clone $this;
1960 1960
             	$this->fk_input_reason = $id;
1961 1961
             	$this->demand_reason_id = $id;
1962 1962
             }
1963 1963
 
1964 1964
 
1965
-            if (! $notrigger && empty($error))
1965
+            if (!$notrigger && empty($error))
1966 1966
             {
1967 1967
             	// Call trigger
1968
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1968
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
1969 1969
             	if ($result < 0) $error++;
1970 1970
             	// End call triggers
1971 1971
             }
1972 1972
 
1973
-            if (! $error)
1973
+            if (!$error)
1974 1974
             {
1975 1975
             	$this->db->commit();
1976 1976
             	return 1;
1977 1977
             }
1978 1978
             else
1979 1979
             {
1980
-            	foreach($this->errors as $errmsg)
1980
+            	foreach ($this->errors as $errmsg)
1981 1981
             	{
1982 1982
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1983
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
1983
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1984 1984
             	}
1985 1985
             	$this->db->rollback();
1986
-            	return -1*$error;
1986
+            	return -1 * $error;
1987 1987
             }
1988 1988
         }
1989 1989
         else
1990 1990
         {
1991
-        	$error_str='Propal status do not meet requirement '.$this->statut;
1991
+        	$error_str = 'Propal status do not meet requirement '.$this->statut;
1992 1992
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
1993
-        	$this->error=$error_str;
1994
-        	$this->errors[]= $this->error;
1993
+        	$this->error = $error_str;
1994
+        	$this->errors[] = $this->error;
1995 1995
         	return -2;
1996 1996
         }
1997 1997
     }
@@ -2004,53 +2004,53 @@  discard block
 block discarded – undo
2004 2004
      *  @param  	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2005 2005
      *  @return     int						<0 if ko, >0 if ok
2006 2006
      */
2007
-    function set_ref_client($user, $ref_client, $notrigger=0)
2007
+    function set_ref_client($user, $ref_client, $notrigger = 0)
2008 2008
     {
2009
-        if (! empty($user->rights->propal->creer))
2009
+        if (!empty($user->rights->propal->creer))
2010 2010
         {
2011
-            $error=0;
2011
+            $error = 0;
2012 2012
 
2013 2013
             $this->db->begin();
2014 2014
 
2015 2015
             $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2016
-            $sql.= ' WHERE rowid = '.$this->id;
2016
+            $sql .= ' WHERE rowid = '.$this->id;
2017 2017
 
2018 2018
             dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2019
-            $resql=$this->db->query($sql);
2019
+            $resql = $this->db->query($sql);
2020 2020
             if (!$resql)
2021 2021
             {
2022
-            	$this->errors[]=$this->db->error();
2022
+            	$this->errors[] = $this->db->error();
2023 2023
             	$error++;
2024 2024
             }
2025 2025
 
2026
-            if (! $error)
2026
+            if (!$error)
2027 2027
             {
2028
-            	$this->oldcopy= clone $this;
2028
+            	$this->oldcopy = clone $this;
2029 2029
             	$this->ref_client = $ref_client;
2030 2030
             }
2031 2031
 
2032
-            if (! $notrigger && empty($error))
2032
+            if (!$notrigger && empty($error))
2033 2033
             {
2034 2034
             	// Call trigger
2035
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2035
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2036 2036
             	if ($result < 0) $error++;
2037 2037
             	// End call triggers
2038 2038
             }
2039 2039
 
2040
-            if (! $error)
2040
+            if (!$error)
2041 2041
             {
2042 2042
             	$this->db->commit();
2043 2043
             	return 1;
2044 2044
             }
2045 2045
             else
2046 2046
             {
2047
-            	foreach($this->errors as $errmsg)
2047
+            	foreach ($this->errors as $errmsg)
2048 2048
             	{
2049 2049
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2050
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2050
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2051 2051
             	}
2052 2052
             	$this->db->rollback();
2053
-            	return -1*$error;
2053
+            	return -1 * $error;
2054 2054
             }
2055 2055
         }
2056 2056
         else
@@ -2067,58 +2067,58 @@  discard block
 block discarded – undo
2067 2067
      *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2068 2068
      *	@return     int         		<0 if ko, >0 if ok
2069 2069
      */
2070
-    function set_remise_percent($user, $remise, $notrigger=0)
2070
+    function set_remise_percent($user, $remise, $notrigger = 0)
2071 2071
     {
2072
-        $remise=trim($remise)?trim($remise):0;
2072
+        $remise = trim($remise) ?trim($remise) : 0;
2073 2073
 
2074
-        if (! empty($user->rights->propal->creer))
2074
+        if (!empty($user->rights->propal->creer))
2075 2075
         {
2076 2076
             $remise = price2num($remise);
2077 2077
 
2078
-            $error=0;
2078
+            $error = 0;
2079 2079
 
2080 2080
             $this->db->begin();
2081 2081
 
2082 2082
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise;
2083
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2083
+            $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2084 2084
 
2085 2085
             dol_syslog(__METHOD__, LOG_DEBUG);
2086
-            $resql=$this->db->query($sql);
2086
+            $resql = $this->db->query($sql);
2087 2087
             if (!$resql)
2088 2088
             {
2089
-            	$this->errors[]=$this->db->error();
2089
+            	$this->errors[] = $this->db->error();
2090 2090
             	$error++;
2091 2091
             }
2092 2092
 
2093
-            if (! $error)
2093
+            if (!$error)
2094 2094
             {
2095
-            	$this->oldcopy= clone $this;
2095
+            	$this->oldcopy = clone $this;
2096 2096
             	$this->remise_percent = $remise;
2097 2097
             	$this->update_price(1);
2098 2098
             }
2099 2099
 
2100
-            if (! $notrigger && empty($error))
2100
+            if (!$notrigger && empty($error))
2101 2101
             {
2102 2102
             	// Call trigger
2103
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2103
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2104 2104
             	if ($result < 0) $error++;
2105 2105
             	// End call triggers
2106 2106
             }
2107 2107
 
2108
-            if (! $error)
2108
+            if (!$error)
2109 2109
             {
2110 2110
             	$this->db->commit();
2111 2111
             	return 1;
2112 2112
             }
2113 2113
             else
2114 2114
             {
2115
-            	foreach($this->errors as $errmsg)
2115
+            	foreach ($this->errors as $errmsg)
2116 2116
             	{
2117 2117
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2118
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2118
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2119 2119
             	}
2120 2120
             	$this->db->rollback();
2121
-            	return -1*$error;
2121
+            	return -1 * $error;
2122 2122
             }
2123 2123
         }
2124 2124
     }
@@ -2132,59 +2132,59 @@  discard block
 block discarded – undo
2132 2132
      *  @param  	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2133 2133
      *	@return     int         		<0 if ko, >0 if ok
2134 2134
      */
2135
-    function set_remise_absolue($user, $remise, $notrigger=0)
2135
+    function set_remise_absolue($user, $remise, $notrigger = 0)
2136 2136
     {
2137
-        $remise=trim($remise)?trim($remise):0;
2137
+        $remise = trim($remise) ?trim($remise) : 0;
2138 2138
 
2139
-        if (! empty($user->rights->propal->creer))
2139
+        if (!empty($user->rights->propal->creer))
2140 2140
         {
2141 2141
             $remise = price2num($remise);
2142 2142
 
2143
-            $error=0;
2143
+            $error = 0;
2144 2144
 
2145 2145
             $this->db->begin();
2146 2146
 
2147 2147
             $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
2148
-            $sql.= " SET remise_absolue = ".$remise;
2149
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2148
+            $sql .= " SET remise_absolue = ".$remise;
2149
+            $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2150 2150
 
2151 2151
             dol_syslog(__METHOD__, LOG_DEBUG);
2152
-            $resql=$this->db->query($sql);
2152
+            $resql = $this->db->query($sql);
2153 2153
             if (!$resql)
2154 2154
             {
2155
-            	$this->errors[]=$this->db->error();
2155
+            	$this->errors[] = $this->db->error();
2156 2156
             	$error++;
2157 2157
             }
2158 2158
 
2159
-            if (! $error)
2159
+            if (!$error)
2160 2160
             {
2161
-            	$this->oldcopy= clone $this;
2161
+            	$this->oldcopy = clone $this;
2162 2162
             	$this->remise_absolue = $remise;
2163 2163
             	$this->update_price(1);
2164 2164
             }
2165 2165
 
2166
-            if (! $notrigger && empty($error))
2166
+            if (!$notrigger && empty($error))
2167 2167
             {
2168 2168
             	// Call trigger
2169
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2169
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2170 2170
             	if ($result < 0) $error++;
2171 2171
             	// End call triggers
2172 2172
             }
2173 2173
 
2174
-            if (! $error)
2174
+            if (!$error)
2175 2175
             {
2176 2176
             	$this->db->commit();
2177 2177
             	return 1;
2178 2178
             }
2179 2179
             else
2180 2180
             {
2181
-            	foreach($this->errors as $errmsg)
2181
+            	foreach ($this->errors as $errmsg)
2182 2182
             	{
2183 2183
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2184
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2184
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2185 2185
             	}
2186 2186
             	$this->db->rollback();
2187
-            	return -1*$error;
2187
+            	return -1 * $error;
2188 2188
             }
2189 2189
         }
2190 2190
     }
@@ -2200,31 +2200,31 @@  discard block
 block discarded – undo
2200 2200
      *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2201 2201
      *	@return     int         		<0 if KO, >0 if OK
2202 2202
      */
2203
-    function reopen($user, $statut, $note='', $notrigger=0)
2203
+    function reopen($user, $statut, $note = '', $notrigger = 0)
2204 2204
     {
2205 2205
 
2206 2206
         $this->statut = $statut;
2207
-        $error=0;
2207
+        $error = 0;
2208 2208
 
2209 2209
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2210
-        $sql.= " SET fk_statut = ".$this->statut.",";
2211
-		if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',";
2212
-        $sql.= " date_cloture=NULL, fk_user_cloture=NULL";
2213
-        $sql.= " WHERE rowid = ".$this->id;
2210
+        $sql .= " SET fk_statut = ".$this->statut.",";
2211
+		if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',";
2212
+        $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
2213
+        $sql .= " WHERE rowid = ".$this->id;
2214 2214
 
2215 2215
     	$this->db->begin();
2216 2216
 
2217 2217
 		dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2218 2218
 		$resql = $this->db->query($sql);
2219
-		if (! $resql) {
2220
-			$error++; $this->errors[]="Error ".$this->db->lasterror();
2219
+		if (!$resql) {
2220
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
2221 2221
 		}
2222
-		if (! $error)
2222
+		if (!$error)
2223 2223
 		{
2224
-			if (! $notrigger)
2224
+			if (!$notrigger)
2225 2225
 			{
2226 2226
                 // Call trigger
2227
-                $result=$this->call_trigger('PROPAL_REOPEN',$user);
2227
+                $result = $this->call_trigger('PROPAL_REOPEN', $user);
2228 2228
                 if ($result < 0) { $error++; }
2229 2229
                 // End call triggers
2230 2230
 			}
@@ -2235,14 +2235,14 @@  discard block
 block discarded – undo
2235 2235
 		{
2236 2236
 		    if (!empty($this->errors))
2237 2237
 		    {
2238
-    			foreach($this->errors as $errmsg)
2238
+    			foreach ($this->errors as $errmsg)
2239 2239
     			{
2240 2240
     				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2241
-    				$this->error.=($this->error?', '.$errmsg:$errmsg);
2241
+    				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2242 2242
     			}
2243 2243
 		    }
2244 2244
 			$this->db->rollback();
2245
-			return -1*$error;
2245
+			return -1 * $error;
2246 2246
 		}
2247 2247
 		else
2248 2248
 		{
@@ -2261,78 +2261,78 @@  discard block
 block discarded – undo
2261 2261
      *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2262 2262
      *	@return     int         		<0 if KO, >0 if OK
2263 2263
      */
2264
-    function cloture($user, $statut, $note, $notrigger=0)
2264
+    function cloture($user, $statut, $note, $notrigger = 0)
2265 2265
     {
2266
-        global $langs,$conf;
2266
+        global $langs, $conf;
2267 2267
 
2268
-        $error=0;
2269
-        $now=dol_now();
2268
+        $error = 0;
2269
+        $now = dol_now();
2270 2270
 
2271 2271
         $this->db->begin();
2272 2272
 
2273 2273
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2274
-        $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
2275
-        $sql.= " WHERE rowid = ".$this->id;
2274
+        $sql .= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
2275
+        $sql .= " WHERE rowid = ".$this->id;
2276 2276
 
2277
-        $resql=$this->db->query($sql);
2277
+        $resql = $this->db->query($sql);
2278 2278
         if ($resql)
2279 2279
         {
2280
-        	$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf;
2281
-        	$trigger_name='PROPAL_CLOSE_REFUSED';
2280
+        	$modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->modelpdf;
2281
+        	$trigger_name = 'PROPAL_CLOSE_REFUSED';
2282 2282
 
2283 2283
             if ($statut == self::STATUS_SIGNED)
2284 2284
             {
2285
-            	$trigger_name='PROPAL_CLOSE_SIGNED';
2286
-				$modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf;
2285
+            	$trigger_name = 'PROPAL_CLOSE_SIGNED';
2286
+				$modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->modelpdf;
2287 2287
 
2288 2288
                 // The connected company is classified as a client
2289
-                $soc=new Societe($this->db);
2289
+                $soc = new Societe($this->db);
2290 2290
                 $soc->id = $this->socid;
2291
-                $result=$soc->set_as_client();
2291
+                $result = $soc->set_as_client();
2292 2292
 
2293 2293
                 if ($result < 0)
2294 2294
                 {
2295
-                    $this->error=$this->db->lasterror();
2295
+                    $this->error = $this->db->lasterror();
2296 2296
                     $this->db->rollback();
2297 2297
                     return -2;
2298 2298
                 }
2299 2299
             }
2300 2300
             if ($statut == self::STATUS_BILLED)
2301 2301
             {
2302
-            	$trigger_name='PROPAL_CLASSIFY_BILLED';
2302
+            	$trigger_name = 'PROPAL_CLASSIFY_BILLED';
2303 2303
             }
2304 2304
 
2305 2305
             if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
2306 2306
             {
2307 2307
              	// Define output language
2308 2308
               	$outputlangs = $langs;
2309
-               	if (! empty($conf->global->MAIN_MULTILANGS))
2309
+               	if (!empty($conf->global->MAIN_MULTILANGS))
2310 2310
                	{
2311
-               		$outputlangs = new Translate("",$conf);
2312
-               		$newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang);
2311
+               		$outputlangs = new Translate("", $conf);
2312
+               		$newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2313 2313
                		$outputlangs->setDefaultLang($newlang);
2314 2314
                	}
2315 2315
                	//$ret=$object->fetch($id);    // Reload to get new records
2316 2316
 	               $this->generateDocument($modelpdf, $outputlangs);
2317 2317
             }
2318 2318
 
2319
-            if (! $error)
2319
+            if (!$error)
2320 2320
             {
2321
-            	$this->oldcopy= clone $this;
2321
+            	$this->oldcopy = clone $this;
2322 2322
             	$this->statut = $statut;
2323 2323
             	$this->date_cloture = $now;
2324 2324
             	$this->note_private = $note;
2325 2325
             }
2326 2326
 
2327
-            if (! $notrigger && empty($error))
2327
+            if (!$notrigger && empty($error))
2328 2328
             {
2329 2329
 	            // Call trigger
2330
-	            $result=$this->call_trigger($trigger_name,$user);
2330
+	            $result = $this->call_trigger($trigger_name, $user);
2331 2331
 	            if ($result < 0) { $error++; }
2332 2332
 	            // End call triggers
2333 2333
             }
2334 2334
 
2335
-            if ( ! $error )
2335
+            if (!$error)
2336 2336
             {
2337 2337
 		        $this->db->commit();
2338 2338
                 return 1;
@@ -2345,7 +2345,7 @@  discard block
 block discarded – undo
2345 2345
         }
2346 2346
         else
2347 2347
         {
2348
-            $this->error=$this->db->lasterror();
2348
+            $this->error = $this->db->lasterror();
2349 2349
             $this->db->rollback();
2350 2350
             return -1;
2351 2351
         }
@@ -2358,9 +2358,9 @@  discard block
 block discarded – undo
2358 2358
      *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2359 2359
      *	@return     int     			<0 si ko, >0 si ok
2360 2360
      */
2361
-    function classifyBilled(User $user, $notrigger=0)
2361
+    function classifyBilled(User $user, $notrigger = 0)
2362 2362
     {
2363
-    	$error=0;
2363
+    	$error = 0;
2364 2364
 
2365 2365
     	$this->db->begin();
2366 2366
 
@@ -2368,41 +2368,41 @@  discard block
 block discarded – undo
2368 2368
         $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2369 2369
 
2370 2370
         dol_syslog(__METHOD__, LOG_DEBUG);
2371
-        $resql=$this->db->query($sql);
2371
+        $resql = $this->db->query($sql);
2372 2372
         if (!$resql)
2373 2373
         {
2374
-        	$this->errors[]=$this->db->error();
2374
+        	$this->errors[] = $this->db->error();
2375 2375
         	$error++;
2376 2376
         }
2377 2377
 
2378
-        if (! $error)
2378
+        if (!$error)
2379 2379
         {
2380
-        	$this->oldcopy= clone $this;
2381
-        	$this->statut=self::STATUS_BILLED;
2380
+        	$this->oldcopy = clone $this;
2381
+        	$this->statut = self::STATUS_BILLED;
2382 2382
         }
2383 2383
 
2384
-        if (! $notrigger && empty($error))
2384
+        if (!$notrigger && empty($error))
2385 2385
         {
2386 2386
         	// Call trigger
2387
-        	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2387
+        	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2388 2388
         	if ($result < 0) $error++;
2389 2389
         	// End call triggers
2390 2390
         }
2391 2391
 
2392
-        if (! $error)
2392
+        if (!$error)
2393 2393
         {
2394 2394
         	$this->db->commit();
2395 2395
         	return 1;
2396 2396
         }
2397 2397
         else
2398 2398
         {
2399
-        	foreach($this->errors as $errmsg)
2399
+        	foreach ($this->errors as $errmsg)
2400 2400
         	{
2401 2401
         		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2402
-        		$this->error.=($this->error?', '.$errmsg:$errmsg);
2402
+        		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2403 2403
         	}
2404 2404
         	$this->db->rollback();
2405
-        	return -1*$error;
2405
+        	return -1 * $error;
2406 2406
         }
2407 2407
     }
2408 2408
 
@@ -2416,7 +2416,7 @@  discard block
 block discarded – undo
2416 2416
     function classer_facturee()
2417 2417
     {
2418 2418
         global $user;
2419
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
2419
+		dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
2420 2420
 
2421 2421
     	return $this->classifyBilled($user);
2422 2422
     }
@@ -2428,52 +2428,52 @@  discard block
 block discarded – undo
2428 2428
      *  @param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
2429 2429
      *	@return		int					<0 if KO, >0 if OK
2430 2430
      */
2431
-    function set_draft($user, $notrigger=0)
2431
+    function set_draft($user, $notrigger = 0)
2432 2432
     {
2433
-    	$error=0;
2433
+    	$error = 0;
2434 2434
 
2435 2435
     	$this->db->begin();
2436 2436
 
2437 2437
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT;
2438
-        $sql.= " WHERE rowid = ".$this->id;
2438
+        $sql .= " WHERE rowid = ".$this->id;
2439 2439
 
2440 2440
         dol_syslog(__METHOD__, LOG_DEBUG);
2441
-        $resql=$this->db->query($sql);
2441
+        $resql = $this->db->query($sql);
2442 2442
         if (!$resql)
2443 2443
         {
2444
-        	$this->errors[]=$this->db->error();
2444
+        	$this->errors[] = $this->db->error();
2445 2445
         	$error++;
2446 2446
         }
2447 2447
 
2448
-        if (! $error)
2448
+        if (!$error)
2449 2449
         {
2450
-        	$this->oldcopy= clone $this;
2450
+        	$this->oldcopy = clone $this;
2451 2451
         	$this->statut = self::STATUS_DRAFT;
2452 2452
             $this->brouillon = 1;
2453 2453
         }
2454 2454
 
2455
-        if (! $notrigger && empty($error))
2455
+        if (!$notrigger && empty($error))
2456 2456
         {
2457 2457
         	// Call trigger
2458
-        	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2458
+        	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2459 2459
         	if ($result < 0) $error++;
2460 2460
         	// End call triggers
2461 2461
         }
2462 2462
 
2463
-        if (! $error)
2463
+        if (!$error)
2464 2464
         {
2465 2465
         	$this->db->commit();
2466 2466
         	return 1;
2467 2467
         }
2468 2468
         else
2469 2469
         {
2470
-        	foreach($this->errors as $errmsg)
2470
+        	foreach ($this->errors as $errmsg)
2471 2471
         	{
2472 2472
         		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2473
-        		$this->error.=($this->error?', '.$errmsg:$errmsg);
2473
+        		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2474 2474
         	}
2475 2475
         	$this->db->rollback();
2476
-        	return -1*$error;
2476
+        	return -1 * $error;
2477 2477
         }
2478 2478
     }
2479 2479
 
@@ -2491,32 +2491,32 @@  discard block
 block discarded – undo
2491 2491
      *    @param    string	$sortorder			Sort order
2492 2492
      *    @return	int		       				-1 if KO, array with result if OK
2493 2493
      */
2494
-    function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC')
2494
+    function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
2495 2495
     {
2496 2496
         global $user;
2497 2497
 
2498 2498
         $ga = array();
2499 2499
 
2500 2500
         $sql = "SELECT s.rowid, s.nom as name, s.client,";
2501
-        $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2502
-        $sql.= " p.datep as dp, p.fin_validite as datelimite";
2503
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2504
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2505
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2506
-        $sql.= " WHERE p.entity IN (".getEntity('propal').")";
2507
-        $sql.= " AND p.fk_soc = s.rowid";
2508
-        $sql.= " AND p.fk_statut = c.id";
2509
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2510
-        {
2511
-        	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2512
-        }
2513
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2514
-        if ($draft)	$sql.= " AND p.fk_statut = ".self::STATUS_DRAFT;
2515
-        if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id;
2516
-        $sql.= $this->db->order($sortfield,$sortorder);
2517
-        $sql.= $this->db->plimit($limit,$offset);
2518
-
2519
-        $result=$this->db->query($sql);
2501
+        $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2502
+        $sql .= " p.datep as dp, p.fin_validite as datelimite";
2503
+        if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
2504
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2505
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2506
+        $sql .= " WHERE p.entity IN (".getEntity('propal').")";
2507
+        $sql .= " AND p.fk_soc = s.rowid";
2508
+        $sql .= " AND p.fk_statut = c.id";
2509
+        if (!$user->rights->societe->client->voir && !$socid) //restriction
2510
+        {
2511
+        	$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
2512
+        }
2513
+        if ($socid) $sql .= " AND s.rowid = ".$socid;
2514
+        if ($draft)	$sql .= " AND p.fk_statut = ".self::STATUS_DRAFT;
2515
+        if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id;
2516
+        $sql .= $this->db->order($sortfield, $sortorder);
2517
+        $sql .= $this->db->plimit($limit, $offset);
2518
+
2519
+        $result = $this->db->query($sql);
2520 2520
         if ($result)
2521 2521
         {
2522 2522
             $num = $this->db->num_rows($result);
@@ -2537,7 +2537,7 @@  discard block
 block discarded – undo
2537 2537
                     }
2538 2538
                     else
2539 2539
 					{
2540
-                        $ga[$i]['id']	= $obj->propalid;
2540
+                        $ga[$i]['id'] = $obj->propalid;
2541 2541
                         $ga[$i]['ref'] 	= $obj->ref;
2542 2542
                         $ga[$i]['name'] = $obj->name;
2543 2543
                     }
@@ -2575,12 +2575,12 @@  discard block
 block discarded – undo
2575 2575
         $ga = array();
2576 2576
         $linkedInvoices = array();
2577 2577
 
2578
-        $this->fetchObjectLinked($id,$this->element);
2579
-        foreach($this->linkedObjectsIds as $objecttype => $objectid)
2578
+        $this->fetchObjectLinked($id, $this->element);
2579
+        foreach ($this->linkedObjectsIds as $objecttype => $objectid)
2580 2580
         {
2581 2581
         	// Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n
2582 2582
         	// On parcourt donc une liste d'objets en tant qu'objet unique
2583
-			foreach($objectid as $key => $object)
2583
+			foreach ($objectid as $key => $object)
2584 2584
             {
2585 2585
                 // Cas des factures liees directement
2586 2586
                 if ($objecttype == 'facture')
@@ -2590,10 +2590,10 @@  discard block
 block discarded – undo
2590 2590
                 // Cas des factures liees par un autre objet (ex: commande)
2591 2591
                 else
2592 2592
 				{
2593
-                    $this->fetchObjectLinked($object,$objecttype);
2594
-                    foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid)
2593
+                    $this->fetchObjectLinked($object, $objecttype);
2594
+                    foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid)
2595 2595
                     {
2596
-						foreach($subobjectid as $subkey => $subobject)
2596
+						foreach ($subobjectid as $subkey => $subobject)
2597 2597
                         {
2598 2598
                         	if ($subobjecttype == 'facture')
2599 2599
                         	{
@@ -2607,18 +2607,18 @@  discard block
 block discarded – undo
2607 2607
 
2608 2608
         if (count($linkedInvoices) > 0)
2609 2609
         {
2610
-            $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye";
2611
-            $sql.= " FROM ".MAIN_DB_PREFIX."facture";
2612
-            $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")";
2610
+            $sql = "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye";
2611
+            $sql .= " FROM ".MAIN_DB_PREFIX."facture";
2612
+            $sql .= " WHERE rowid IN (".implode(',', $linkedInvoices).")";
2613 2613
 
2614 2614
             dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
2615
-            $resql=$this->db->query($sql);
2615
+            $resql = $this->db->query($sql);
2616 2616
 
2617 2617
             if ($resql)
2618 2618
             {
2619
-                $tab_sqlobj=array();
2619
+                $tab_sqlobj = array();
2620 2620
                 $nump = $this->db->num_rows($resql);
2621
-                for ($i = 0;$i < $nump;$i++)
2621
+                for ($i = 0; $i < $nump; $i++)
2622 2622
                 {
2623 2623
                     $sqlobj = $this->db->fetch_object($resql);
2624 2624
                     $tab_sqlobj[] = $sqlobj;
@@ -2656,24 +2656,24 @@  discard block
 block discarded – undo
2656 2656
      *	@param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2657 2657
      *	@return	int						1 if ok, otherwise if error
2658 2658
      */
2659
-    function delete($user, $notrigger=0)
2659
+    function delete($user, $notrigger = 0)
2660 2660
     {
2661 2661
         global $conf;
2662 2662
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2663 2663
 
2664
-        $error=0;
2664
+        $error = 0;
2665 2665
 
2666 2666
         $this->db->begin();
2667 2667
 
2668
-        if (! $notrigger)
2668
+        if (!$notrigger)
2669 2669
         {
2670 2670
             // Call trigger
2671
-            $result=$this->call_trigger('PROPAL_DELETE',$user);
2671
+            $result = $this->call_trigger('PROPAL_DELETE', $user);
2672 2672
             if ($result < 0) { $error++; }
2673 2673
             // End call triggers
2674 2674
         }
2675 2675
 
2676
-        if (! $error)
2676
+        if (!$error)
2677 2677
         {
2678 2678
             $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id;
2679 2679
             if ($this->db->query($sql))
@@ -2689,33 +2689,33 @@  discard block
 block discarded – undo
2689 2689
                     $res = $this->delete_linked_contact();
2690 2690
                     if ($res < 0) $error++;
2691 2691
 
2692
-                    if (! $error)
2692
+                    if (!$error)
2693 2693
                     {
2694 2694
                         // We remove directory
2695 2695
                         $ref = dol_sanitizeFileName($this->ref);
2696 2696
                         if ($conf->propal->dir_output && !empty($this->ref))
2697 2697
                         {
2698
-                            $dir = $conf->propal->dir_output . "/" . $ref ;
2699
-                            $file = $dir . "/" . $ref . ".pdf";
2698
+                            $dir = $conf->propal->dir_output."/".$ref;
2699
+                            $file = $dir."/".$ref.".pdf";
2700 2700
                             if (file_exists($file))
2701 2701
                             {
2702 2702
                                 dol_delete_preview($this);
2703 2703
 
2704
-                                if (! dol_delete_file($file,0,0,0,$this)) // For triggers
2704
+                                if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
2705 2705
                                 {
2706
-                                    $this->error='ErrorFailToDeleteFile';
2707
-                                    $this->errors=array('ErrorFailToDeleteFile');
2706
+                                    $this->error = 'ErrorFailToDeleteFile';
2707
+                                    $this->errors = array('ErrorFailToDeleteFile');
2708 2708
                                 	$this->db->rollback();
2709 2709
                                     return 0;
2710 2710
                                 }
2711 2711
                             }
2712 2712
                             if (file_exists($dir))
2713 2713
                             {
2714
-                                $res=@dol_delete_dir_recursive($dir);
2715
-                                if (! $res)
2714
+                                $res = @dol_delete_dir_recursive($dir);
2715
+                                if (!$res)
2716 2716
                                 {
2717
-                                    $this->error='ErrorFailToDeleteDir';
2718
-                                    $this->errors=array('ErrorFailToDeleteDir');
2717
+                                    $this->error = 'ErrorFailToDeleteDir';
2718
+                                    $this->errors = array('ErrorFailToDeleteDir');
2719 2719
                                     $this->db->rollback();
2720 2720
                                     return 0;
2721 2721
                                 }
@@ -2724,21 +2724,21 @@  discard block
 block discarded – undo
2724 2724
                     }
2725 2725
 
2726 2726
                     // Removed extrafields
2727
-                    if (! $error)
2727
+                    if (!$error)
2728 2728
                     {
2729 2729
                     	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2730 2730
                     	{
2731
-                    		$result=$this->deleteExtraFields();
2731
+                    		$result = $this->deleteExtraFields();
2732 2732
                     		if ($result < 0)
2733 2733
                     		{
2734 2734
                     			$error++;
2735
-                    			$errorflag=-4;
2735
+                    			$errorflag = -4;
2736 2736
                     			dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
2737 2737
                     		}
2738 2738
                     	}
2739 2739
                     }
2740 2740
 
2741
-                    if (! $error)
2741
+                    if (!$error)
2742 2742
                     {
2743 2743
                         dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
2744 2744
                         $this->db->commit();
@@ -2746,21 +2746,21 @@  discard block
 block discarded – undo
2746 2746
                     }
2747 2747
                     else
2748 2748
                     {
2749
-                        $this->error=$this->db->lasterror();
2749
+                        $this->error = $this->db->lasterror();
2750 2750
                         $this->db->rollback();
2751 2751
                         return 0;
2752 2752
                     }
2753 2753
                 }
2754 2754
                 else
2755 2755
                 {
2756
-                    $this->error=$this->db->lasterror();
2756
+                    $this->error = $this->db->lasterror();
2757 2757
                     $this->db->rollback();
2758 2758
                     return -3;
2759 2759
                 }
2760 2760
             }
2761 2761
             else
2762 2762
             {
2763
-                $this->error=$this->db->lasterror();
2763
+                $this->error = $this->db->lasterror();
2764 2764
                 $this->db->rollback();
2765 2765
                 return -2;
2766 2766
             }
@@ -2780,13 +2780,13 @@  discard block
 block discarded – undo
2780 2780
      *  @return int                  	>0 if OK, <0 if KO
2781 2781
      *  @deprecated  use set_availability
2782 2782
      */
2783
-    function availability($availability_id, $notrigger=0)
2783
+    function availability($availability_id, $notrigger = 0)
2784 2784
     {
2785 2785
         global $user;
2786 2786
 
2787 2787
         if ($this->statut >= self::STATUS_DRAFT)
2788 2788
         {
2789
-        	$error=0;
2789
+        	$error = 0;
2790 2790
 
2791 2791
         	$this->db->begin();
2792 2792
 
@@ -2795,49 +2795,49 @@  discard block
 block discarded – undo
2795 2795
             $sql .= ' WHERE rowid='.$this->id;
2796 2796
 
2797 2797
             dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
2798
-            $resql=$this->db->query($sql);
2798
+            $resql = $this->db->query($sql);
2799 2799
             if (!$resql)
2800 2800
             {
2801
-            	$this->errors[]=$this->db->error();
2801
+            	$this->errors[] = $this->db->error();
2802 2802
             	$error++;
2803 2803
             }
2804 2804
 
2805
-            if (! $error)
2805
+            if (!$error)
2806 2806
             {
2807
-            	$this->oldcopy= clone $this;
2807
+            	$this->oldcopy = clone $this;
2808 2808
             	$this->availability_id = $availability_id;
2809 2809
             }
2810 2810
 
2811
-            if (! $notrigger && empty($error))
2811
+            if (!$notrigger && empty($error))
2812 2812
             {
2813 2813
             	// Call trigger
2814
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2814
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2815 2815
             	if ($result < 0) $error++;
2816 2816
             	// End call triggers
2817 2817
             }
2818 2818
 
2819
-            if (! $error)
2819
+            if (!$error)
2820 2820
             {
2821 2821
             	$this->db->commit();
2822 2822
             	return 1;
2823 2823
             }
2824 2824
             else
2825 2825
             {
2826
-            	foreach($this->errors as $errmsg)
2826
+            	foreach ($this->errors as $errmsg)
2827 2827
             	{
2828 2828
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2829
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2829
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2830 2830
             	}
2831 2831
             	$this->db->rollback();
2832
-            	return -1*$error;
2832
+            	return -1 * $error;
2833 2833
             }
2834 2834
         }
2835 2835
         else
2836 2836
         {
2837
-        	$error_str='Propal status do not meet requirement '.$this->statut;
2837
+        	$error_str = 'Propal status do not meet requirement '.$this->statut;
2838 2838
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2839
-        	$this->error=$error_str;
2840
-        	$this->errors[]= $this->error;
2839
+        	$this->error = $error_str;
2840
+        	$this->errors[] = $this->error;
2841 2841
             return -2;
2842 2842
         }
2843 2843
     }
@@ -2850,11 +2850,11 @@  discard block
 block discarded – undo
2850 2850
      *	@return int						>0 si ok, <0 si ko
2851 2851
      *	@deprecated use set_demand_reason
2852 2852
      */
2853
-    function demand_reason($demand_reason_id, $notrigger=0)
2853
+    function demand_reason($demand_reason_id, $notrigger = 0)
2854 2854
     {
2855 2855
         if ($this->statut >= self::STATUS_DRAFT)
2856 2856
         {
2857
-        	$error=0;
2857
+        	$error = 0;
2858 2858
 
2859 2859
         	$this->db->begin();
2860 2860
 
@@ -2863,49 +2863,49 @@  discard block
 block discarded – undo
2863 2863
             $sql .= ' WHERE rowid='.$this->id;
2864 2864
 
2865 2865
             dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
2866
-            $resql=$this->db->query($sql);
2866
+            $resql = $this->db->query($sql);
2867 2867
             if (!$resql)
2868 2868
             {
2869
-            	$this->errors[]=$this->db->error();
2869
+            	$this->errors[] = $this->db->error();
2870 2870
             	$error++;
2871 2871
             }
2872 2872
 
2873
-            if (! $error)
2873
+            if (!$error)
2874 2874
             {
2875
-            	$this->oldcopy= clone $this;
2875
+            	$this->oldcopy = clone $this;
2876 2876
             	$this->demand_reason_id = $demand_reason_id;
2877 2877
             }
2878 2878
 
2879
-            if (! $notrigger && empty($error))
2879
+            if (!$notrigger && empty($error))
2880 2880
             {
2881 2881
             	// Call trigger
2882
-            	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2882
+            	$result = $this->call_trigger('PROPAL_MODIFY', $user);
2883 2883
             	if ($result < 0) $error++;
2884 2884
             	// End call triggers
2885 2885
             }
2886 2886
 
2887
-            if (! $error)
2887
+            if (!$error)
2888 2888
             {
2889 2889
             	$this->db->commit();
2890 2890
             	return 1;
2891 2891
             }
2892 2892
             else
2893 2893
             {
2894
-            	foreach($this->errors as $errmsg)
2894
+            	foreach ($this->errors as $errmsg)
2895 2895
             	{
2896 2896
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2897
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2897
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2898 2898
             	}
2899 2899
             	$this->db->rollback();
2900
-            	return -1*$error;
2900
+            	return -1 * $error;
2901 2901
             }
2902 2902
         }
2903 2903
         else
2904 2904
         {
2905
-        	$error_str='Propal status do not meet requirement '.$this->statut;
2905
+        	$error_str = 'Propal status do not meet requirement '.$this->statut;
2906 2906
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2907
-        	$this->error=$error_str;
2908
-        	$this->errors[]= $this->error;
2907
+        	$this->error = $error_str;
2908
+        	$this->errors[] = $this->error;
2909 2909
             return -2;
2910 2910
         }
2911 2911
     }
@@ -2920,10 +2920,10 @@  discard block
 block discarded – undo
2920 2920
     function info($id)
2921 2921
     {
2922 2922
         $sql = "SELECT c.rowid, ";
2923
-        $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
2924
-        $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
2925
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as c";
2926
-        $sql.= " WHERE c.rowid = ".$id;
2923
+        $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
2924
+        $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
2925
+        $sql .= " FROM ".MAIN_DB_PREFIX."propal as c";
2926
+        $sql .= " WHERE c.rowid = ".$id;
2927 2927
 
2928 2928
         $result = $this->db->query($sql);
2929 2929
 
@@ -2941,20 +2941,20 @@  discard block
 block discarded – undo
2941 2941
 
2942 2942
                 $cuser = new User($this->db);
2943 2943
                 $cuser->fetch($obj->fk_user_author);
2944
-                $this->user_creation     = $cuser;
2944
+                $this->user_creation = $cuser;
2945 2945
 
2946 2946
                 if ($obj->fk_user_valid)
2947 2947
                 {
2948 2948
                     $vuser = new User($this->db);
2949 2949
                     $vuser->fetch($obj->fk_user_valid);
2950
-                    $this->user_validation     = $vuser;
2950
+                    $this->user_validation = $vuser;
2951 2951
                 }
2952 2952
 
2953 2953
                 if ($obj->fk_user_cloture)
2954 2954
                 {
2955 2955
                     $cluser = new User($this->db);
2956 2956
                     $cluser->fetch($obj->fk_user_cloture);
2957
-                    $this->user_cloture     = $cluser;
2957
+                    $this->user_cloture = $cluser;
2958 2958
                 }
2959 2959
 
2960 2960
 
@@ -2975,7 +2975,7 @@  discard block
 block discarded – undo
2975 2975
      *    	@param      int			$mode        0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
2976 2976
      *    	@return     string		Label
2977 2977
      */
2978
-    function getLibStatut($mode=0)
2978
+    function getLibStatut($mode = 0)
2979 2979
     {
2980 2980
         return $this->LibStatut($this->statut, $mode);
2981 2981
     }
@@ -2987,24 +2987,24 @@  discard block
 block discarded – undo
2987 2987
      *    	@param      int			$mode      	0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2988 2988
      *    	@return     string		Label
2989 2989
      */
2990
-     function LibStatut($statut,$mode=1)
2990
+     function LibStatut($statut, $mode = 1)
2991 2991
     {
2992 2992
 		global $langs;
2993 2993
 		$langs->load("propal");
2994 2994
 
2995
-		if ($statut==self::STATUS_DRAFT) $statuttrans='statut0';
2996
-		if ($statut==self::STATUS_VALIDATED) $statuttrans='statut1';
2997
-		if ($statut==self::STATUS_SIGNED) $statuttrans='statut3';
2998
-		if ($statut==self::STATUS_NOTSIGNED) $statuttrans='statut5';
2999
-		if ($statut==self::STATUS_BILLED) $statuttrans='statut6';
2995
+		if ($statut == self::STATUS_DRAFT) $statuttrans = 'statut0';
2996
+		if ($statut == self::STATUS_VALIDATED) $statuttrans = 'statut1';
2997
+		if ($statut == self::STATUS_SIGNED) $statuttrans = 'statut3';
2998
+		if ($statut == self::STATUS_NOTSIGNED) $statuttrans = 'statut5';
2999
+		if ($statut == self::STATUS_BILLED) $statuttrans = 'statut6';
3000 3000
 
3001 3001
 		if ($mode == 0)	return $this->labelstatut[$statut];
3002 3002
 		if ($mode == 1)	return $this->labelstatut_short[$statut];
3003 3003
 		if ($mode == 2)	return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut];
3004 3004
 		if ($mode == 3)	return img_picto($this->labelstatut[$statut], $statuttrans);
3005
-		if ($mode == 4)	return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut];
3006
-		if ($mode == 5)	return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3007
-		if ($mode == 6)	return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3005
+		if ($mode == 4)	return img_picto($this->labelstatut[$statut], $statuttrans).' '.$this->labelstatut[$statut];
3006
+		if ($mode == 5)	return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut], $statuttrans);
3007
+		if ($mode == 6)	return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut], $statuttrans);
3008 3008
      }
3009 3009
 
3010 3010
 
@@ -3015,51 +3015,51 @@  discard block
 block discarded – undo
3015 3015
      *      @param          int		$mode   "opened" for proposal to close, "signed" for proposal to invoice
3016 3016
      *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
3017 3017
      */
3018
-    function load_board($user,$mode)
3018
+    function load_board($user, $mode)
3019 3019
     {
3020 3020
         global $conf, $langs;
3021 3021
 
3022 3022
         $clause = " WHERE";
3023 3023
 
3024 3024
         $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin";
3025
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3025
+        $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3026 3026
         if (!$user->rights->societe->client->voir && !$user->societe_id)
3027 3027
         {
3028
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3029
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3028
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3029
+            $sql .= " WHERE sc.fk_user = ".$user->id;
3030 3030
             $clause = " AND";
3031 3031
         }
3032
-        $sql.= $clause." p.entity IN (".getEntity('propal').")";
3033
-        if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3034
-        if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED;
3035
-        if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id;
3032
+        $sql .= $clause." p.entity IN (".getEntity('propal').")";
3033
+        if ($mode == 'opened') $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3034
+        if ($mode == 'signed') $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
3035
+        if ($user->societe_id) $sql .= " AND p.fk_soc = ".$user->societe_id;
3036 3036
 
3037
-        $resql=$this->db->query($sql);
3037
+        $resql = $this->db->query($sql);
3038 3038
         if ($resql)
3039 3039
         {
3040 3040
 	        $langs->load("propal");
3041
-	        $now=dol_now();
3041
+	        $now = dol_now();
3042 3042
 
3043 3043
             if ($mode == 'opened') {
3044
-	            $delay_warning=$conf->propal->cloture->warning_delay;
3044
+	            $delay_warning = $conf->propal->cloture->warning_delay;
3045 3045
 	            $statut = self::STATUS_VALIDATED;
3046 3046
 	            $label = $langs->trans("PropalsToClose");
3047 3047
             }
3048 3048
             if ($mode == 'signed') {
3049
-	            $delay_warning=$conf->propal->facturation->warning_delay;
3049
+	            $delay_warning = $conf->propal->facturation->warning_delay;
3050 3050
 	            $statut = self::STATUS_SIGNED;
3051
-	            $label = $langs->trans("PropalsToBill");         // We set here bill but may be billed or ordered
3051
+	            $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
3052 3052
             }
3053 3053
 
3054 3054
 	        $response = new WorkboardResponse();
3055
-	        $response->warning_delay = $delay_warning/60/60/24;
3055
+	        $response->warning_delay = $delay_warning / 60 / 60 / 24;
3056 3056
 	        $response->label = $label;
3057 3057
 	        $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals';
3058 3058
 	        $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
3059
-	        $response->img = img_object('',"propal");
3059
+	        $response->img = img_object('', "propal");
3060 3060
 
3061 3061
             // This assignment in condition is not a bug. It allows walking the results.
3062
-            while ($obj=$this->db->fetch_object($resql))
3062
+            while ($obj = $this->db->fetch_object($resql))
3063 3063
             {
3064 3064
                 $response->nbtodo++;
3065 3065
                 if ($mode == 'opened')
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
         }
3079 3079
         else
3080 3080
         {
3081
-            $this->error=$this->db->error();
3081
+            $this->error = $this->db->error();
3082 3082
             return -1;
3083 3083
         }
3084 3084
     }
@@ -3099,8 +3099,8 @@  discard block
 block discarded – undo
3099 3099
         $num_prods = 0;
3100 3100
         $prodids = array();
3101 3101
         $sql = "SELECT rowid";
3102
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
3103
-        $sql.= " WHERE entity IN (".getEntity('product').")";
3102
+        $sql .= " FROM ".MAIN_DB_PREFIX."product";
3103
+        $sql .= " WHERE entity IN (".getEntity('product').")";
3104 3104
         $resql = $this->db->query($sql);
3105 3105
         if ($resql)
3106 3106
         {
@@ -3115,13 +3115,13 @@  discard block
 block discarded – undo
3115 3115
         }
3116 3116
 
3117 3117
         // Initialise parametres
3118
-        $this->id=0;
3118
+        $this->id = 0;
3119 3119
         $this->ref = 'SPECIMEN';
3120
-        $this->ref_client='NEMICEPS';
3121
-        $this->specimen=1;
3120
+        $this->ref_client = 'NEMICEPS';
3121
+        $this->specimen = 1;
3122 3122
         $this->socid = 1;
3123 3123
         $this->date = time();
3124
-        $this->fin_validite = $this->date+3600*24*30;
3124
+        $this->fin_validite = $this->date + 3600 * 24 * 30;
3125 3125
         $this->cond_reglement_id   = 1;
3126 3126
         $this->cond_reglement_code = 'RECEP';
3127 3127
         $this->mode_reglement_id   = 7;
@@ -3130,44 +3130,44 @@  discard block
 block discarded – undo
3130 3130
         $this->availability_code   = 'AV_NOW';
3131 3131
         $this->demand_reason_id    = 1;
3132 3132
         $this->demand_reason_code  = 'SRC_00';
3133
-        $this->note_public='This is a comment (public)';
3134
-        $this->note_private='This is a comment (private)';
3133
+        $this->note_public = 'This is a comment (public)';
3134
+        $this->note_private = 'This is a comment (private)';
3135 3135
         // Lines
3136 3136
         $nbp = 5;
3137 3137
         $xnbp = 0;
3138 3138
         while ($xnbp < $nbp)
3139 3139
         {
3140
-            $line=new PropaleLigne($this->db);
3141
-            $line->desc=$langs->trans("Description")." ".$xnbp;
3142
-            $line->qty=1;
3143
-            $line->subprice=100;
3144
-            $line->price=100;
3145
-            $line->tva_tx=20;
3146
-            $line->localtax1_tx=0;
3147
-            $line->localtax2_tx=0;
3140
+            $line = new PropaleLigne($this->db);
3141
+            $line->desc = $langs->trans("Description")." ".$xnbp;
3142
+            $line->qty = 1;
3143
+            $line->subprice = 100;
3144
+            $line->price = 100;
3145
+            $line->tva_tx = 20;
3146
+            $line->localtax1_tx = 0;
3147
+            $line->localtax2_tx = 0;
3148 3148
             if ($xnbp == 2)
3149 3149
             {
3150
-                $line->total_ht=50;
3151
-                $line->total_ttc=60;
3152
-                $line->total_tva=10;
3153
-                $line->remise_percent=50;
3150
+                $line->total_ht = 50;
3151
+                $line->total_ttc = 60;
3152
+                $line->total_tva = 10;
3153
+                $line->remise_percent = 50;
3154 3154
             }
3155 3155
             else
3156 3156
             {
3157
-                $line->total_ht=100;
3158
-                $line->total_ttc=120;
3159
-                $line->total_tva=20;
3160
-                $line->remise_percent=00;
3157
+                $line->total_ht = 100;
3158
+                $line->total_ttc = 120;
3159
+                $line->total_tva = 20;
3160
+                $line->remise_percent = 00;
3161 3161
             }
3162 3162
 
3163 3163
             if ($num_prods > 0)
3164 3164
             {
3165 3165
             	$prodid = mt_rand(1, $num_prods);
3166
-            	$line->fk_product=$prodids[$prodid];
3167
-		$line->product_ref='SPECIMEN';
3166
+            	$line->fk_product = $prodids[$prodid];
3167
+		$line->product_ref = 'SPECIMEN';
3168 3168
             }
3169 3169
 
3170
-            $this->lines[$xnbp]=$line;
3170
+            $this->lines[$xnbp] = $line;
3171 3171
 
3172 3172
             $this->total_ht       += $line->total_ht;
3173 3173
             $this->total_tva      += $line->total_tva;
@@ -3186,27 +3186,27 @@  discard block
 block discarded – undo
3186 3186
     {
3187 3187
         global $user;
3188 3188
 
3189
-        $this->nb=array();
3189
+        $this->nb = array();
3190 3190
         $clause = "WHERE";
3191 3191
 
3192 3192
         $sql = "SELECT count(p.rowid) as nb";
3193
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
3194
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3193
+        $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3194
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3195 3195
         if (!$user->rights->societe->client->voir && !$user->societe_id)
3196 3196
         {
3197
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3198
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3197
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3198
+            $sql .= " WHERE sc.fk_user = ".$user->id;
3199 3199
             $clause = "AND";
3200 3200
         }
3201
-        $sql.= " ".$clause." p.entity IN (".getEntity('propal').")";
3201
+        $sql .= " ".$clause." p.entity IN (".getEntity('propal').")";
3202 3202
 
3203
-        $resql=$this->db->query($sql);
3203
+        $resql = $this->db->query($sql);
3204 3204
         if ($resql)
3205 3205
         {
3206 3206
             // This assignment in condition is not a bug. It allows walking the results.
3207
-            while ($obj=$this->db->fetch_object($resql))
3207
+            while ($obj = $this->db->fetch_object($resql))
3208 3208
             {
3209
-                $this->nb["proposals"]=$obj->nb;
3209
+                $this->nb["proposals"] = $obj->nb;
3210 3210
             }
3211 3211
             $this->db->free($resql);
3212 3212
             return 1;
@@ -3214,7 +3214,7 @@  discard block
 block discarded – undo
3214 3214
         else
3215 3215
         {
3216 3216
             dol_print_error($this->db);
3217
-            $this->error=$this->db->error();
3217
+            $this->error = $this->db->error();
3218 3218
             return -1;
3219 3219
         }
3220 3220
     }
@@ -3229,12 +3229,12 @@  discard block
 block discarded – undo
3229 3229
      */
3230 3230
     function getNextNumRef($soc)
3231 3231
     {
3232
-        global $conf,$langs;
3232
+        global $conf, $langs;
3233 3233
         $langs->load("propal");
3234 3234
 
3235
-        if (! empty($conf->global->PROPALE_ADDON))
3235
+        if (!empty($conf->global->PROPALE_ADDON))
3236 3236
         {
3237
-        	$mybool=false;
3237
+        	$mybool = false;
3238 3238
 
3239 3239
             $file = $conf->global->PROPALE_ADDON.".php";
3240 3240
             $classname = $conf->global->PROPALE_ADDON;
@@ -3246,18 +3246,18 @@  discard block
 block discarded – undo
3246 3246
                 $dir = dol_buildpath($reldir."core/modules/propale/");
3247 3247
 
3248 3248
                 // Load file with numbering class (if found)
3249
-                $mybool|=@include_once $dir.$file;
3249
+                $mybool |= @include_once $dir.$file;
3250 3250
             }
3251 3251
 
3252
-            if (! $mybool)
3252
+            if (!$mybool)
3253 3253
             {
3254
-            	dol_print_error('',"Failed to include file ".$file);
3254
+            	dol_print_error('', "Failed to include file ".$file);
3255 3255
             	return '';
3256 3256
             }
3257 3257
 
3258 3258
             $obj = new $classname();
3259 3259
             $numref = "";
3260
-            $numref = $obj->getNextValue($soc,$this);
3260
+            $numref = $obj->getNextValue($soc, $this);
3261 3261
 
3262 3262
             if ($numref != "")
3263 3263
             {
@@ -3265,7 +3265,7 @@  discard block
 block discarded – undo
3265 3265
             }
3266 3266
             else
3267 3267
 			{
3268
-                $this->error=$obj->error;
3268
+                $this->error = $obj->error;
3269 3269
                 //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3270 3270
                 return "";
3271 3271
             }
@@ -3288,72 +3288,72 @@  discard block
 block discarded – undo
3288 3288
      *  @param      int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3289 3289
      *	@return     string          		          String with URL
3290 3290
      */
3291
-    function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1)
3291
+    function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1)
3292 3292
     {
3293 3293
         global $langs, $conf, $user;
3294 3294
 
3295
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3295
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
3296 3296
 
3297
-        $result='';
3298
-        $label='';
3299
-        $url='';
3297
+        $result = '';
3298
+        $label = '';
3299
+        $url = '';
3300 3300
 
3301 3301
         if ($user->rights->propal->lire)
3302 3302
         {
3303
-            $label = '<u>' . $langs->trans("ShowPropal") . '</u>';
3304
-            if (! empty($this->ref))
3305
-                $label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3306
-            if (! empty($this->ref_client))
3307
-                $label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3308
-            if (! empty($this->total_ht))
3309
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3310
-            if (! empty($this->total_tva))
3311
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3312
-            if (! empty($this->total_ttc))
3313
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3303
+            $label = '<u>'.$langs->trans("ShowPropal").'</u>';
3304
+            if (!empty($this->ref))
3305
+                $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3306
+            if (!empty($this->ref_client))
3307
+                $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3308
+            if (!empty($this->total_ht))
3309
+                $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3310
+            if (!empty($this->total_tva))
3311
+                $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3312
+            if (!empty($this->total_ttc))
3313
+                $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3314 3314
             if ($option == '') {
3315
-                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3315
+                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
3316 3316
             }
3317 3317
             if ($option == 'compta') {  // deprecated
3318
-                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3318
+                $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
3319 3319
             }
3320 3320
             if ($option == 'expedition') {
3321
-                $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params;
3321
+                $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id.$get_params;
3322 3322
             }
3323 3323
             if ($option == 'document') {
3324
-                $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params;
3324
+                $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id.$get_params;
3325 3325
             }
3326 3326
 
3327 3327
             if ($option != 'nolink')
3328 3328
             {
3329 3329
                 // Add param to save lastsearch_values or not
3330
-                $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3331
-                if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3332
-                if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3330
+                $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3331
+                if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
3332
+                if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
3333 3333
             }
3334 3334
         }
3335 3335
 
3336
-        $linkclose='';
3336
+        $linkclose = '';
3337 3337
         if (empty($notooltip) && $user->rights->propal->lire)
3338 3338
         {
3339
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3339
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3340 3340
             {
3341
-                $label=$langs->trans("ShowPropal");
3342
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3341
+                $label = $langs->trans("ShowPropal");
3342
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3343 3343
             }
3344
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3345
-            $linkclose.=' class="classfortooltip"';
3344
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
3345
+            $linkclose .= ' class="classfortooltip"';
3346 3346
         }
3347 3347
 
3348 3348
         $linkstart = '<a href="'.$url.'"';
3349
-        $linkstart.=$linkclose.'>';
3350
-        $linkend='</a>';
3349
+        $linkstart .= $linkclose.'>';
3350
+        $linkend = '</a>';
3351 3351
 
3352 3352
         if ($withpicto)
3353
-            $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3353
+            $result .= ($linkstart.img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
3354 3354
         if ($withpicto && $withpicto != 2)
3355
-            $result.=' ';
3356
-        $result.=$linkstart.$this->ref.$linkend;
3355
+            $result .= ' ';
3356
+        $result .= $linkstart.$this->ref.$linkend;
3357 3357
         return $result;
3358 3358
     }
3359 3359
 
@@ -3369,17 +3369,17 @@  discard block
 block discarded – undo
3369 3369
         $this->lines = array();
3370 3370
 
3371 3371
         $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
3372
-        $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,';
3373
-        $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,';
3374
-        $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,';
3375
-	    $sql.= ' pt.fk_unit,';
3376
-        $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,';
3377
-        $sql.= ' p.entity,';
3378
-		$sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc';
3379
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt';
3380
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
3381
-        $sql.= ' WHERE pt.fk_propal = '.$this->id;
3382
-        $sql.= ' ORDER BY pt.rang ASC, pt.rowid';
3372
+        $sql .= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,';
3373
+        $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,';
3374
+        $sql .= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,';
3375
+	    $sql .= ' pt.fk_unit,';
3376
+        $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,';
3377
+        $sql .= ' p.entity,';
3378
+		$sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc';
3379
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt';
3380
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
3381
+        $sql .= ' WHERE pt.fk_propal = '.$this->id;
3382
+        $sql .= ' ORDER BY pt.rang ASC, pt.rowid';
3383 3383
 
3384 3384
         dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
3385 3385
         $resql = $this->db->query($sql);
@@ -3392,53 +3392,53 @@  discard block
 block discarded – undo
3392 3392
             {
3393 3393
                 $obj = $this->db->fetch_object($resql);
3394 3394
 
3395
-                $this->lines[$i]					= new PropaleLigne($this->db);
3396
-                $this->lines[$i]->id				= $obj->rowid; // for backward compatibility
3395
+                $this->lines[$i] = new PropaleLigne($this->db);
3396
+                $this->lines[$i]->id = $obj->rowid; // for backward compatibility
3397 3397
                 $this->lines[$i]->rowid				= $obj->rowid;
3398 3398
                 $this->lines[$i]->label 			= $obj->custom_label;
3399
-                $this->lines[$i]->desc       		= $obj->description;
3400
-                $this->lines[$i]->description 		= $obj->description;
3401
-                $this->lines[$i]->fk_product		= $obj->fk_product;
3402
-                $this->lines[$i]->ref				= $obj->ref;
3403
-                $this->lines[$i]->product_ref		= $obj->ref;
3404
-                $this->lines[$i]->entity            = $obj->entity;             // Product entity
3405
-                $this->lines[$i]->product_label		= $obj->product_label;
3399
+                $this->lines[$i]->desc = $obj->description;
3400
+                $this->lines[$i]->description = $obj->description;
3401
+                $this->lines[$i]->fk_product = $obj->fk_product;
3402
+                $this->lines[$i]->ref = $obj->ref;
3403
+                $this->lines[$i]->product_ref = $obj->ref;
3404
+                $this->lines[$i]->entity            = $obj->entity; // Product entity
3405
+                $this->lines[$i]->product_label = $obj->product_label;
3406 3406
                 $this->lines[$i]->product_desc		= $obj->product_desc;
3407 3407
                 $this->lines[$i]->product_tobatch   = $obj->product_tobatch;
3408
-                $this->lines[$i]->fk_product_type	= $obj->fk_product_type;    // deprecated
3408
+                $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated
3409 3409
                 $this->lines[$i]->product_type		= $obj->product_type;
3410
-                $this->lines[$i]->qty				= $obj->qty;
3411
-                $this->lines[$i]->subprice			= $obj->subprice;
3410
+                $this->lines[$i]->qty = $obj->qty;
3411
+                $this->lines[$i]->subprice = $obj->subprice;
3412 3412
                 $this->lines[$i]->fk_remise_except 	= $obj->fk_remise_except;
3413
-                $this->lines[$i]->remise_percent	= $obj->remise_percent;
3413
+                $this->lines[$i]->remise_percent = $obj->remise_percent;
3414 3414
 
3415 3415
                 $this->lines[$i]->vat_src_code      = $obj->vat_src_code;
3416
-                $this->lines[$i]->tva_tx			= $obj->tva_tx;
3416
+                $this->lines[$i]->tva_tx = $obj->tva_tx;
3417 3417
                 $this->lines[$i]->localtax1_tx		= $obj->localtax1_tx;
3418 3418
                 $this->lines[$i]->localtax2_tx		= $obj->localtax2_tx;
3419 3419
                 $this->lines[$i]->localtax1_type	= $obj->localtax1_type;
3420 3420
                 $this->lines[$i]->localtax2_type	= $obj->localtax2_type;
3421 3421
                 $this->lines[$i]->info_bits			= $obj->info_bits;
3422
-                $this->lines[$i]->total_ht			= $obj->total_ht;
3422
+                $this->lines[$i]->total_ht = $obj->total_ht;
3423 3423
                 $this->lines[$i]->total_tva			= $obj->total_tva;
3424 3424
                 $this->lines[$i]->total_ttc			= $obj->total_ttc;
3425 3425
                 $this->lines[$i]->total_localtax1	= $obj->total_localtax1;
3426 3426
                 $this->lines[$i]->total_localtax2	= $obj->total_localtax2;
3427
-                $this->lines[$i]->fk_fournprice		= $obj->fk_fournprice;
3428
-				$marginInfos						= getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
3429
-				$this->lines[$i]->pa_ht				= $marginInfos[0];
3430
-				$this->lines[$i]->marge_tx			= $marginInfos[1];
3431
-				$this->lines[$i]->marque_tx			= $marginInfos[2];
3432
-				$this->lines[$i]->fk_parent_line	= $obj->fk_parent_line;
3433
-                $this->lines[$i]->special_code		= $obj->special_code;
3434
-                $this->lines[$i]->rang				= $obj->rang;
3435
-                $this->lines[$i]->date_start		= $this->db->jdate($obj->date_start);
3436
-                $this->lines[$i]->date_end			= $this->db->jdate($obj->date_end);
3437
-	            $this->lines[$i]->fk_unit			= $obj->fk_unit;
3427
+                $this->lines[$i]->fk_fournprice = $obj->fk_fournprice;
3428
+				$marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
3429
+				$this->lines[$i]->pa_ht = $marginInfos[0];
3430
+				$this->lines[$i]->marge_tx = $marginInfos[1];
3431
+				$this->lines[$i]->marque_tx = $marginInfos[2];
3432
+				$this->lines[$i]->fk_parent_line = $obj->fk_parent_line;
3433
+                $this->lines[$i]->special_code = $obj->special_code;
3434
+                $this->lines[$i]->rang = $obj->rang;
3435
+                $this->lines[$i]->date_start = $this->db->jdate($obj->date_start);
3436
+                $this->lines[$i]->date_end = $this->db->jdate($obj->date_end);
3437
+	            $this->lines[$i]->fk_unit = $obj->fk_unit;
3438 3438
 
3439 3439
 				// Multicurrency
3440
-				$this->lines[$i]->fk_multicurrency 			= $obj->fk_multicurrency;
3441
-				$this->lines[$i]->multicurrency_code 		= $obj->multicurrency_code;
3440
+				$this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency;
3441
+				$this->lines[$i]->multicurrency_code = $obj->multicurrency_code;
3442 3442
 				$this->lines[$i]->multicurrency_subprice 	= $obj->multicurrency_subprice;
3443 3443
 				$this->lines[$i]->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
3444 3444
 				$this->lines[$i]->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
@@ -3452,7 +3452,7 @@  discard block
 block discarded – undo
3452 3452
         }
3453 3453
         else
3454 3454
         {
3455
-            $this->error=$this->db->error();
3455
+            $this->error = $this->db->error();
3456 3456
             return -1;
3457 3457
         }
3458 3458
     }
@@ -3467,19 +3467,19 @@  discard block
 block discarded – undo
3467 3467
 	 *  @param      int			$hideref        Hide ref
3468 3468
 	 * 	@return     int         				0 if KO, 1 if OK
3469 3469
 	 */
3470
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
3470
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
3471 3471
 	{
3472
-		global $conf,$langs;
3472
+		global $conf, $langs;
3473 3473
 
3474 3474
 		$langs->load("propale");
3475 3475
 
3476
-		if (! dol_strlen($modele)) {
3476
+		if (!dol_strlen($modele)) {
3477 3477
 
3478 3478
 			$modele = 'azur';
3479 3479
 
3480 3480
 			if ($this->modelpdf) {
3481 3481
 				$modele = $this->modelpdf;
3482
-			} elseif (! empty($conf->global->PROPALE_ADDON_PDF)) {
3482
+			} elseif (!empty($conf->global->PROPALE_ADDON_PDF)) {
3483 3483
 				$modele = $conf->global->PROPALE_ADDON_PDF;
3484 3484
 			}
3485 3485
 		}
@@ -3513,16 +3513,16 @@  discard block
 block discarded – undo
3513 3513
  */
3514 3514
 class PropaleLigne extends CommonObjectLine
3515 3515
 {
3516
-    public $element='propaldet';
3517
-    public $table_element='propaldet';
3516
+    public $element = 'propaldet';
3517
+    public $table_element = 'propaldet';
3518 3518
 
3519 3519
     var $oldline;
3520 3520
 
3521 3521
     // From llx_propaldet
3522 3522
     var $fk_propal;
3523 3523
     var $fk_parent_line;
3524
-    var $desc;          	// Description ligne
3525
-    var $fk_product;		// Id produit predefini
3524
+    var $desc; // Description ligne
3525
+    var $fk_product; // Id produit predefini
3526 3526
 	/**
3527 3527
 	 * @deprecated
3528 3528
 	 * @see product_type
@@ -3548,18 +3548,18 @@  discard block
 block discarded – undo
3548 3548
 	var $marge_tx;
3549 3549
 	var $marque_tx;
3550 3550
 
3551
-    var $special_code;	// Tag for special lines (exlusive tags)
3551
+    var $special_code; // Tag for special lines (exlusive tags)
3552 3552
     // 1: frais de port
3553 3553
     // 2: ecotaxe
3554 3554
     // 3: option line (when qty = 0)
3555 3555
 
3556
-    var $info_bits = 0;	// Liste d'options cumulables:
3556
+    var $info_bits = 0; // Liste d'options cumulables:
3557 3557
     // Bit 0: 	0 si TVA normal - 1 si TVA NPR
3558 3558
     // Bit 1:	0 ligne normale - 1 si ligne de remise fixe
3559 3559
 
3560
-    var $total_ht;			// Total HT  de la ligne toute quantite et incluant la remise ligne
3561
-    var $total_tva;			// Total TVA  de la ligne toute quantite et incluant la remise ligne
3562
-    var $total_ttc;			// Total TTC de la ligne toute quantite et incluant la remise ligne
3560
+    var $total_ht; // Total HT  de la ligne toute quantite et incluant la remise ligne
3561
+    var $total_tva; // Total TVA  de la ligne toute quantite et incluant la remise ligne
3562
+    var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne
3563 3563
 
3564 3564
 	/**
3565 3565
 	 * @deprecated
@@ -3599,12 +3599,12 @@  discard block
 block discarded – undo
3599 3599
 	 */
3600 3600
     public $product_desc;
3601 3601
 
3602
-    var $localtax1_tx;		// Local tax 1
3603
-    var $localtax2_tx;		// Local tax 2
3604
-    var $localtax1_type;	// Local tax 1 type
3605
-	var $localtax2_type;	// Local tax 2 type
3606
-    var $total_localtax1;  	// Line total local tax 1
3607
-    var $total_localtax2;	// Line total local tax 2
3602
+    var $localtax1_tx; // Local tax 1
3603
+    var $localtax2_tx; // Local tax 2
3604
+    var $localtax1_type; // Local tax 1 type
3605
+	var $localtax2_type; // Local tax 2 type
3606
+    var $total_localtax1; // Line total local tax 1
3607
+    var $total_localtax2; // Line total local tax 2
3608 3608
 
3609 3609
     var $date_start;
3610 3610
     var $date_end;
@@ -3626,7 +3626,7 @@  discard block
 block discarded – undo
3626 3626
      */
3627 3627
     function __construct($db)
3628 3628
     {
3629
-        $this->db= $db;
3629
+        $this->db = $db;
3630 3630
     }
3631 3631
 
3632 3632
     /**
@@ -3638,44 +3638,44 @@  discard block
 block discarded – undo
3638 3638
 	function fetch($rowid)
3639 3639
 	{
3640 3640
 		$sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,';
3641
-		$sql.= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
3642
-		$sql.= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
3643
-		$sql.= ' pd.fk_unit,';
3644
-		$sql.= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
3645
-		$sql.= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,';
3646
-		$sql.= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
3647
-		$sql.= ' pd.date_start, pd.date_end, pd.product_type';
3648
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd';
3649
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
3650
-		$sql.= ' WHERE pd.rowid = '.$rowid;
3641
+		$sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
3642
+		$sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
3643
+		$sql .= ' pd.fk_unit,';
3644
+		$sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
3645
+		$sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,';
3646
+		$sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
3647
+		$sql .= ' pd.date_start, pd.date_end, pd.product_type';
3648
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd';
3649
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
3650
+		$sql .= ' WHERE pd.rowid = '.$rowid;
3651 3651
 
3652 3652
 		$result = $this->db->query($sql);
3653 3653
 		if ($result)
3654 3654
 		{
3655 3655
 			$objp = $this->db->fetch_object($result);
3656 3656
 
3657
-			$this->id               = $objp->rowid;
3658
-			$this->rowid			= $objp->rowid;     // deprecated
3659
-			$this->fk_propal		= $objp->fk_propal;
3660
-			$this->fk_parent_line	= $objp->fk_parent_line;
3657
+			$this->id = $objp->rowid;
3658
+			$this->rowid			= $objp->rowid; // deprecated
3659
+			$this->fk_propal = $objp->fk_propal;
3660
+			$this->fk_parent_line = $objp->fk_parent_line;
3661 3661
 			$this->label			= $objp->custom_label;
3662 3662
 			$this->desc				= $objp->description;
3663
-			$this->qty				= $objp->qty;
3664
-			$this->price			= $objp->price;		// deprecated
3665
-			$this->subprice			= $objp->subprice;
3666
-			$this->vat_src_code		= $objp->vat_src_code;
3663
+			$this->qty = $objp->qty;
3664
+			$this->price			= $objp->price; // deprecated
3665
+			$this->subprice = $objp->subprice;
3666
+			$this->vat_src_code = $objp->vat_src_code;
3667 3667
 			$this->tva_tx			= $objp->tva_tx;
3668
-			$this->remise			= $objp->remise;    // deprecated
3669
-			$this->remise_percent	= $objp->remise_percent;
3668
+			$this->remise			= $objp->remise; // deprecated
3669
+			$this->remise_percent = $objp->remise_percent;
3670 3670
 			$this->fk_remise_except = $objp->fk_remise_except;
3671
-			$this->fk_product		= $objp->fk_product;
3671
+			$this->fk_product = $objp->fk_product;
3672 3672
 			$this->info_bits		= $objp->info_bits;
3673 3673
 
3674 3674
 			$this->total_ht			= $objp->total_ht;
3675 3675
 			$this->total_tva		= $objp->total_tva;
3676 3676
 			$this->total_ttc		= $objp->total_ttc;
3677 3677
 
3678
-			$this->fk_fournprice	= $objp->fk_fournprice;
3678
+			$this->fk_fournprice = $objp->fk_fournprice;
3679 3679
 
3680 3680
 			$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
3681 3681
 			$this->pa_ht			= $marginInfos[0];
@@ -3684,21 +3684,21 @@  discard block
 block discarded – undo
3684 3684
 
3685 3685
 			$this->special_code		= $objp->special_code;
3686 3686
 			$this->product_type		= $objp->product_type;
3687
-			$this->rang				= $objp->rang;
3687
+			$this->rang = $objp->rang;
3688 3688
 
3689
-			$this->ref				= $objp->product_ref;      // deprecated
3690
-			$this->product_ref		= $objp->product_ref;
3691
-			$this->libelle			= $objp->product_label;  // deprecated
3689
+			$this->ref = $objp->product_ref; // deprecated
3690
+			$this->product_ref = $objp->product_ref;
3691
+			$this->libelle = $objp->product_label; // deprecated
3692 3692
 			$this->product_label	= $objp->product_label;
3693 3693
 			$this->product_desc		= $objp->product_desc;
3694 3694
 			$this->fk_unit          = $objp->fk_unit;
3695 3695
 
3696 3696
 			$this->date_start       = $this->db->jdate($objp->date_start);
3697
-            $this->date_end         = $this->db->jdate($objp->date_end);
3697
+            $this->date_end = $this->db->jdate($objp->date_end);
3698 3698
 
3699 3699
 			// Multicurrency
3700
-			$this->fk_multicurrency 		= $objp->fk_multicurrency;
3701
-			$this->multicurrency_code 		= $objp->multicurrency_code;
3700
+			$this->fk_multicurrency = $objp->fk_multicurrency;
3701
+			$this->multicurrency_code = $objp->multicurrency_code;
3702 3702
 			$this->multicurrency_subprice 	= $objp->multicurrency_subprice;
3703 3703
 			$this->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
3704 3704
 			$this->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
@@ -3720,37 +3720,37 @@  discard block
 block discarded – undo
3720 3720
      *	@param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
3721 3721
      *	@return		int						<0 if KO, >0 if OK
3722 3722
      */
3723
-    function insert($notrigger=0)
3723
+    function insert($notrigger = 0)
3724 3724
     {
3725
-        global $conf,$user;
3725
+        global $conf, $user;
3726 3726
 
3727
-        $error=0;
3727
+        $error = 0;
3728 3728
 
3729 3729
         dol_syslog(get_class($this)."::insert rang=".$this->rang);
3730 3730
 
3731 3731
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3732 3732
 
3733 3733
         // Clean parameters
3734
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3735
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3736
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3737
-        if (empty($this->localtax1_type)) $this->localtax1_type=0;
3738
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3739
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3740
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3741
-        if (empty($this->rang)) $this->rang=0;
3742
-        if (empty($this->remise)) $this->remise=0;
3743
-        if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0;
3744
-        if (empty($this->info_bits)) $this->info_bits=0;
3745
-        if (empty($this->special_code)) $this->special_code=0;
3746
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3747
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3748
-		if (! is_numeric($this->qty)) $this->qty = 0;
3749
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3750
-        if (empty($this->multicurrency_subprice))  $this->multicurrency_subprice=0;
3751
-        if (empty($this->multicurrency_total_ht))  $this->multicurrency_total_ht=0;
3752
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
3753
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
3734
+        if (empty($this->tva_tx)) $this->tva_tx = 0;
3735
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
3736
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
3737
+        if (empty($this->localtax1_type)) $this->localtax1_type = 0;
3738
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
3739
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
3740
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
3741
+        if (empty($this->rang)) $this->rang = 0;
3742
+        if (empty($this->remise)) $this->remise = 0;
3743
+        if (empty($this->remise_percent) || !is_numeric($this->remise_percent)) $this->remise_percent = 0;
3744
+        if (empty($this->info_bits)) $this->info_bits = 0;
3745
+        if (empty($this->special_code)) $this->special_code = 0;
3746
+        if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
3747
+        if (empty($this->fk_fournprice)) $this->fk_fournprice = 0;
3748
+		if (!is_numeric($this->qty)) $this->qty = 0;
3749
+        if (empty($this->pa_ht)) $this->pa_ht = 0;
3750
+        if (empty($this->multicurrency_subprice))  $this->multicurrency_subprice = 0;
3751
+        if (empty($this->multicurrency_total_ht))  $this->multicurrency_total_ht = 0;
3752
+        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
3753
+        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
3754 3754
 
3755 3755
        // if buy price not defined, define buyprice as configured in margin admin
3756 3756
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3772,71 +3772,71 @@  discard block
 block discarded – undo
3772 3772
 
3773 3773
         // Insert line into database
3774 3774
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet';
3775
-        $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
3776
-		$sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3777
-        $sql.= ' subprice, remise_percent, ';
3778
-        $sql.= ' info_bits, ';
3779
-        $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
3780
-	    $sql.= ' fk_unit,';
3781
-        $sql.= ' date_start, date_end';
3782
-		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)';
3783
-        $sql.= " VALUES (".$this->fk_propal.",";
3784
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3785
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
3786
-        $sql.= " '".$this->db->escape($this->desc)."',";
3787
-        $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").",";
3788
-        $sql.= " '".$this->db->escape($this->product_type)."',";
3789
-        $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").",";
3790
-        $sql.= " ".price2num($this->qty).",";
3791
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3792
-        $sql.= " ".price2num($this->tva_tx).",";
3793
-        $sql.= " ".price2num($this->localtax1_tx).",";
3794
-        $sql.= " ".price2num($this->localtax2_tx).",";
3795
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
3796
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
3797
-        $sql.= " ".($this->subprice?price2num($this->subprice):"null").",";
3798
-        $sql.= " ".price2num($this->remise_percent).",";
3799
-        $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").",";
3800
-        $sql.= " ".price2num($this->total_ht).",";
3801
-        $sql.= " ".price2num($this->total_tva).",";
3802
-        $sql.= " ".price2num($this->total_localtax1).",";
3803
-        $sql.= " ".price2num($this->total_localtax2).",";
3804
-        $sql.= " ".price2num($this->total_ttc).",";
3805
-        $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").",";
3806
-        $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").",";
3807
-        $sql.= ' '.$this->special_code.',';
3808
-        $sql.= ' '.$this->rang.',';
3809
-	    $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).',';
3810
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
3811
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3812
-		$sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null');
3813
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3814
-		$sql.= ", ".$this->multicurrency_subprice;
3815
-		$sql.= ", ".$this->multicurrency_total_ht;
3816
-		$sql.= ", ".$this->multicurrency_total_tva;
3817
-		$sql.= ", ".$this->multicurrency_total_ttc;
3818
-        $sql.= ')';
3775
+        $sql .= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
3776
+		$sql .= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3777
+        $sql .= ' subprice, remise_percent, ';
3778
+        $sql .= ' info_bits, ';
3779
+        $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
3780
+	    $sql .= ' fk_unit,';
3781
+        $sql .= ' date_start, date_end';
3782
+		$sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)';
3783
+        $sql .= " VALUES (".$this->fk_propal.",";
3784
+        $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
3785
+        $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
3786
+        $sql .= " '".$this->db->escape($this->desc)."',";
3787
+        $sql .= " ".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : "null").",";
3788
+        $sql .= " '".$this->db->escape($this->product_type)."',";
3789
+        $sql .= " ".($this->fk_remise_except ? "'".$this->db->escape($this->fk_remise_except)."'" : "null").",";
3790
+        $sql .= " ".price2num($this->qty).",";
3791
+        $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
3792
+        $sql .= " ".price2num($this->tva_tx).",";
3793
+        $sql .= " ".price2num($this->localtax1_tx).",";
3794
+        $sql .= " ".price2num($this->localtax2_tx).",";
3795
+		$sql .= " '".$this->db->escape($this->localtax1_type)."',";
3796
+		$sql .= " '".$this->db->escape($this->localtax2_type)."',";
3797
+        $sql .= " ".($this->subprice ?price2num($this->subprice) : "null").",";
3798
+        $sql .= " ".price2num($this->remise_percent).",";
3799
+        $sql .= " ".(isset($this->info_bits) ? "'".$this->db->escape($this->info_bits)."'" : "null").",";
3800
+        $sql .= " ".price2num($this->total_ht).",";
3801
+        $sql .= " ".price2num($this->total_tva).",";
3802
+        $sql .= " ".price2num($this->total_localtax1).",";
3803
+        $sql .= " ".price2num($this->total_localtax2).",";
3804
+        $sql .= " ".price2num($this->total_ttc).",";
3805
+        $sql .= " ".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null").",";
3806
+        $sql .= " ".(isset($this->pa_ht) ? "'".price2num($this->pa_ht)."'" : "null").",";
3807
+        $sql .= ' '.$this->special_code.',';
3808
+        $sql .= ' '.$this->rang.',';
3809
+	    $sql .= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).',';
3810
+        $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
3811
+        $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
3812
+		$sql .= ", ".($this->fk_multicurrency > 0 ? $this->fk_multicurrency : 'null');
3813
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
3814
+		$sql .= ", ".$this->multicurrency_subprice;
3815
+		$sql .= ", ".$this->multicurrency_total_ht;
3816
+		$sql .= ", ".$this->multicurrency_total_tva;
3817
+		$sql .= ", ".$this->multicurrency_total_ttc;
3818
+        $sql .= ')';
3819 3819
 
3820 3820
         dol_syslog(get_class($this).'::insert', LOG_DEBUG);
3821
-        $resql=$this->db->query($sql);
3821
+        $resql = $this->db->query($sql);
3822 3822
         if ($resql)
3823 3823
         {
3824
-            $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
3824
+            $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
3825 3825
 
3826 3826
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3827 3827
             {
3828
-            	$this->id=$this->rowid;
3829
-            	$result=$this->insertExtraFields();
3828
+            	$this->id = $this->rowid;
3829
+            	$result = $this->insertExtraFields();
3830 3830
             	if ($result < 0)
3831 3831
             	{
3832 3832
             		$error++;
3833 3833
             	}
3834 3834
             }
3835 3835
 
3836
-            if (! $notrigger)
3836
+            if (!$notrigger)
3837 3837
             {
3838 3838
                 // Call trigger
3839
-                $result=$this->call_trigger('LINEPROPAL_INSERT',$user);
3839
+                $result = $this->call_trigger('LINEPROPAL_INSERT', $user);
3840 3840
                 if ($result < 0)
3841 3841
                 {
3842 3842
                     $this->db->rollback();
@@ -3850,7 +3850,7 @@  discard block
 block discarded – undo
3850 3850
         }
3851 3851
         else
3852 3852
         {
3853
-            $this->error=$this->db->error()." sql=".$sql;
3853
+            $this->error = $this->db->error()." sql=".$sql;
3854 3854
             $this->db->rollback();
3855 3855
             return -1;
3856 3856
         }
@@ -3862,23 +3862,23 @@  discard block
 block discarded – undo
3862 3862
      *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3863 3863
      *	@return	 int  <0 if ko, >0 if ok
3864 3864
      */
3865
-    function delete($notrigger=0)
3865
+    function delete($notrigger = 0)
3866 3866
     {
3867
-        global $conf,$user;
3867
+        global $conf, $user;
3868 3868
 
3869
-        $error=0;
3869
+        $error = 0;
3870 3870
         $this->db->begin();
3871 3871
 
3872 3872
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid;
3873 3873
         dol_syslog("PropaleLigne::delete", LOG_DEBUG);
3874
-        if ($this->db->query($sql) )
3874
+        if ($this->db->query($sql))
3875 3875
         {
3876 3876
 
3877 3877
         	// Remove extrafields
3878
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3878
+        	if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3879 3879
         	{
3880
-        		$this->id=$this->rowid;
3881
-        		$result=$this->deleteExtraFields();
3880
+        		$this->id = $this->rowid;
3881
+        		$result = $this->deleteExtraFields();
3882 3882
         		if ($result < 0)
3883 3883
         		{
3884 3884
         			$error++;
@@ -3886,10 +3886,10 @@  discard block
 block discarded – undo
3886 3886
         		}
3887 3887
         	}
3888 3888
 
3889
-        	if (! $error && ! $notrigger)
3889
+        	if (!$error && !$notrigger)
3890 3890
         	{
3891 3891
 	            // Call trigger
3892
-	            $result=$this->call_trigger('LINEPROPAL_DELETE',$user);
3892
+	            $result = $this->call_trigger('LINEPROPAL_DELETE', $user);
3893 3893
 	            if ($result < 0)
3894 3894
 	            {
3895 3895
 	                $this->db->rollback();
@@ -3904,7 +3904,7 @@  discard block
 block discarded – undo
3904 3904
         }
3905 3905
         else
3906 3906
         {
3907
-            $this->error=$this->db->error()." sql=".$sql;
3907
+            $this->error = $this->db->error()." sql=".$sql;
3908 3908
             $this->db->rollback();
3909 3909
             return -1;
3910 3910
         }
@@ -3916,33 +3916,33 @@  discard block
 block discarded – undo
3916 3916
      *	@param 	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3917 3917
      *	@return	int					<0 if ko, >0 if ok
3918 3918
      */
3919
-    function update($notrigger=0)
3919
+    function update($notrigger = 0)
3920 3920
     {
3921
-        global $conf,$user;
3921
+        global $conf, $user;
3922 3922
 
3923
-        $error=0;
3923
+        $error = 0;
3924 3924
 
3925 3925
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3926 3926
 
3927 3927
         // Clean parameters
3928
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3929
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3930
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3931
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3932
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3933
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3934
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3935
-        if (empty($this->marque_tx)) $this->marque_tx=0;
3936
-        if (empty($this->marge_tx)) $this->marge_tx=0;
3937
-        if (empty($this->price)) $this->price=0;	// TODO A virer
3938
-        if (empty($this->remise)) $this->remise=0;	// TODO A virer
3939
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3940
-        if (empty($this->info_bits)) $this->info_bits=0;
3941
-        if (empty($this->special_code)) $this->special_code=0;
3942
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3943
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3944
-        if (empty($this->subprice)) $this->subprice=0;
3945
-		if (empty($this->pa_ht)) $this->pa_ht=0;
3928
+        if (empty($this->tva_tx)) $this->tva_tx = 0;
3929
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
3930
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
3931
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
3932
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
3933
+		if (empty($this->localtax1_type)) $this->localtax1_type = 0;
3934
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
3935
+        if (empty($this->marque_tx)) $this->marque_tx = 0;
3936
+        if (empty($this->marge_tx)) $this->marge_tx = 0;
3937
+        if (empty($this->price)) $this->price = 0; // TODO A virer
3938
+        if (empty($this->remise)) $this->remise = 0; // TODO A virer
3939
+        if (empty($this->remise_percent)) $this->remise_percent = 0;
3940
+        if (empty($this->info_bits)) $this->info_bits = 0;
3941
+        if (empty($this->special_code)) $this->special_code = 0;
3942
+        if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
3943
+        if (empty($this->fk_fournprice)) $this->fk_fournprice = 0;
3944
+        if (empty($this->subprice)) $this->subprice = 0;
3945
+		if (empty($this->pa_ht)) $this->pa_ht = 0;
3946 3946
 
3947 3947
 		// if buy price not defined, define buyprice as configured in margin admin
3948 3948
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3961,64 +3961,64 @@  discard block
 block discarded – undo
3961 3961
 
3962 3962
         // Mise a jour ligne en base
3963 3963
         $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
3964
-        $sql.= " description='".$this->db->escape($this->desc)."'";
3965
-        $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
3966
-        $sql.= ", product_type=".$this->product_type;
3967
-		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
3968
-        $sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3969
-        $sql.= ", localtax1_tx=".price2num($this->localtax1_tx);
3970
-        $sql.= ", localtax2_tx=".price2num($this->localtax2_tx);
3971
-		$sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3972
-		$sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3973
-        $sql.= ", qty='".price2num($this->qty)."'";
3974
-        $sql.= ", subprice=".price2num($this->subprice)."";
3975
-        $sql.= ", remise_percent=".price2num($this->remise_percent)."";
3976
-        $sql.= ", price=".price2num($this->price)."";					// TODO A virer
3977
-        $sql.= ", remise=".price2num($this->remise)."";				// TODO A virer
3978
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3964
+        $sql .= " description='".$this->db->escape($this->desc)."'";
3965
+        $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
3966
+        $sql .= ", product_type=".$this->product_type;
3967
+		$sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
3968
+        $sql .= ", tva_tx='".price2num($this->tva_tx)."'";
3969
+        $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
3970
+        $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
3971
+		$sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3972
+		$sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3973
+        $sql .= ", qty='".price2num($this->qty)."'";
3974
+        $sql .= ", subprice=".price2num($this->subprice)."";
3975
+        $sql .= ", remise_percent=".price2num($this->remise_percent)."";
3976
+        $sql .= ", price=".price2num($this->price).""; // TODO A virer
3977
+        $sql .= ", remise=".price2num($this->remise).""; // TODO A virer
3978
+        $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
3979 3979
         if (empty($this->skip_update_total))
3980 3980
         {
3981
-            $sql.= ", total_ht=".price2num($this->total_ht)."";
3982
-            $sql.= ", total_tva=".price2num($this->total_tva)."";
3983
-            $sql.= ", total_ttc=".price2num($this->total_ttc)."";
3984
-            $sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
3985
-            $sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
3986
-        }
3987
-		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
3988
-		$sql.= ", buy_price_ht=".price2num($this->pa_ht);
3989
-        if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code;
3990
-        $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
3991
-        if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
3992
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3993
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3994
-	    $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3981
+            $sql .= ", total_ht=".price2num($this->total_ht)."";
3982
+            $sql .= ", total_tva=".price2num($this->total_tva)."";
3983
+            $sql .= ", total_ttc=".price2num($this->total_ttc)."";
3984
+            $sql .= ", total_localtax1=".price2num($this->total_localtax1)."";
3985
+            $sql .= ", total_localtax2=".price2num($this->total_localtax2)."";
3986
+        }
3987
+		$sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
3988
+		$sql .= ", buy_price_ht=".price2num($this->pa_ht);
3989
+        if (strlen($this->special_code)) $sql .= ", special_code=".$this->special_code;
3990
+        $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
3991
+        if (!empty($this->rang)) $sql .= ", rang=".$this->rang;
3992
+        $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
3993
+        $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
3994
+	    $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3995 3995
 
3996 3996
 		// Multicurrency
3997
-		$sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3998
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3999
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4000
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3997
+		$sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3998
+        $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3999
+        $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4000
+        $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4001 4001
 
4002
-        $sql.= " WHERE rowid = ".$this->rowid;
4002
+        $sql .= " WHERE rowid = ".$this->rowid;
4003 4003
 
4004 4004
         dol_syslog(get_class($this)."::update", LOG_DEBUG);
4005
-        $resql=$this->db->query($sql);
4005
+        $resql = $this->db->query($sql);
4006 4006
         if ($resql)
4007 4007
         {
4008 4008
         	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4009 4009
         	{
4010
-        		$this->id=$this->rowid;
4011
-        		$result=$this->insertExtraFields();
4010
+        		$this->id = $this->rowid;
4011
+        		$result = $this->insertExtraFields();
4012 4012
         		if ($result < 0)
4013 4013
         		{
4014 4014
         			$error++;
4015 4015
         		}
4016 4016
         	}
4017 4017
 
4018
-            if (! $notrigger)
4018
+            if (!$notrigger)
4019 4019
             {
4020 4020
                 // Call trigger
4021
-                $result=$this->call_trigger('LINEPROPAL_UPDATE',$user);
4021
+                $result = $this->call_trigger('LINEPROPAL_UPDATE', $user);
4022 4022
                 if ($result < 0)
4023 4023
                 {
4024 4024
                     $this->db->rollback();
@@ -4032,7 +4032,7 @@  discard block
 block discarded – undo
4032 4032
         }
4033 4033
         else
4034 4034
         {
4035
-            $this->error=$this->db->error();
4035
+            $this->error = $this->db->error();
4036 4036
             $this->db->rollback();
4037 4037
             return -2;
4038 4038
         }
@@ -4050,14 +4050,14 @@  discard block
 block discarded – undo
4050 4050
 
4051 4051
         // Mise a jour ligne en base
4052 4052
         $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
4053
-        $sql.= " total_ht=".price2num($this->total_ht,'MT')."";
4054
-        $sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
4055
-        $sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
4056
-        $sql.= " WHERE rowid = ".$this->rowid;
4053
+        $sql .= " total_ht=".price2num($this->total_ht, 'MT')."";
4054
+        $sql .= ",total_tva=".price2num($this->total_tva, 'MT')."";
4055
+        $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT')."";
4056
+        $sql .= " WHERE rowid = ".$this->rowid;
4057 4057
 
4058 4058
         dol_syslog("PropaleLigne::update_total", LOG_DEBUG);
4059 4059
 
4060
-        $resql=$this->db->query($sql);
4060
+        $resql = $this->db->query($sql);
4061 4061
         if ($resql)
4062 4062
         {
4063 4063
             $this->db->commit();
@@ -4065,7 +4065,7 @@  discard block
 block discarded – undo
4065 4065
         }
4066 4066
         else
4067 4067
         {
4068
-            $this->error=$this->db->error();
4068
+            $this->error = $this->db->error();
4069 4069
             $this->db->rollback();
4070 4070
             return -2;
4071 4071
         }
Please login to merge, or discard this patch.
Braces   +457 added lines, -270 removed lines patch added patch discarded remove patch
@@ -240,7 +240,9 @@  discard block
 block discarded – undo
240 240
     {
241 241
         global $conf, $mysoc;
242 242
 
243
-        if (! $qty) $qty = 1;
243
+        if (! $qty) {
244
+        	$qty = 1;
245
+        }
244 246
 
245 247
         dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
246 248
         if ($idproduct > 0)
@@ -252,7 +254,9 @@  discard block
 block discarded – undo
252 254
 
253 255
             $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
254 256
             $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
255
-            if (empty($tva_tx)) $tva_npr=0;
257
+            if (empty($tva_tx)) {
258
+            	$tva_npr=0;
259
+            }
256 260
             $vat_src_code = '';     // May be defined into tva_tx
257 261
 
258 262
             $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr);
@@ -262,8 +266,7 @@  discard block
 block discarded – undo
262 266
             if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
263 267
             {
264 268
                 $price = $prod->multiprices[$this->thirdparty->price_level];
265
-            }
266
-            else
269
+            } else
267 270
             {
268 271
                 $price = $prod->price;
269 272
             }
@@ -278,7 +281,9 @@  discard block
 block discarded – undo
278 281
             $line->vat_src_code=$vat_src_code;
279 282
             $line->tva_tx=$tva_tx;
280 283
 	        $line->fk_unit=$prod->fk_unit;
281
-			if ($tva_npr) $line->info_bits = 1;
284
+			if ($tva_npr) {
285
+				$line->info_bits = 1;
286
+			}
282 287
 
283 288
             $this->lines[]=$line;
284 289
         }
@@ -304,9 +309,11 @@  discard block
 block discarded – undo
304 309
 
305 310
         if ($result > 0)
306 311
         {
307
-            if ($remise->fk_facture)	// Protection against multiple submission
312
+            if ($remise->fk_facture) {
313
+            	// Protection against multiple submission
308 314
             {
309 315
                 $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
316
+            }
310 317
                 $this->db->rollback();
311 318
                 return -5;
312 319
             }
@@ -343,21 +350,18 @@  discard block
 block discarded – undo
343 350
                 {
344 351
                     $this->db->commit();
345 352
                     return 1;
346
-                }
347
-                else
353
+                } else
348 354
                 {
349 355
                     $this->db->rollback();
350 356
                     return -1;
351 357
                 }
352
-            }
353
-            else
358
+            } else
354 359
             {
355 360
                 $this->error=$line->error;
356 361
                 $this->db->rollback();
357 362
                 return -2;
358 363
             }
359
-        }
360
-        else
364
+        } else
361 365
         {
362 366
             $this->db->rollback();
363 367
             return -2;
@@ -408,11 +412,21 @@  discard block
 block discarded – undo
408 412
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
409 413
 
410 414
         // Clean parameters
411
-        if (empty($remise_percent)) $remise_percent=0;
412
-        if (empty($qty)) $qty=0;
413
-        if (empty($info_bits)) $info_bits=0;
414
-        if (empty($rang)) $rang=0;
415
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
415
+        if (empty($remise_percent)) {
416
+        	$remise_percent=0;
417
+        }
418
+        if (empty($qty)) {
419
+        	$qty=0;
420
+        }
421
+        if (empty($info_bits)) {
422
+        	$info_bits=0;
423
+        }
424
+        if (empty($rang)) {
425
+        	$rang=0;
426
+        }
427
+        if (empty($fk_parent_line) || $fk_parent_line < 0) {
428
+        	$fk_parent_line=0;
429
+        }
416 430
 
417 431
         $remise_percent=price2num($remise_percent);
418 432
         $qty=price2num($qty);
@@ -425,14 +439,15 @@  discard block
 block discarded – undo
425 439
         if ($price_base_type=='HT')
426 440
         {
427 441
             $pu=$pu_ht;
428
-        }
429
-        else
442
+        } else
430 443
         {
431 444
             $pu=$pu_ttc;
432 445
         }
433 446
 
434 447
         // Check parameters
435
-        if ($type < 0) return -1;
448
+        if ($type < 0) {
449
+        	return -1;
450
+        }
436 451
 
437 452
         if ($this->statut == self::STATUS_DRAFT)
438 453
         {
@@ -553,7 +568,9 @@  discard block
 block discarded – undo
553 568
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
554 569
 
555 570
             // Mise en option de la ligne
556
-            if (empty($qty) && empty($special_code)) $this->line->special_code=3;
571
+            if (empty($qty) && empty($special_code)) {
572
+            	$this->line->special_code=3;
573
+            }
557 574
 
558 575
             // TODO deprecated
559 576
             $this->line->price=$price;
@@ -567,7 +584,9 @@  discard block
 block discarded – undo
567 584
             if ($result > 0)
568 585
             {
569 586
                 // Reorder if child line
570
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
587
+                if (! empty($fk_parent_line)) {
588
+                	$this->line_order(true,'DESC');
589
+                }
571 590
 
572 591
                 // Mise a jour informations denormalisees au niveau de la propale meme
573 592
                 $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
@@ -575,15 +594,13 @@  discard block
 block discarded – undo
575 594
                 {
576 595
                     $this->db->commit();
577 596
                     return $this->line->rowid;
578
-                }
579
-                else
597
+                } else
580 598
                 {
581 599
                     $this->error=$this->db->error();
582 600
                     $this->db->rollback();
583 601
                     return -1;
584 602
                 }
585
-            }
586
-            else
603
+            } else
587 604
             {
588 605
                 $this->error=$this->line->error;
589 606
                 $this->db->rollback();
@@ -637,9 +654,17 @@  discard block
 block discarded – undo
637 654
         $txlocaltax1=price2num($txlocaltax1);
638 655
         $txlocaltax2=price2num($txlocaltax2);
639 656
     	$pa_ht=price2num($pa_ht);
640
-        if (empty($qty) && empty($special_code)) $special_code=3;    // Set option tag
641
-        if (! empty($qty) && $special_code == 3) $special_code=0;    // Remove option tag
642
-        if (empty($type)) $type=0;
657
+        if (empty($qty) && empty($special_code)) {
658
+        	$special_code=3;
659
+        }
660
+        // Set option tag
661
+        if (! empty($qty) && $special_code == 3) {
662
+        	$special_code=0;
663
+        }
664
+        // Remove option tag
665
+        if (empty($type)) {
666
+        	$type=0;
667
+        }
643 668
 
644 669
         if ($this->statut == self::STATUS_DRAFT)
645 670
         {
@@ -751,7 +776,9 @@  discard block
 block discarded – undo
751 776
             if ($result > 0)
752 777
             {
753 778
                 // Reorder if child line
754
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
779
+                if (! empty($fk_parent_line)) {
780
+                	$this->line_order(true,'DESC');
781
+                }
755 782
 
756 783
                 $this->update_price(1);
757 784
 
@@ -760,16 +787,14 @@  discard block
 block discarded – undo
760 787
 
761 788
                 $this->db->commit();
762 789
                 return $result;
763
-            }
764
-            else
790
+            } else
765 791
             {
766 792
                 $this->error=$this->line->error;
767 793
 
768 794
                 $this->db->rollback();
769 795
                 return -1;
770 796
             }
771
-        }
772
-        else
797
+        } else
773 798
         {
774 799
             dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
775 800
             return -2;
@@ -797,13 +822,11 @@  discard block
 block discarded – undo
797 822
                 $this->update_price(1);
798 823
 
799 824
                 return 1;
800
-            }
801
-            else
825
+            } else
802 826
             {
803 827
                 return -1;
804 828
             }
805
-        }
806
-        else
829
+        } else
807 830
         {
808 831
             return -2;
809 832
         }
@@ -826,13 +849,21 @@  discard block
 block discarded – undo
826 849
         $now=dol_now();
827 850
 
828 851
         // Clean parameters
829
-        if (empty($this->date)) $this->date=$this->datep;
852
+        if (empty($this->date)) {
853
+        	$this->date=$this->datep;
854
+        }
830 855
         $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
831
-        if (empty($this->availability_id)) $this->availability_id=0;
832
-        if (empty($this->demand_reason_id)) $this->demand_reason_id=0;
856
+        if (empty($this->availability_id)) {
857
+        	$this->availability_id=0;
858
+        }
859
+        if (empty($this->demand_reason_id)) {
860
+        	$this->demand_reason_id=0;
861
+        }
833 862
 
834 863
 		// Multicurrency
835
-		if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
864
+		if (!empty($this->multicurrency_code)) {
865
+			list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
866
+		}
836 867
 		if (empty($this->fk_multicurrency))
837 868
 		{
838 869
 			$this->multicurrency_code = $conf->currency;
@@ -852,9 +883,12 @@  discard block
 block discarded – undo
852 883
         }
853 884
 
854 885
         // Check parameters
855
-		if (! empty($this->ref))	// We check that ref is not already used
886
+		if (! empty($this->ref)) {
887
+			// We check that ref is not already used
856 888
 		{
857
-			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
889
+			$result=self::isExistingObject($this->element, 0, $this->ref);
890
+		}
891
+		// Check ref is not yet used
858 892
 			if ($result > 0)
859 893
 			{
860 894
 				$this->error='ErrorRefAlreadyExists';
@@ -953,7 +987,9 @@  discard block
 block discarded – undo
953 987
 
954 988
                 dol_syslog(get_class($this)."::create", LOG_DEBUG);
955 989
                 $resql=$this->db->query($sql);
956
-                if (! $resql) $error++;
990
+                if (! $resql) {
991
+                	$error++;
992
+                }
957 993
 
958 994
                 /*
959 995
                  *  Insertion du detail des produits dans la base
@@ -1015,7 +1051,9 @@  discard block
 block discarded – undo
1015 1051
                 if (! $error && $this->origin && $this->origin_id)
1016 1052
                 {
1017 1053
                     $ret = $this->add_object_linked();
1018
-                    if (! $ret)	dol_print_error($this->db);
1054
+                    if (! $ret) {
1055
+                    	dol_print_error($this->db);
1056
+                    }
1019 1057
                 }
1020 1058
 
1021 1059
                 // Set delivery address
@@ -1044,16 +1082,19 @@  discard block
 block discarded – undo
1044 1082
                     	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1045 1083
                     	if (empty($reshook))
1046 1084
                     	{
1047
-                    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1085
+                    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
1086
+                    			// For avoid conflicts if trigger used
1048 1087
                     		{
1049 1088
                     			$result=$this->insertExtraFields();
1089
+                    		}
1050 1090
                     			if ($result < 0)
1051 1091
                     			{
1052 1092
                     				$error++;
1053 1093
                     			}
1054 1094
                     		}
1095
+                    	} else if ($reshook < 0) {
1096
+                    		$error++;
1055 1097
                     	}
1056
-                    	else if ($reshook < 0) $error++;
1057 1098
 
1058 1099
                         if (! $notrigger)
1059 1100
                         {
@@ -1062,15 +1103,13 @@  discard block
 block discarded – undo
1062 1103
                             if ($result < 0) { $error++; }
1063 1104
                             // End call triggers
1064 1105
                         }
1065
-                    }
1066
-                    else
1106
+                    } else
1067 1107
 					{
1068 1108
                         $this->error=$this->db->lasterror();
1069 1109
                         $error++;
1070 1110
                     }
1071 1111
                 }
1072
-            }
1073
-            else
1112
+            } else
1074 1113
 			{
1075 1114
                 $this->error=$this->db->lasterror();
1076 1115
                 $error++;
@@ -1081,14 +1120,12 @@  discard block
 block discarded – undo
1081 1120
                 $this->db->commit();
1082 1121
                 dol_syslog(get_class($this)."::create done id=".$this->id);
1083 1122
                 return $this->id;
1084
-            }
1085
-            else
1123
+            } else
1086 1124
             {
1087 1125
                 $this->db->rollback();
1088 1126
                 return -2;
1089 1127
             }
1090
-        }
1091
-        else
1128
+        } else
1092 1129
         {
1093 1130
             $this->error=$this->db->lasterror();
1094 1131
             $this->db->rollback();
@@ -1132,8 +1169,9 @@  discard block
 block discarded – undo
1132 1169
         $this->db->begin();
1133 1170
 
1134 1171
 		// get extrafields so they will be clone
1135
-		foreach($this->lines as $line)
1136
-			$line->fetch_optionals($line->rowid);
1172
+		foreach($this->lines as $line) {
1173
+					$line->fetch_optionals($line->rowid);
1174
+		}
1137 1175
 
1138 1176
         // Load dest object
1139 1177
         $clonedObj = clone $this;
@@ -1167,8 +1205,7 @@  discard block
 block discarded – undo
1167 1205
             $clonedObj->ref_client  = '';
1168 1206
 
1169 1207
             // TODO Change product price if multi-prices
1170
-        }
1171
-        else
1208
+        } else
1172 1209
         {
1173 1210
             $objsoc->fetch($clonedObj->socid);
1174 1211
         }
@@ -1183,23 +1220,28 @@  discard block
 block discarded – undo
1183 1220
         $clonedObj->date		= $now;
1184 1221
         $clonedObj->datep		= $now;    // deprecated
1185 1222
         $clonedObj->fin_validite	= $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600);
1186
-        if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client	= '';
1223
+        if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) {
1224
+        	$clonedObj->ref_client	= '';
1225
+        }
1187 1226
 
1188 1227
         // Create clone
1189 1228
 
1190 1229
         $result=$clonedObj->create($user);
1191
-        if ($result < 0) $error++;
1192
-        else
1230
+        if ($result < 0) {
1231
+        	$error++;
1232
+        } else
1193 1233
         {
1194 1234
 			// copy internal contacts
1195
-    		if ($clonedObj->copy_linked_contact($this, 'internal') < 0)
1196
-            	$error++;
1235
+    		if ($clonedObj->copy_linked_contact($this, 'internal') < 0) {
1236
+    		            	$error++;
1237
+    		}
1197 1238
 
1198 1239
             // copy external contacts if same company
1199 1240
             elseif ($this->socid == $clonedObj->socid)
1200 1241
             {
1201
-		        if ($clonedObj->copy_linked_contact($this, 'external') < 0)
1202
-					$error++;
1242
+		        if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
1243
+		        					$error++;
1244
+		        }
1203 1245
             }
1204 1246
         }
1205 1247
 
@@ -1211,7 +1253,9 @@  discard block
 block discarded – undo
1211 1253
                 $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj);
1212 1254
                 $action='';
1213 1255
                 $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action);    // Note that $action and $object may have been modified by some hooks
1214
-                if ($reshook < 0) $error++;
1256
+                if ($reshook < 0) {
1257
+                	$error++;
1258
+                }
1215 1259
             }
1216 1260
 
1217 1261
             // Call trigger
@@ -1227,8 +1271,7 @@  discard block
 block discarded – undo
1227 1271
         {
1228 1272
             $this->db->commit();
1229 1273
             return $clonedObj->id;
1230
-        }
1231
-        else
1274
+        } else
1232 1275
         {
1233 1276
             $this->db->rollback();
1234 1277
             return -1;
@@ -1279,8 +1322,11 @@  discard block
 block discarded – undo
1279 1322
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1280 1323
         $sql.= " WHERE p.fk_statut = c.id";
1281 1324
         $sql.= " AND p.entity IN (".getEntity('propal').")";
1282
-        if ($ref) $sql.= " AND p.ref='".$ref."'";
1283
-        else $sql.= " AND p.rowid=".$rowid;
1325
+        if ($ref) {
1326
+        	$sql.= " AND p.ref='".$ref."'";
1327
+        } else {
1328
+        	$sql.= " AND p.rowid=".$rowid;
1329
+        }
1284 1330
 
1285 1331
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1286 1332
         $resql=$this->db->query($sql);
@@ -1387,8 +1433,7 @@  discard block
 block discarded – undo
1387 1433
 
1388 1434
             $this->error="Record Not Found";
1389 1435
             return 0;
1390
-        }
1391
-        else
1436
+        } else
1392 1437
         {
1393 1438
             $this->error=$this->db->lasterror();
1394 1439
             return -1;
@@ -1414,7 +1459,9 @@  discard block
 block discarded – undo
1414 1459
 		$sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
1415 1460
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
1416 1461
 		$sql.= ' WHERE d.fk_propal = '.$this->id;
1417
-		if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1462
+		if ($only_product) {
1463
+			$sql .= ' AND p.fk_product_type = 0';
1464
+		}
1418 1465
 		$sql.= ' ORDER by d.rang';
1419 1466
 
1420 1467
 		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
@@ -1497,8 +1544,7 @@  discard block
 block discarded – undo
1497 1544
 			$this->db->free($result);
1498 1545
 
1499 1546
 			return 1;
1500
-		}
1501
-		else
1547
+		} else
1502 1548
 		{
1503 1549
 			$this->error=$this->db->lasterror();
1504 1550
 			return -3;
@@ -1525,22 +1571,24 @@  discard block
 block discarded – undo
1525 1571
     	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1526 1572
     	if (empty($reshook))
1527 1573
     	{
1528
-    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1574
+    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
1575
+    			// For avoid conflicts if trigger used
1529 1576
     		{
1530 1577
     			$result=$this->insertExtraFields();
1578
+    		}
1531 1579
     			if ($result < 0)
1532 1580
     			{
1533 1581
     				$error++;
1534 1582
     			}
1535 1583
     		}
1584
+    	} else if ($reshook < 0) {
1585
+    		$error++;
1536 1586
     	}
1537
-    	else if ($reshook < 0) $error++;
1538 1587
 
1539 1588
 		if (!$error)
1540 1589
 	    {
1541 1590
 	    	return 1;
1542
-	    }
1543
-	    else
1591
+	    } else
1544 1592
 	    {
1545 1593
 	    	return -1;
1546 1594
 	    }
@@ -1586,11 +1634,12 @@  discard block
 block discarded – undo
1586 1634
         $soc->fetch($this->socid);
1587 1635
 
1588 1636
         // Define new ref
1589
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1637
+        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) {
1638
+        	// empty should not happened, but when it occurs, the test save life
1590 1639
         {
1591 1640
         	$num = $this->getNextNumRef($soc);
1592 1641
         }
1593
-        else
1642
+        } else
1594 1643
         {
1595 1644
         	$num = $this->ref;
1596 1645
         }
@@ -1660,8 +1709,7 @@  discard block
 block discarded – undo
1660 1709
 
1661 1710
         	$this->db->commit();
1662 1711
         	return 1;
1663
-        }
1664
-        else
1712
+        } else
1665 1713
 		{
1666 1714
         	$this->db->rollback();
1667 1715
         	return -1;
@@ -1714,7 +1762,9 @@  discard block
 block discarded – undo
1714 1762
             {
1715 1763
             	// Call trigger
1716 1764
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1717
-            	if ($result < 0) $error++;
1765
+            	if ($result < 0) {
1766
+            		$error++;
1767
+            	}
1718 1768
             	// End call triggers
1719 1769
             }
1720 1770
 
@@ -1722,8 +1772,7 @@  discard block
 block discarded – undo
1722 1772
             {
1723 1773
             	$this->db->commit();
1724 1774
             	return 1;
1725
-            }
1726
-            else
1775
+            } else
1727 1776
             {
1728 1777
             	foreach($this->errors as $errmsg)
1729 1778
             	{
@@ -1774,7 +1823,9 @@  discard block
 block discarded – undo
1774 1823
             {
1775 1824
             	// Call trigger
1776 1825
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1777
-            	if ($result < 0) $error++;
1826
+            	if ($result < 0) {
1827
+            		$error++;
1828
+            	}
1778 1829
             	// End call triggers
1779 1830
             }
1780 1831
 
@@ -1782,8 +1833,7 @@  discard block
 block discarded – undo
1782 1833
             {
1783 1834
             	$this->db->commit();
1784 1835
             	return 1;
1785
-            }
1786
-            else
1836
+            } else
1787 1837
             {
1788 1838
             	foreach($this->errors as $errmsg)
1789 1839
             	{
@@ -1834,7 +1884,9 @@  discard block
 block discarded – undo
1834 1884
             {
1835 1885
             	// Call trigger
1836 1886
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1837
-            	if ($result < 0) $error++;
1887
+            	if ($result < 0) {
1888
+            		$error++;
1889
+            	}
1838 1890
             	// End call triggers
1839 1891
             }
1840 1892
 
@@ -1842,8 +1894,7 @@  discard block
 block discarded – undo
1842 1894
             {
1843 1895
             	$this->db->commit();
1844 1896
             	return 1;
1845
-            }
1846
-            else
1897
+            } else
1847 1898
             {
1848 1899
             	foreach($this->errors as $errmsg)
1849 1900
             	{
@@ -1895,7 +1946,9 @@  discard block
 block discarded – undo
1895 1946
             {
1896 1947
             	// Call trigger
1897 1948
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1898
-            	if ($result < 0) $error++;
1949
+            	if ($result < 0) {
1950
+            		$error++;
1951
+            	}
1899 1952
             	// End call triggers
1900 1953
             }
1901 1954
 
@@ -1903,8 +1956,7 @@  discard block
 block discarded – undo
1903 1956
             {
1904 1957
             	$this->db->commit();
1905 1958
             	return 1;
1906
-            }
1907
-            else
1959
+            } else
1908 1960
             {
1909 1961
             	foreach($this->errors as $errmsg)
1910 1962
             	{
@@ -1914,8 +1966,7 @@  discard block
 block discarded – undo
1914 1966
             	$this->db->rollback();
1915 1967
             	return -1*$error;
1916 1968
             }
1917
-        }
1918
-        else
1969
+        } else
1919 1970
         {
1920 1971
         	$error_str='Propal status do not meet requirement '.$this->statut;
1921 1972
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -1966,7 +2017,9 @@  discard block
 block discarded – undo
1966 2017
             {
1967 2018
             	// Call trigger
1968 2019
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
1969
-            	if ($result < 0) $error++;
2020
+            	if ($result < 0) {
2021
+            		$error++;
2022
+            	}
1970 2023
             	// End call triggers
1971 2024
             }
1972 2025
 
@@ -1974,8 +2027,7 @@  discard block
 block discarded – undo
1974 2027
             {
1975 2028
             	$this->db->commit();
1976 2029
             	return 1;
1977
-            }
1978
-            else
2030
+            } else
1979 2031
             {
1980 2032
             	foreach($this->errors as $errmsg)
1981 2033
             	{
@@ -1985,8 +2037,7 @@  discard block
 block discarded – undo
1985 2037
             	$this->db->rollback();
1986 2038
             	return -1*$error;
1987 2039
             }
1988
-        }
1989
-        else
2040
+        } else
1990 2041
         {
1991 2042
         	$error_str='Propal status do not meet requirement '.$this->statut;
1992 2043
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -2033,7 +2084,9 @@  discard block
 block discarded – undo
2033 2084
             {
2034 2085
             	// Call trigger
2035 2086
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2036
-            	if ($result < 0) $error++;
2087
+            	if ($result < 0) {
2088
+            		$error++;
2089
+            	}
2037 2090
             	// End call triggers
2038 2091
             }
2039 2092
 
@@ -2041,8 +2094,7 @@  discard block
 block discarded – undo
2041 2094
             {
2042 2095
             	$this->db->commit();
2043 2096
             	return 1;
2044
-            }
2045
-            else
2097
+            } else
2046 2098
             {
2047 2099
             	foreach($this->errors as $errmsg)
2048 2100
             	{
@@ -2052,8 +2104,7 @@  discard block
 block discarded – undo
2052 2104
             	$this->db->rollback();
2053 2105
             	return -1*$error;
2054 2106
             }
2055
-        }
2056
-        else
2107
+        } else
2057 2108
         {
2058 2109
             return -1;
2059 2110
         }
@@ -2101,7 +2152,9 @@  discard block
 block discarded – undo
2101 2152
             {
2102 2153
             	// Call trigger
2103 2154
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2104
-            	if ($result < 0) $error++;
2155
+            	if ($result < 0) {
2156
+            		$error++;
2157
+            	}
2105 2158
             	// End call triggers
2106 2159
             }
2107 2160
 
@@ -2109,8 +2162,7 @@  discard block
 block discarded – undo
2109 2162
             {
2110 2163
             	$this->db->commit();
2111 2164
             	return 1;
2112
-            }
2113
-            else
2165
+            } else
2114 2166
             {
2115 2167
             	foreach($this->errors as $errmsg)
2116 2168
             	{
@@ -2167,7 +2219,9 @@  discard block
 block discarded – undo
2167 2219
             {
2168 2220
             	// Call trigger
2169 2221
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2170
-            	if ($result < 0) $error++;
2222
+            	if ($result < 0) {
2223
+            		$error++;
2224
+            	}
2171 2225
             	// End call triggers
2172 2226
             }
2173 2227
 
@@ -2175,8 +2229,7 @@  discard block
 block discarded – undo
2175 2229
             {
2176 2230
             	$this->db->commit();
2177 2231
             	return 1;
2178
-            }
2179
-            else
2232
+            } else
2180 2233
             {
2181 2234
             	foreach($this->errors as $errmsg)
2182 2235
             	{
@@ -2208,7 +2261,9 @@  discard block
 block discarded – undo
2208 2261
 
2209 2262
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2210 2263
         $sql.= " SET fk_statut = ".$this->statut.",";
2211
-		if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',";
2264
+		if (! empty($note)) {
2265
+			$sql.= " note_private = '".$this->db->escape($note)."',";
2266
+		}
2212 2267
         $sql.= " date_cloture=NULL, fk_user_cloture=NULL";
2213 2268
         $sql.= " WHERE rowid = ".$this->id;
2214 2269
 
@@ -2243,8 +2298,7 @@  discard block
 block discarded – undo
2243 2298
 		    }
2244 2299
 			$this->db->rollback();
2245 2300
 			return -1*$error;
2246
-		}
2247
-		else
2301
+		} else
2248 2302
 		{
2249 2303
 			$this->db->commit();
2250 2304
 			return 1;
@@ -2336,14 +2390,12 @@  discard block
 block discarded – undo
2336 2390
             {
2337 2391
 		        $this->db->commit();
2338 2392
                 return 1;
2339
-            }
2340
-            else
2393
+            } else
2341 2394
             {
2342 2395
                 $this->db->rollback();
2343 2396
                 return -1;
2344 2397
             }
2345
-        }
2346
-        else
2398
+        } else
2347 2399
         {
2348 2400
             $this->error=$this->db->lasterror();
2349 2401
             $this->db->rollback();
@@ -2385,7 +2437,9 @@  discard block
 block discarded – undo
2385 2437
         {
2386 2438
         	// Call trigger
2387 2439
         	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2388
-        	if ($result < 0) $error++;
2440
+        	if ($result < 0) {
2441
+        		$error++;
2442
+        	}
2389 2443
         	// End call triggers
2390 2444
         }
2391 2445
 
@@ -2393,8 +2447,7 @@  discard block
 block discarded – undo
2393 2447
         {
2394 2448
         	$this->db->commit();
2395 2449
         	return 1;
2396
-        }
2397
-        else
2450
+        } else
2398 2451
         {
2399 2452
         	foreach($this->errors as $errmsg)
2400 2453
         	{
@@ -2456,7 +2509,9 @@  discard block
 block discarded – undo
2456 2509
         {
2457 2510
         	// Call trigger
2458 2511
         	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2459
-        	if ($result < 0) $error++;
2512
+        	if ($result < 0) {
2513
+        		$error++;
2514
+        	}
2460 2515
         	// End call triggers
2461 2516
         }
2462 2517
 
@@ -2464,8 +2519,7 @@  discard block
 block discarded – undo
2464 2519
         {
2465 2520
         	$this->db->commit();
2466 2521
         	return 1;
2467
-        }
2468
-        else
2522
+        } else
2469 2523
         {
2470 2524
         	foreach($this->errors as $errmsg)
2471 2525
         	{
@@ -2500,19 +2554,31 @@  discard block
 block discarded – undo
2500 2554
         $sql = "SELECT s.rowid, s.nom as name, s.client,";
2501 2555
         $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2502 2556
         $sql.= " p.datep as dp, p.fin_validite as datelimite";
2503
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2557
+        if (! $user->rights->societe->client->voir && ! $socid) {
2558
+        	$sql .= ", sc.fk_soc, sc.fk_user";
2559
+        }
2504 2560
         $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2505
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2561
+		if (! $user->rights->societe->client->voir && ! $socid) {
2562
+			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2563
+		}
2506 2564
         $sql.= " WHERE p.entity IN (".getEntity('propal').")";
2507 2565
         $sql.= " AND p.fk_soc = s.rowid";
2508 2566
         $sql.= " AND p.fk_statut = c.id";
2509
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2567
+        if (! $user->rights->societe->client->voir && ! $socid) {
2568
+        	//restriction
2510 2569
         {
2511 2570
         	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2512 2571
         }
2513
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2514
-        if ($draft)	$sql.= " AND p.fk_statut = ".self::STATUS_DRAFT;
2515
-        if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id;
2572
+        }
2573
+        if ($socid) {
2574
+        	$sql.= " AND s.rowid = ".$socid;
2575
+        }
2576
+        if ($draft) {
2577
+        	$sql.= " AND p.fk_statut = ".self::STATUS_DRAFT;
2578
+        }
2579
+        if ($notcurrentuser > 0) {
2580
+        	$sql.= " AND p.fk_user_author <> ".$user->id;
2581
+        }
2516 2582
         $sql.= $this->db->order($sortfield,$sortorder);
2517 2583
         $sql.= $this->db->plimit($limit,$offset);
2518 2584
 
@@ -2530,12 +2596,10 @@  discard block
 block discarded – undo
2530 2596
                     if ($shortlist == 1)
2531 2597
                     {
2532 2598
                         $ga[$obj->propalid] = $obj->ref;
2533
-                    }
2534
-                    else if ($shortlist == 2)
2599
+                    } else if ($shortlist == 2)
2535 2600
                     {
2536 2601
                         $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
2537
-                    }
2538
-                    else
2602
+                    } else
2539 2603
 					{
2540 2604
                         $ga[$i]['id']	= $obj->propalid;
2541 2605
                         $ga[$i]['ref'] 	= $obj->ref;
@@ -2546,8 +2610,7 @@  discard block
 block discarded – undo
2546 2610
                 }
2547 2611
             }
2548 2612
             return $ga;
2549
-        }
2550
-        else
2613
+        } else
2551 2614
         {
2552 2615
             dol_print_error($this->db);
2553 2616
             return -1;
@@ -2640,13 +2703,13 @@  discard block
 block discarded – undo
2640 2703
                     }
2641 2704
                 }
2642 2705
                 return $ga;
2643
-            }
2644
-            else
2706
+            } else
2645 2707
             {
2646 2708
                 return -1;
2647 2709
             }
2710
+        } else {
2711
+        	return $ga;
2648 2712
         }
2649
-        else return $ga;
2650 2713
     }
2651 2714
 
2652 2715
     /**
@@ -2683,11 +2746,15 @@  discard block
 block discarded – undo
2683 2746
                 {
2684 2747
                     // Delete linked object
2685 2748
                     $res = $this->deleteObjectLinked();
2686
-                    if ($res < 0) $error++;
2749
+                    if ($res < 0) {
2750
+                    	$error++;
2751
+                    }
2687 2752
 
2688 2753
                     // Delete linked contacts
2689 2754
                     $res = $this->delete_linked_contact();
2690
-                    if ($res < 0) $error++;
2755
+                    if ($res < 0) {
2756
+                    	$error++;
2757
+                    }
2691 2758
 
2692 2759
                     if (! $error)
2693 2760
                     {
@@ -2701,9 +2768,11 @@  discard block
 block discarded – undo
2701 2768
                             {
2702 2769
                                 dol_delete_preview($this);
2703 2770
 
2704
-                                if (! dol_delete_file($file,0,0,0,$this)) // For triggers
2771
+                                if (! dol_delete_file($file,0,0,0,$this)) {
2772
+                                	// For triggers
2705 2773
                                 {
2706 2774
                                     $this->error='ErrorFailToDeleteFile';
2775
+                                }
2707 2776
                                     $this->errors=array('ErrorFailToDeleteFile');
2708 2777
                                 	$this->db->rollback();
2709 2778
                                     return 0;
@@ -2726,9 +2795,11 @@  discard block
 block discarded – undo
2726 2795
                     // Removed extrafields
2727 2796
                     if (! $error)
2728 2797
                     {
2729
-                    	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2798
+                    	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
2799
+                    		// For avoid conflicts if trigger used
2730 2800
                     	{
2731 2801
                     		$result=$this->deleteExtraFields();
2802
+                    	}
2732 2803
                     		if ($result < 0)
2733 2804
                     		{
2734 2805
                     			$error++;
@@ -2743,29 +2814,25 @@  discard block
 block discarded – undo
2743 2814
                         dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
2744 2815
                         $this->db->commit();
2745 2816
                         return 1;
2746
-                    }
2747
-                    else
2817
+                    } else
2748 2818
                     {
2749 2819
                         $this->error=$this->db->lasterror();
2750 2820
                         $this->db->rollback();
2751 2821
                         return 0;
2752 2822
                     }
2753
-                }
2754
-                else
2823
+                } else
2755 2824
                 {
2756 2825
                     $this->error=$this->db->lasterror();
2757 2826
                     $this->db->rollback();
2758 2827
                     return -3;
2759 2828
                 }
2760
-            }
2761
-            else
2829
+            } else
2762 2830
             {
2763 2831
                 $this->error=$this->db->lasterror();
2764 2832
                 $this->db->rollback();
2765 2833
                 return -2;
2766 2834
             }
2767
-        }
2768
-        else
2835
+        } else
2769 2836
         {
2770 2837
             $this->db->rollback();
2771 2838
             return -1;
@@ -2812,7 +2879,9 @@  discard block
 block discarded – undo
2812 2879
             {
2813 2880
             	// Call trigger
2814 2881
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2815
-            	if ($result < 0) $error++;
2882
+            	if ($result < 0) {
2883
+            		$error++;
2884
+            	}
2816 2885
             	// End call triggers
2817 2886
             }
2818 2887
 
@@ -2820,8 +2889,7 @@  discard block
 block discarded – undo
2820 2889
             {
2821 2890
             	$this->db->commit();
2822 2891
             	return 1;
2823
-            }
2824
-            else
2892
+            } else
2825 2893
             {
2826 2894
             	foreach($this->errors as $errmsg)
2827 2895
             	{
@@ -2831,8 +2899,7 @@  discard block
 block discarded – undo
2831 2899
             	$this->db->rollback();
2832 2900
             	return -1*$error;
2833 2901
             }
2834
-        }
2835
-        else
2902
+        } else
2836 2903
         {
2837 2904
         	$error_str='Propal status do not meet requirement '.$this->statut;
2838 2905
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -2880,7 +2947,9 @@  discard block
 block discarded – undo
2880 2947
             {
2881 2948
             	// Call trigger
2882 2949
             	$result=$this->call_trigger('PROPAL_MODIFY',$user);
2883
-            	if ($result < 0) $error++;
2950
+            	if ($result < 0) {
2951
+            		$error++;
2952
+            	}
2884 2953
             	// End call triggers
2885 2954
             }
2886 2955
 
@@ -2888,8 +2957,7 @@  discard block
 block discarded – undo
2888 2957
             {
2889 2958
             	$this->db->commit();
2890 2959
             	return 1;
2891
-            }
2892
-            else
2960
+            } else
2893 2961
             {
2894 2962
             	foreach($this->errors as $errmsg)
2895 2963
             	{
@@ -2899,8 +2967,7 @@  discard block
 block discarded – undo
2899 2967
             	$this->db->rollback();
2900 2968
             	return -1*$error;
2901 2969
             }
2902
-        }
2903
-        else
2970
+        } else
2904 2971
         {
2905 2972
         	$error_str='Propal status do not meet requirement '.$this->statut;
2906 2973
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -2961,8 +3028,7 @@  discard block
 block discarded – undo
2961 3028
             }
2962 3029
             $this->db->free($result);
2963 3030
 
2964
-        }
2965
-        else
3031
+        } else
2966 3032
         {
2967 3033
             dol_print_error($this->db);
2968 3034
         }
@@ -2992,19 +3058,43 @@  discard block
 block discarded – undo
2992 3058
 		global $langs;
2993 3059
 		$langs->load("propal");
2994 3060
 
2995
-		if ($statut==self::STATUS_DRAFT) $statuttrans='statut0';
2996
-		if ($statut==self::STATUS_VALIDATED) $statuttrans='statut1';
2997
-		if ($statut==self::STATUS_SIGNED) $statuttrans='statut3';
2998
-		if ($statut==self::STATUS_NOTSIGNED) $statuttrans='statut5';
2999
-		if ($statut==self::STATUS_BILLED) $statuttrans='statut6';
3000
-
3001
-		if ($mode == 0)	return $this->labelstatut[$statut];
3002
-		if ($mode == 1)	return $this->labelstatut_short[$statut];
3003
-		if ($mode == 2)	return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut];
3004
-		if ($mode == 3)	return img_picto($this->labelstatut[$statut], $statuttrans);
3005
-		if ($mode == 4)	return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut];
3006
-		if ($mode == 5)	return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3007
-		if ($mode == 6)	return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3061
+		if ($statut==self::STATUS_DRAFT) {
3062
+			$statuttrans='statut0';
3063
+		}
3064
+		if ($statut==self::STATUS_VALIDATED) {
3065
+			$statuttrans='statut1';
3066
+		}
3067
+		if ($statut==self::STATUS_SIGNED) {
3068
+			$statuttrans='statut3';
3069
+		}
3070
+		if ($statut==self::STATUS_NOTSIGNED) {
3071
+			$statuttrans='statut5';
3072
+		}
3073
+		if ($statut==self::STATUS_BILLED) {
3074
+			$statuttrans='statut6';
3075
+		}
3076
+
3077
+		if ($mode == 0) {
3078
+			return $this->labelstatut[$statut];
3079
+		}
3080
+		if ($mode == 1) {
3081
+			return $this->labelstatut_short[$statut];
3082
+		}
3083
+		if ($mode == 2) {
3084
+			return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut];
3085
+		}
3086
+		if ($mode == 3) {
3087
+			return img_picto($this->labelstatut[$statut], $statuttrans);
3088
+		}
3089
+		if ($mode == 4) {
3090
+			return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut];
3091
+		}
3092
+		if ($mode == 5) {
3093
+			return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3094
+		}
3095
+		if ($mode == 6) {
3096
+			return '<span class="hideonsmartphone">'.$this->labelstatut[$statut].' </span>'.img_picto($this->labelstatut[$statut],$statuttrans);
3097
+		}
3008 3098
      }
3009 3099
 
3010 3100
 
@@ -3030,9 +3120,15 @@  discard block
 block discarded – undo
3030 3120
             $clause = " AND";
3031 3121
         }
3032 3122
         $sql.= $clause." p.entity IN (".getEntity('propal').")";
3033
-        if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3034
-        if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED;
3035
-        if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id;
3123
+        if ($mode == 'opened') {
3124
+        	$sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3125
+        }
3126
+        if ($mode == 'signed') {
3127
+        	$sql.= " AND p.fk_statut = ".self::STATUS_SIGNED;
3128
+        }
3129
+        if ($user->societe_id) {
3130
+        	$sql.= " AND p.fk_soc = ".$user->societe_id;
3131
+        }
3036 3132
 
3037 3133
         $resql=$this->db->query($sql);
3038 3134
         if ($resql)
@@ -3075,8 +3171,7 @@  discard block
 block discarded – undo
3075 3171
             }
3076 3172
 
3077 3173
             return $response;
3078
-        }
3079
-        else
3174
+        } else
3080 3175
         {
3081 3176
             $this->error=$this->db->error();
3082 3177
             return -1;
@@ -3151,8 +3246,7 @@  discard block
 block discarded – undo
3151 3246
                 $line->total_ttc=60;
3152 3247
                 $line->total_tva=10;
3153 3248
                 $line->remise_percent=50;
3154
-            }
3155
-            else
3249
+            } else
3156 3250
             {
3157 3251
                 $line->total_ht=100;
3158 3252
                 $line->total_ttc=120;
@@ -3210,8 +3304,7 @@  discard block
 block discarded – undo
3210 3304
             }
3211 3305
             $this->db->free($resql);
3212 3306
             return 1;
3213
-        }
3214
-        else
3307
+        } else
3215 3308
         {
3216 3309
             dol_print_error($this->db);
3217 3310
             $this->error=$this->db->error();
@@ -3262,15 +3355,13 @@  discard block
 block discarded – undo
3262 3355
             if ($numref != "")
3263 3356
             {
3264 3357
                 return $numref;
3265
-            }
3266
-            else
3358
+            } else
3267 3359
 			{
3268 3360
                 $this->error=$obj->error;
3269 3361
                 //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3270 3362
                 return "";
3271 3363
             }
3272
-        }
3273
-        else
3364
+        } else
3274 3365
 		{
3275 3366
             $langs->load("errors");
3276 3367
             print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
@@ -3292,7 +3383,10 @@  discard block
 block discarded – undo
3292 3383
     {
3293 3384
         global $langs, $conf, $user;
3294 3385
 
3295
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3386
+        if (! empty($conf->dol_no_mouse_hover)) {
3387
+        	$notooltip=1;
3388
+        }
3389
+        // Force disable tooltips
3296 3390
 
3297 3391
         $result='';
3298 3392
         $label='';
@@ -3301,16 +3395,21 @@  discard block
 block discarded – undo
3301 3395
         if ($user->rights->propal->lire)
3302 3396
         {
3303 3397
             $label = '<u>' . $langs->trans("ShowPropal") . '</u>';
3304
-            if (! empty($this->ref))
3305
-                $label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3306
-            if (! empty($this->ref_client))
3307
-                $label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3308
-            if (! empty($this->total_ht))
3309
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3310
-            if (! empty($this->total_tva))
3311
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3312
-            if (! empty($this->total_ttc))
3313
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3398
+            if (! empty($this->ref)) {
3399
+                            $label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3400
+            }
3401
+            if (! empty($this->ref_client)) {
3402
+                            $label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3403
+            }
3404
+            if (! empty($this->total_ht)) {
3405
+                            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3406
+            }
3407
+            if (! empty($this->total_tva)) {
3408
+                            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3409
+            }
3410
+            if (! empty($this->total_ttc)) {
3411
+                            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3412
+            }
3314 3413
             if ($option == '') {
3315 3414
                 $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params;
3316 3415
             }
@@ -3328,8 +3427,12 @@  discard block
 block discarded – undo
3328 3427
             {
3329 3428
                 // Add param to save lastsearch_values or not
3330 3429
                 $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3331
-                if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3332
-                if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3430
+                if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
3431
+                	$add_save_lastsearch_values=1;
3432
+                }
3433
+                if ($add_save_lastsearch_values) {
3434
+                	$url.='&save_lastsearch_values=1';
3435
+                }
3333 3436
             }
3334 3437
         }
3335 3438
 
@@ -3349,10 +3452,12 @@  discard block
 block discarded – undo
3349 3452
         $linkstart.=$linkclose.'>';
3350 3453
         $linkend='</a>';
3351 3454
 
3352
-        if ($withpicto)
3353
-            $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3354
-        if ($withpicto && $withpicto != 2)
3355
-            $result.=' ';
3455
+        if ($withpicto) {
3456
+                    $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3457
+        }
3458
+        if ($withpicto && $withpicto != 2) {
3459
+                    $result.=' ';
3460
+        }
3356 3461
         $result.=$linkstart.$this->ref.$linkend;
3357 3462
         return $result;
3358 3463
     }
@@ -3449,8 +3554,7 @@  discard block
 block discarded – undo
3449 3554
             $this->db->free($resql);
3450 3555
 
3451 3556
             return 1;
3452
-        }
3453
-        else
3557
+        } else
3454 3558
         {
3455 3559
             $this->error=$this->db->error();
3456 3560
             return -1;
@@ -3707,8 +3811,7 @@  discard block
 block discarded – undo
3707 3811
 			$this->db->free($result);
3708 3812
 
3709 3813
             return 1;
3710
-		}
3711
-		else
3814
+		} else
3712 3815
 		{
3713 3816
 			return -1;
3714 3817
 		}
@@ -3731,26 +3834,66 @@  discard block
 block discarded – undo
3731 3834
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3732 3835
 
3733 3836
         // Clean parameters
3734
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3735
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3736
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3737
-        if (empty($this->localtax1_type)) $this->localtax1_type=0;
3738
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3739
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3740
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3741
-        if (empty($this->rang)) $this->rang=0;
3742
-        if (empty($this->remise)) $this->remise=0;
3743
-        if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0;
3744
-        if (empty($this->info_bits)) $this->info_bits=0;
3745
-        if (empty($this->special_code)) $this->special_code=0;
3746
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3747
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3748
-		if (! is_numeric($this->qty)) $this->qty = 0;
3749
-        if (empty($this->pa_ht)) $this->pa_ht=0;
3750
-        if (empty($this->multicurrency_subprice))  $this->multicurrency_subprice=0;
3751
-        if (empty($this->multicurrency_total_ht))  $this->multicurrency_total_ht=0;
3752
-        if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
3753
-        if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
3837
+        if (empty($this->tva_tx)) {
3838
+        	$this->tva_tx=0;
3839
+        }
3840
+        if (empty($this->localtax1_tx)) {
3841
+        	$this->localtax1_tx=0;
3842
+        }
3843
+        if (empty($this->localtax2_tx)) {
3844
+        	$this->localtax2_tx=0;
3845
+        }
3846
+        if (empty($this->localtax1_type)) {
3847
+        	$this->localtax1_type=0;
3848
+        }
3849
+		if (empty($this->localtax2_type)) {
3850
+			$this->localtax2_type=0;
3851
+		}
3852
+        if (empty($this->total_localtax1)) {
3853
+        	$this->total_localtax1=0;
3854
+        }
3855
+        if (empty($this->total_localtax2)) {
3856
+        	$this->total_localtax2=0;
3857
+        }
3858
+        if (empty($this->rang)) {
3859
+        	$this->rang=0;
3860
+        }
3861
+        if (empty($this->remise)) {
3862
+        	$this->remise=0;
3863
+        }
3864
+        if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) {
3865
+        	$this->remise_percent=0;
3866
+        }
3867
+        if (empty($this->info_bits)) {
3868
+        	$this->info_bits=0;
3869
+        }
3870
+        if (empty($this->special_code)) {
3871
+        	$this->special_code=0;
3872
+        }
3873
+        if (empty($this->fk_parent_line)) {
3874
+        	$this->fk_parent_line=0;
3875
+        }
3876
+        if (empty($this->fk_fournprice)) {
3877
+        	$this->fk_fournprice=0;
3878
+        }
3879
+		if (! is_numeric($this->qty)) {
3880
+			$this->qty = 0;
3881
+		}
3882
+        if (empty($this->pa_ht)) {
3883
+        	$this->pa_ht=0;
3884
+        }
3885
+        if (empty($this->multicurrency_subprice)) {
3886
+        	$this->multicurrency_subprice=0;
3887
+        }
3888
+        if (empty($this->multicurrency_total_ht)) {
3889
+        	$this->multicurrency_total_ht=0;
3890
+        }
3891
+        if (empty($this->multicurrency_total_tva)) {
3892
+        	$this->multicurrency_total_tva=0;
3893
+        }
3894
+        if (empty($this->multicurrency_total_ttc)) {
3895
+        	$this->multicurrency_total_ttc=0;
3896
+        }
3754 3897
 
3755 3898
        // if buy price not defined, define buyprice as configured in margin admin
3756 3899
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3758,15 +3901,16 @@  discard block
 block discarded – undo
3758 3901
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
3759 3902
 			{
3760 3903
 				return $result;
3761
-			}
3762
-			else
3904
+			} else
3763 3905
 			{
3764 3906
 				$this->pa_ht = $result;
3765 3907
 			}
3766 3908
 		}
3767 3909
 
3768 3910
         // Check parameters
3769
-        if ($this->product_type < 0) return -1;
3911
+        if ($this->product_type < 0) {
3912
+        	return -1;
3913
+        }
3770 3914
 
3771 3915
         $this->db->begin();
3772 3916
 
@@ -3823,9 +3967,11 @@  discard block
 block discarded – undo
3823 3967
         {
3824 3968
             $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
3825 3969
 
3826
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3970
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
3971
+            	// For avoid conflicts if trigger used
3827 3972
             {
3828 3973
             	$this->id=$this->rowid;
3974
+            }
3829 3975
             	$result=$this->insertExtraFields();
3830 3976
             	if ($result < 0)
3831 3977
             	{
@@ -3847,8 +3993,7 @@  discard block
 block discarded – undo
3847 3993
 
3848 3994
             $this->db->commit();
3849 3995
             return 1;
3850
-        }
3851
-        else
3996
+        } else
3852 3997
         {
3853 3998
             $this->error=$this->db->error()." sql=".$sql;
3854 3999
             $this->db->rollback();
@@ -3875,9 +4020,11 @@  discard block
 block discarded – undo
3875 4020
         {
3876 4021
 
3877 4022
         	// Remove extrafields
3878
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
4023
+        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
4024
+        		// For avoid conflicts if trigger used
3879 4025
         	{
3880 4026
         		$this->id=$this->rowid;
4027
+        	}
3881 4028
         		$result=$this->deleteExtraFields();
3882 4029
         		if ($result < 0)
3883 4030
         		{
@@ -3901,8 +4048,7 @@  discard block
 block discarded – undo
3901 4048
             $this->db->commit();
3902 4049
 
3903 4050
             return 1;
3904
-        }
3905
-        else
4051
+        } else
3906 4052
         {
3907 4053
             $this->error=$this->db->error()." sql=".$sql;
3908 4054
             $this->db->rollback();
@@ -3925,24 +4071,62 @@  discard block
 block discarded – undo
3925 4071
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3926 4072
 
3927 4073
         // Clean parameters
3928
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3929
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3930
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3931
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3932
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3933
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3934
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3935
-        if (empty($this->marque_tx)) $this->marque_tx=0;
3936
-        if (empty($this->marge_tx)) $this->marge_tx=0;
3937
-        if (empty($this->price)) $this->price=0;	// TODO A virer
3938
-        if (empty($this->remise)) $this->remise=0;	// TODO A virer
3939
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3940
-        if (empty($this->info_bits)) $this->info_bits=0;
3941
-        if (empty($this->special_code)) $this->special_code=0;
3942
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3943
-        if (empty($this->fk_fournprice)) $this->fk_fournprice=0;
3944
-        if (empty($this->subprice)) $this->subprice=0;
3945
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4074
+        if (empty($this->tva_tx)) {
4075
+        	$this->tva_tx=0;
4076
+        }
4077
+        if (empty($this->localtax1_tx)) {
4078
+        	$this->localtax1_tx=0;
4079
+        }
4080
+        if (empty($this->localtax2_tx)) {
4081
+        	$this->localtax2_tx=0;
4082
+        }
4083
+        if (empty($this->total_localtax1)) {
4084
+        	$this->total_localtax1=0;
4085
+        }
4086
+        if (empty($this->total_localtax2)) {
4087
+        	$this->total_localtax2=0;
4088
+        }
4089
+		if (empty($this->localtax1_type)) {
4090
+			$this->localtax1_type=0;
4091
+		}
4092
+		if (empty($this->localtax2_type)) {
4093
+			$this->localtax2_type=0;
4094
+		}
4095
+        if (empty($this->marque_tx)) {
4096
+        	$this->marque_tx=0;
4097
+        }
4098
+        if (empty($this->marge_tx)) {
4099
+        	$this->marge_tx=0;
4100
+        }
4101
+        if (empty($this->price)) {
4102
+        	$this->price=0;
4103
+        }
4104
+        // TODO A virer
4105
+        if (empty($this->remise)) {
4106
+        	$this->remise=0;
4107
+        }
4108
+        // TODO A virer
4109
+        if (empty($this->remise_percent)) {
4110
+        	$this->remise_percent=0;
4111
+        }
4112
+        if (empty($this->info_bits)) {
4113
+        	$this->info_bits=0;
4114
+        }
4115
+        if (empty($this->special_code)) {
4116
+        	$this->special_code=0;
4117
+        }
4118
+        if (empty($this->fk_parent_line)) {
4119
+        	$this->fk_parent_line=0;
4120
+        }
4121
+        if (empty($this->fk_fournprice)) {
4122
+        	$this->fk_fournprice=0;
4123
+        }
4124
+        if (empty($this->subprice)) {
4125
+        	$this->subprice=0;
4126
+        }
4127
+		if (empty($this->pa_ht)) {
4128
+			$this->pa_ht=0;
4129
+		}
3946 4130
 
3947 4131
 		// if buy price not defined, define buyprice as configured in margin admin
3948 4132
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3950,8 +4134,7 @@  discard block
 block discarded – undo
3950 4134
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
3951 4135
 			{
3952 4136
 				return $result;
3953
-			}
3954
-			else
4137
+			} else
3955 4138
 			{
3956 4139
 				$this->pa_ht = $result;
3957 4140
 			}
@@ -3986,9 +4169,13 @@  discard block
 block discarded – undo
3986 4169
         }
3987 4170
 		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
3988 4171
 		$sql.= ", buy_price_ht=".price2num($this->pa_ht);
3989
-        if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code;
4172
+        if (strlen($this->special_code)) {
4173
+        	$sql.= ", special_code=".$this->special_code;
4174
+        }
3990 4175
         $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
3991
-        if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
4176
+        if (! empty($this->rang)) {
4177
+        	$sql.= ", rang=".$this->rang;
4178
+        }
3992 4179
         $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3993 4180
         $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3994 4181
 	    $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
@@ -4005,9 +4192,11 @@  discard block
 block discarded – undo
4005 4192
         $resql=$this->db->query($sql);
4006 4193
         if ($resql)
4007 4194
         {
4008
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4195
+        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
4196
+        		// For avoid conflicts if trigger used
4009 4197
         	{
4010 4198
         		$this->id=$this->rowid;
4199
+        	}
4011 4200
         		$result=$this->insertExtraFields();
4012 4201
         		if ($result < 0)
4013 4202
         		{
@@ -4029,8 +4218,7 @@  discard block
 block discarded – undo
4029 4218
 
4030 4219
             $this->db->commit();
4031 4220
             return 1;
4032
-        }
4033
-        else
4221
+        } else
4034 4222
         {
4035 4223
             $this->error=$this->db->error();
4036 4224
             $this->db->rollback();
@@ -4062,8 +4250,7 @@  discard block
 block discarded – undo
4062 4250
         {
4063 4251
             $this->db->commit();
4064 4252
             return 1;
4065
-        }
4066
-        else
4253
+        } else
4067 4254
         {
4068 4255
             $this->error=$this->db->error();
4069 4256
             $this->db->rollback();
Please login to merge, or discard this patch.
htdocs/commande/class/commande.class.php 4 patches
Doc Comments   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -1207,14 +1207,14 @@  discard block
 block discarded – undo
1207 1207
      *	@param      float			$pu_ht    	        Unit price (without tax)
1208 1208
      *	@param      float			$qty             	Quantite
1209 1209
      *	@param      float			$txtva           	Taux de tva force, sinon -1
1210
-     *	@param      float			$txlocaltax1		Local tax 1 rate
1211
-     *	@param      float			$txlocaltax2		Local tax 2 rate
1210
+     *	@param      integer			$txlocaltax1		Local tax 1 rate
1211
+     *	@param      integer			$txlocaltax2		Local tax 2 rate
1212 1212
      *	@param      int				$fk_product      	Id of product
1213
-     *	@param      float			$remise_percent  	Pourcentage de remise de la ligne
1213
+     *	@param      integer			$remise_percent  	Pourcentage de remise de la ligne
1214 1214
      *	@param      int				$info_bits			Bits de type de lignes
1215 1215
      *	@param      int				$fk_remise_except	Id remise
1216 1216
      *	@param      string			$price_base_type	HT or TTC
1217
-     *	@param      float			$pu_ttc    		    Prix unitaire TTC
1217
+     *	@param      integer			$pu_ttc    		    Prix unitaire TTC
1218 1218
      *	@param      int				$date_start       	Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1219 1219
      *	@param      int				$date_end         	End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1220 1220
      *	@param      int				$type				Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
@@ -1224,11 +1224,11 @@  discard block
 block discarded – undo
1224 1224
      *  @param		int				$fk_fournprice		Id supplier price
1225 1225
      *  @param		int				$pa_ht				Buying price (without tax)
1226 1226
      *  @param		string			$label				Label
1227
-	 *  @param		array			$array_options		extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
1227
+	 *  @param		integer			$array_options		extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
1228 1228
      * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
1229 1229
      * 	@param		string		    $origin				'order', ...
1230 1230
      *  @param		int			    $origin_id			Id of origin object
1231
-	 * 	@param		double			$pu_ht_devise		Unit price in currency
1231
+	 * 	@param		integer			$pu_ht_devise		Unit price in currency
1232 1232
      *	@return     int             					>0 if OK, <0 if KO
1233 1233
      *
1234 1234
      *	@see        add_product
@@ -2775,9 +2775,9 @@  discard block
 block discarded – undo
2775 2775
      *  @param		int				$pa_ht				Price (without tax) of product when it was bought
2776 2776
      *  @param		string			$label				Label
2777 2777
      *  @param		int				$special_code		Special code (also used by externals modules!)
2778
-	 *  @param		array			$array_options		extrafields array
2778
+	 *  @param		integer			$array_options		extrafields array
2779 2779
      * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
2780
-	 *  @param		double			$pu_ht_devise		Amount in currency
2780
+	 *  @param		integer			$pu_ht_devise		Amount in currency
2781 2781
      * 	@param		int				$notrigger			disable line update trigger
2782 2782
      *  @return   	int              					< 0 if KO, > 0 if OK
2783 2783
      */
Please login to merge, or discard this patch.
Indentation   +3554 added lines, -3554 removed lines patch added patch discarded remove patch
@@ -41,100 +41,100 @@  discard block
 block discarded – undo
41 41
  */
42 42
 class Commande extends CommonOrder
43 43
 {
44
-    public $element='commande';
45
-    public $table_element='commande';
46
-    public $table_element_line = 'commandedet';
47
-    public $class_element_line = 'OrderLine';
48
-    public $fk_element = 'fk_commande';
49
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
-    public $picto = 'order';
51
-
52
-    /**
53
-     * {@inheritdoc}
54
-     */
55
-    protected $table_ref_field = 'ref';
44
+	public $element='commande';
45
+	public $table_element='commande';
46
+	public $table_element_line = 'commandedet';
47
+	public $class_element_line = 'OrderLine';
48
+	public $fk_element = 'fk_commande';
49
+	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
+	public $picto = 'order';
51
+
52
+	/**
53
+	 * {@inheritdoc}
54
+	 */
55
+	protected $table_ref_field = 'ref';
56 56
 
57 57
 	/**
58 58
 	 * Client ID
59 59
 	 * @var int
60 60
 	 */
61
-    public $socid;
61
+	public $socid;
62 62
 
63
-    public $ref_client;
64
-    public $ref_int;
65
-    public $contactid;
63
+	public $ref_client;
64
+	public $ref_int;
65
+	public $contactid;
66 66
 
67 67
 	/**
68 68
 	 * Status of the order
69 69
 	 * @var int
70 70
 	 */
71
-    public $statut;
71
+	public $statut;
72 72
 	/**
73 73
 	 * @deprecated
74 74
 	 * @see billed
75 75
 	 */
76
-    public $facturee;
77
-    public $billed;		// billed or not
78
-
79
-    public $brouillon;
80
-    public $cond_reglement_code;
81
-
82
-    public $fk_account;
83
-
84
-    /**
85
-     * It holds the label of the payment mode. Use it in case translation cannot be found.
86
-     * @var string
87
-     */
88
-    public $mode_reglement;
89
-
90
-    /**
91
-     * Payment mode id
92
-     * @var int
93
-     */
94
-    public $mode_reglement_id;
95
-    /**
96
-     * Payment mode code
97
-     * @var string
98
-     */
99
-    public $mode_reglement_code;
100
-    /**
101
-     * Availability delivery time id
102
-     * @var int
103
-     */
104
-    public $availability_id;
105
-    /**
106
-     * Availability delivery time code
107
-     * @var string
108
-     */
109
-    public $availability_code;
110
-    /**
111
-     * Label of availability delivery time. Use it in case translation cannot be found.
112
-     * @var string
113
-     */
114
-    public $availability;
115
-
116
-    public $demand_reason_id;   // Source reason. Why we receive order (after a phone campaign, ...)
117
-    public $demand_reason_code;
118
-    public $date;				// Date commande
76
+	public $facturee;
77
+	public $billed;		// billed or not
78
+
79
+	public $brouillon;
80
+	public $cond_reglement_code;
81
+
82
+	public $fk_account;
83
+
84
+	/**
85
+	 * It holds the label of the payment mode. Use it in case translation cannot be found.
86
+	 * @var string
87
+	 */
88
+	public $mode_reglement;
89
+
90
+	/**
91
+	 * Payment mode id
92
+	 * @var int
93
+	 */
94
+	public $mode_reglement_id;
95
+	/**
96
+	 * Payment mode code
97
+	 * @var string
98
+	 */
99
+	public $mode_reglement_code;
100
+	/**
101
+	 * Availability delivery time id
102
+	 * @var int
103
+	 */
104
+	public $availability_id;
105
+	/**
106
+	 * Availability delivery time code
107
+	 * @var string
108
+	 */
109
+	public $availability_code;
110
+	/**
111
+	 * Label of availability delivery time. Use it in case translation cannot be found.
112
+	 * @var string
113
+	 */
114
+	public $availability;
115
+
116
+	public $demand_reason_id;   // Source reason. Why we receive order (after a phone campaign, ...)
117
+	public $demand_reason_code;
118
+	public $date;				// Date commande
119 119
 	/**
120 120
 	 * @deprecated
121 121
 	 * @see date
122 122
 	 */
123
-    public $date_commande;
124
-    public $date_livraison;	    // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
125
-    public $fk_remise_except;
126
-    public $remise_percent;
127
-    public $remise_absolue;
128
-    public $info_bits;
129
-    public $rang;
130
-    public $special_code;
131
-    public $source;			    // Order mode. How we received order (by phone, by email, ...)
132
-    public $extraparams=array();
133
-
134
-    public $linked_objects=array();
135
-
136
-    public $user_author_id;
137
-    public $user_valid;
123
+	public $date_commande;
124
+	public $date_livraison;	    // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
125
+	public $fk_remise_except;
126
+	public $remise_percent;
127
+	public $remise_absolue;
128
+	public $info_bits;
129
+	public $rang;
130
+	public $special_code;
131
+	public $source;			    // Order mode. How we received order (by phone, by email, ...)
132
+	public $extraparams=array();
133
+
134
+	public $linked_objects=array();
135
+
136
+	public $user_author_id;
137
+	public $user_valid;
138 138
 
139 139
 	/**
140 140
 	 * @var OrderLine[]
@@ -151,10 +151,10 @@  discard block
 block discarded – undo
151 151
 
152 152
 	public $oldcopy;
153 153
 
154
-    /**
155
-     * ERR Not enough stock
156
-     */
157
-    const STOCK_NOT_ENOUGH_FOR_ORDER = -3;
154
+	/**
155
+	 * ERR Not enough stock
156
+	 */
157
+	const STOCK_NOT_ENOUGH_FOR_ORDER = -3;
158 158
 
159 159
 	/**
160 160
 	 * Canceled status
@@ -182,2465 +182,2537 @@  discard block
 block discarded – undo
182 182
 	const STATUS_CLOSED = 3;
183 183
 
184 184
 
185
-    /**
186
-     *	Constructor
187
-     *
188
-     *  @param		DoliDB		$db      Database handler
189
-     */
190
-    function __construct($db)
191
-    {
192
-        $this->db = $db;
185
+	/**
186
+	 *	Constructor
187
+	 *
188
+	 *  @param		DoliDB		$db      Database handler
189
+	 */
190
+	function __construct($db)
191
+	{
192
+		$this->db = $db;
193 193
 
194
-        $this->remise = 0;
195
-        $this->remise_percent = 0;
194
+		$this->remise = 0;
195
+		$this->remise_percent = 0;
196 196
 
197
-        $this->products = array();
198
-    }
197
+		$this->products = array();
198
+	}
199 199
 
200
-    /**
200
+	/**
201 201
 	 *  Returns the reference to the following non used Order depending on the active numbering module
202 202
 	 *  defined into COMMANDE_ADDON
203 203
 	 *
204 204
 	 *  @param	Societe		$soc  	Object thirdparty
205 205
 	 *  @return string      		Order free reference
206 206
 	 */
207
-    function getNextNumRef($soc)
208
-    {
209
-        global $langs, $conf;
210
-        $langs->load("order");
207
+	function getNextNumRef($soc)
208
+	{
209
+		global $langs, $conf;
210
+		$langs->load("order");
211 211
 
212
-        if (! empty($conf->global->COMMANDE_ADDON))
213
-        {
214
-        	$mybool=false;
212
+		if (! empty($conf->global->COMMANDE_ADDON))
213
+		{
214
+			$mybool=false;
215 215
 
216
-        	$file = $conf->global->COMMANDE_ADDON.".php";
216
+			$file = $conf->global->COMMANDE_ADDON.".php";
217 217
 			$classname = $conf->global->COMMANDE_ADDON;
218 218
 
219 219
 			// Include file with class
220 220
 			$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
221 221
 			foreach ($dirmodels as $reldir)
222 222
 			{
223
-                $dir = dol_buildpath($reldir."core/modules/commande/");
224
-
225
-                // Load file with numbering class (if found)
226
-                $mybool|=@include_once $dir.$file;
227
-            }
228
-
229
-            if (! $mybool)
230
-            {
231
-                dol_print_error('',"Failed to include file ".$file);
232
-                return '';
233
-            }
234
-
235
-            $obj = new $classname();
236
-            $numref = $obj->getNextValue($soc,$this);
237
-
238
-            if ($numref != "")
239
-            {
240
-            	return $numref;
241
-            }
242
-            else
223
+				$dir = dol_buildpath($reldir."core/modules/commande/");
224
+
225
+				// Load file with numbering class (if found)
226
+				$mybool|=@include_once $dir.$file;
227
+			}
228
+
229
+			if (! $mybool)
230
+			{
231
+				dol_print_error('',"Failed to include file ".$file);
232
+				return '';
233
+			}
234
+
235
+			$obj = new $classname();
236
+			$numref = $obj->getNextValue($soc,$this);
237
+
238
+			if ($numref != "")
239
+			{
240
+				return $numref;
241
+			}
242
+			else
243 243
 			{
244 244
 				$this->error=$obj->error;
245
-            	//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
246
-            	return "";
247
-            }
248
-        }
249
-        else
250
-        {
251
-            print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
252
-            return "";
253
-        }
254
-    }
255
-
256
-
257
-    /**
258
-     *	Validate order
259
-     *
260
-     *	@param		User	$user     		User making status change
261
-     *	@param		int		$idwarehouse	Id of warehouse to use for stock decrease
262
-     *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
263
-     *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
264
-     */
265
-    function valid($user, $idwarehouse=0, $notrigger=0)
266
-    {
267
-        global $conf,$langs;
268
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
269
-
270
-        $error=0;
271
-
272
-        // Protection
273
-        if ($this->statut == self::STATUS_VALIDATED)
274
-        {
275
-            dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
276
-            return 0;
277
-        }
278
-
279
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
280
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
281
-        {
282
-            $this->error='NotEnoughPermissions';
283
-            dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
284
-            return -1;
285
-        }
286
-
287
-        $now=dol_now();
288
-
289
-        $this->db->begin();
290
-
291
-        // Definition du nom de module de numerotation de commande
292
-        $soc = new Societe($this->db);
293
-        $soc->fetch($this->socid);
294
-
295
-        // Class of company linked to order
296
-        $result=$soc->set_as_client();
297
-
298
-        // Define new ref
299
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
300
-        {
301
-            $num = $this->getNextNumRef($soc);
302
-        }
303
-        else
304
-		{
305
-            $num = $this->ref;
306
-        }
307
-        $this->newref = $num;
308
-
309
-        // Validate
310
-        $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
311
-        $sql.= " SET ref = '".$num."',";
312
-        $sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
313
-        $sql.= " date_valid='".$this->db->idate($now)."',";
314
-        $sql.= " fk_user_valid = ".$user->id;
315
-        $sql.= " WHERE rowid = ".$this->id;
316
-
317
-        dol_syslog(get_class($this)."::valid()", LOG_DEBUG);
318
-        $resql=$this->db->query($sql);
319
-        if (! $resql)
320
-        {
321
-            dol_print_error($this->db);
322
-            $this->error=$this->db->lasterror();
323
-            $error++;
324
-        }
325
-
326
-        if (! $error)
327
-        {
328
-            // If stock is incremented on validate order, we must increment it
329
-            if ($result >= 0 && ! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
330
-            {
331
-                require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
332
-                $langs->load("agenda");
333
-
334
-                // Loop on each line
335
-                $cpt=count($this->lines);
336
-                for ($i = 0; $i < $cpt; $i++)
337
-                {
338
-                    if ($this->lines[$i]->fk_product > 0)
339
-                    {
340
-                        $mouvP = new MouvementStock($this->db);
341
-						$mouvP->origin = &$this;
342
-                        // We decrement stock of product (and sub-products)
343
-                        $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr",$num));
344
-                        if ($result < 0)
345
-                        {
346
-                        	$error++;
347
-                        	$this->error=$mouvP->error;
348
-                        }
349
-                    }
350
-                    if ($error) break;
351
-                }
352
-            }
353
-        }
354
-
355
-        if (! $error && ! $notrigger)
356
-        {
357
-            // Call trigger
358
-            $result=$this->call_trigger('ORDER_VALIDATE',$user);
359
-            if ($result < 0) $error++;
360
-            // End call triggers
361
-        }
362
-
363
-        if (! $error)
364
-        {
365
-            $this->oldref = $this->ref;
366
-
367
-            // Rename directory if dir was a temporary ref
368
-            if (preg_match('/^[\(]?PROV/i', $this->ref))
369
-            {
370
-            	// On renomme repertoire ($this->ref = ancienne ref, $num = nouvelle ref)
371
-                // in order not to lose the attachments
372
-                $oldref = dol_sanitizeFileName($this->ref);
373
-                $newref = dol_sanitizeFileName($num);
374
-                $dirsource = $conf->commande->dir_output.'/'.$oldref;
375
-                $dirdest = $conf->commande->dir_output.'/'.$newref;
376
-                if (file_exists($dirsource))
377
-                {
378
-                    dol_syslog(get_class($this)."::valid() rename dir ".$dirsource." into ".$dirdest);
379
-
380
-                    if (@rename($dirsource, $dirdest))
381
-                    {
382
-                        dol_syslog("Rename ok");
383
-                        // Rename docs starting with $oldref with $newref
384
-                        $listoffiles=dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
385
-                        foreach($listoffiles as $fileentry)
386
-                        {
387
-                        	$dirsource=$fileentry['name'];
388
-                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
389
-                        	$dirsource=$fileentry['path'].'/'.$dirsource;
390
-                        	$dirdest=$fileentry['path'].'/'.$dirdest;
391
-                        	@rename($dirsource, $dirdest);
392
-                        }
393
-                    }
394
-                }
395
-            }
396
-        }
397
-
398
-        // Set new ref and current status
399
-        if (! $error)
400
-        {
401
-            $this->ref = $num;
402
-            $this->statut = self::STATUS_VALIDATED;
403
-        }
404
-
405
-        if (! $error)
406
-        {
407
-            $this->db->commit();
408
-            return 1;
409
-        }
410
-        else
245
+				//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
246
+				return "";
247
+			}
248
+		}
249
+		else
411 250
 		{
412
-            $this->db->rollback();
413
-            return -1;
414
-        }
415
-    }
416
-
417
-    /**
418
-     *	Set draft status
419
-     *
420
-     *	@param	User	$user			Object user that modify
421
-     *	@param	int		$idwarehouse	Id warehouse to use for stock change.
422
-     *	@return	int						<0 if KO, >0 if OK
423
-     */
424
-    function set_draft($user, $idwarehouse=-1)
425
-    {
426
-        global $conf,$langs;
427
-
428
-        $error=0;
429
-
430
-        // Protection
431
-        if ($this->statut <= self::STATUS_DRAFT)
432
-        {
433
-            return 0;
434
-        }
435
-
436
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
437
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
438
-        {
439
-            $this->error='Permission denied';
440
-            return -1;
441
-        }
442
-
443
-        $this->db->begin();
444
-
445
-        $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
446
-        $sql.= " SET fk_statut = ".self::STATUS_DRAFT;
447
-        $sql.= " WHERE rowid = ".$this->id;
448
-
449
-        dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
450
-        if ($this->db->query($sql))
451
-        {
452
-            // If stock is decremented on validate order, we must reincrement it
453
-            if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
454
-            {
455
-                $result = 0;
456
-
457
-                require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
458
-                $langs->load("agenda");
459
-
460
-                $num=count($this->lines);
461
-                for ($i = 0; $i < $num; $i++)
462
-                {
463
-                    if ($this->lines[$i]->fk_product > 0)
464
-                    {
465
-                        $mouvP = new MouvementStock($this->db);
466
-                        $mouvP->origin = &$this;
467
-                        // We increment stock of product (and sub-products)
468
-                        $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr",$this->ref));
469
-                        if ($result < 0) { $error++; $this->error=$mouvP->error; break; }
470
-                    }
471
-                }
472
-            }
473
-
474
-            if (!$error) {
475
-            	// Call trigger
476
-            	$result=$this->call_trigger('ORDER_UNVALIDATE',$user);
477
-            	if ($result < 0) $error++;
478
-            }
479
-
480
-            if (!$error) {
481
-           		$this->statut=self::STATUS_DRAFT;
482
-            	$this->db->commit();
483
-            	return 1;
484
-            }else {
485
-            	$this->db->rollback();
486
-            	return -1;
487
-            }
488
-        }
489
-        else
490
-        {
491
-            $this->error=$this->db->error();
492
-            $this->db->rollback();
493
-            return -1;
494
-        }
495
-    }
496
-
497
-
498
-    /**
499
-     *	Tag the order as validated (opened)
500
-     *	Function used when order is reopend after being closed.
501
-     *
502
-     *	@param      User	$user       Object user that change status
503
-     *	@return     int         		<0 if KO, 0 if nothing is done, >0 if OK
504
-     */
505
-    function set_reopen($user)
506
-    {
507
-        $error=0;
508
-
509
-        if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED)
510
-        {
511
-        	dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
512
-            return 0;
513
-        }
514
-
515
-        $this->db->begin();
516
-
517
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
518
-        $sql.= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0';
519
-        $sql.= ' WHERE rowid = '.$this->id;
520
-
521
-        dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
522
-        $resql = $this->db->query($sql);
523
-        if ($resql)
524
-        {
525
-            // Call trigger
526
-            $result=$this->call_trigger('ORDER_REOPEN',$user);
527
-            if ($result < 0) $error++;
528
-            // End call triggers
529
-        }
530
-        else
531
-        {
532
-            $error++;
533
-            $this->error=$this->db->lasterror();
534
-            dol_print_error($this->db);
535
-        }
536
-
537
-        if (! $error)
538
-        {
539
-        	$this->statut = self::STATUS_VALIDATED;
540
-        	$this->billed = 0;
541
-        	$this->facturee = 0; // deprecated
542
-
543
-            $this->db->commit();
544
-            return 1;
545
-        }
546
-        else
547
-        {
548
-	        foreach($this->errors as $errmsg)
549
-	        {
550
-		        dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
551
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
552
-	        }
553
-	        $this->db->rollback();
554
-	        return -1*$error;
555
-        }
556
-    }
557
-
558
-    /**
559
-     *  Close order
560
-     *
561
-     * 	@param      User	$user       Objet user that close
562
-     *	@return		int					<0 if KO, >0 if OK
563
-     */
564
-    function cloture($user)
565
-    {
566
-        global $conf;
567
-
568
-        $error=0;
569
-
570
-        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
571
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))
572
-        {
573
-            $this->db->begin();
574
-
575
-            $now=dol_now();
576
-
577
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
578
-            $sql.= ' SET fk_statut = '.self::STATUS_CLOSED.',';
579
-            $sql.= ' fk_user_cloture = '.$user->id.',';
580
-            $sql.= " date_cloture = '".$this->db->idate($now)."'";
581
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
582
-
583
-            if ($this->db->query($sql))
584
-            {
585
-	            // Call trigger
586
-	            $result=$this->call_trigger('ORDER_CLOSE',$user);
587
-	            if ($result < 0) $error++;
588
-	            // End call triggers
589
-
590
-                if (! $error)
591
-                {
592
-                	$this->statut=self::STATUS_CLOSED;
593
-
594
-                    $this->db->commit();
595
-                    return 1;
596
-                }
597
-                else
598
-                {
599
-                    $this->db->rollback();
600
-                    return -1;
601
-                }
602
-            }
603
-            else
604
-            {
605
-                $this->error=$this->db->lasterror();
606
-
607
-                $this->db->rollback();
608
-                return -1;
609
-            }
610
-        }
611
-    }
612
-
613
-    /**
614
-     * 	Cancel an order
615
-     * 	If stock is decremented on order validation, we must reincrement it
616
-     *
617
-     *	@param	int		$idwarehouse	Id warehouse to use for stock change.
618
-     *	@return	int						<0 if KO, >0 if OK
619
-     */
620
-	function cancel($idwarehouse=-1)
251
+			print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
252
+			return "";
253
+		}
254
+	}
255
+
256
+
257
+	/**
258
+	 *	Validate order
259
+	 *
260
+	 *	@param		User	$user     		User making status change
261
+	 *	@param		int		$idwarehouse	Id of warehouse to use for stock decrease
262
+	 *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
263
+	 *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
264
+	 */
265
+	function valid($user, $idwarehouse=0, $notrigger=0)
621 266
 	{
622
-		global $conf,$user,$langs;
267
+		global $conf,$langs;
268
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
623 269
 
624 270
 		$error=0;
625 271
 
272
+		// Protection
273
+		if ($this->statut == self::STATUS_VALIDATED)
274
+		{
275
+			dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
276
+			return 0;
277
+		}
278
+
279
+		if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
280
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
281
+		{
282
+			$this->error='NotEnoughPermissions';
283
+			dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
284
+			return -1;
285
+		}
286
+
287
+		$now=dol_now();
288
+
626 289
 		$this->db->begin();
627 290
 
291
+		// Definition du nom de module de numerotation de commande
292
+		$soc = new Societe($this->db);
293
+		$soc->fetch($this->socid);
294
+
295
+		// Class of company linked to order
296
+		$result=$soc->set_as_client();
297
+
298
+		// Define new ref
299
+		if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
300
+		{
301
+			$num = $this->getNextNumRef($soc);
302
+		}
303
+		else
304
+		{
305
+			$num = $this->ref;
306
+		}
307
+		$this->newref = $num;
308
+
309
+		// Validate
628 310
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
629
-		$sql.= " SET fk_statut = ".self::STATUS_CANCELED;
311
+		$sql.= " SET ref = '".$num."',";
312
+		$sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
313
+		$sql.= " date_valid='".$this->db->idate($now)."',";
314
+		$sql.= " fk_user_valid = ".$user->id;
630 315
 		$sql.= " WHERE rowid = ".$this->id;
631
-		$sql.= " AND fk_statut = ".self::STATUS_VALIDATED;
632 316
 
633
-		dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
634
-		if ($this->db->query($sql))
317
+		dol_syslog(get_class($this)."::valid()", LOG_DEBUG);
318
+		$resql=$this->db->query($sql);
319
+		if (! $resql)
635 320
 		{
636
-			// If stock is decremented on validate order, we must reincrement it
637
-			if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
321
+			dol_print_error($this->db);
322
+			$this->error=$this->db->lasterror();
323
+			$error++;
324
+		}
325
+
326
+		if (! $error)
327
+		{
328
+			// If stock is incremented on validate order, we must increment it
329
+			if ($result >= 0 && ! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
638 330
 			{
639 331
 				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
640 332
 				$langs->load("agenda");
641 333
 
642
-				$num=count($this->lines);
643
-				for ($i = 0; $i < $num; $i++)
334
+				// Loop on each line
335
+				$cpt=count($this->lines);
336
+				for ($i = 0; $i < $cpt; $i++)
644 337
 				{
645 338
 					if ($this->lines[$i]->fk_product > 0)
646 339
 					{
647 340
 						$mouvP = new MouvementStock($this->db);
648
-						// We increment stock of product (and sub-products)
649
-						$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr",$this->ref));  // price is 0, we don't want WAP to be changed
341
+						$mouvP->origin = &$this;
342
+						// We decrement stock of product (and sub-products)
343
+						$result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr",$num));
650 344
 						if ($result < 0)
651 345
 						{
652 346
 							$error++;
653 347
 							$this->error=$mouvP->error;
654
-							break;
655 348
 						}
656 349
 					}
350
+					if ($error) break;
657 351
 				}
658 352
 			}
353
+		}
659 354
 
660
-			if (! $error)
661
-			{
662
-	            // Call trigger
663
-	            $result=$this->call_trigger('ORDER_CANCEL',$user);
664
-	            if ($result < 0) $error++;
665
-	            // End call triggers
666
-			}
355
+		if (! $error && ! $notrigger)
356
+		{
357
+			// Call trigger
358
+			$result=$this->call_trigger('ORDER_VALIDATE',$user);
359
+			if ($result < 0) $error++;
360
+			// End call triggers
361
+		}
667 362
 
668
-			if (! $error)
669
-			{
670
-				$this->statut=self::STATUS_CANCELED;
671
-				$this->db->commit();
672
-				return 1;
673
-			}
674
-			else
363
+		if (! $error)
364
+		{
365
+			$this->oldref = $this->ref;
366
+
367
+			// Rename directory if dir was a temporary ref
368
+			if (preg_match('/^[\(]?PROV/i', $this->ref))
675 369
 			{
676
-				foreach($this->errors as $errmsg)
370
+				// On renomme repertoire ($this->ref = ancienne ref, $num = nouvelle ref)
371
+				// in order not to lose the attachments
372
+				$oldref = dol_sanitizeFileName($this->ref);
373
+				$newref = dol_sanitizeFileName($num);
374
+				$dirsource = $conf->commande->dir_output.'/'.$oldref;
375
+				$dirdest = $conf->commande->dir_output.'/'.$newref;
376
+				if (file_exists($dirsource))
677 377
 				{
678
-					dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
679
-					$this->error.=($this->error?', '.$errmsg:$errmsg);
378
+					dol_syslog(get_class($this)."::valid() rename dir ".$dirsource." into ".$dirdest);
379
+
380
+					if (@rename($dirsource, $dirdest))
381
+					{
382
+						dol_syslog("Rename ok");
383
+						// Rename docs starting with $oldref with $newref
384
+						$listoffiles=dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
385
+						foreach($listoffiles as $fileentry)
386
+						{
387
+							$dirsource=$fileentry['name'];
388
+							$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
389
+							$dirsource=$fileentry['path'].'/'.$dirsource;
390
+							$dirdest=$fileentry['path'].'/'.$dirdest;
391
+							@rename($dirsource, $dirdest);
392
+						}
393
+					}
680 394
 				}
681
-				$this->db->rollback();
682
-				return -1*$error;
683 395
 			}
684 396
 		}
397
+
398
+		// Set new ref and current status
399
+		if (! $error)
400
+		{
401
+			$this->ref = $num;
402
+			$this->statut = self::STATUS_VALIDATED;
403
+		}
404
+
405
+		if (! $error)
406
+		{
407
+			$this->db->commit();
408
+			return 1;
409
+		}
685 410
 		else
686 411
 		{
687
-			$this->error=$this->db->error();
688 412
 			$this->db->rollback();
689 413
 			return -1;
690 414
 		}
691 415
 	}
692 416
 
693
-    /**
694
-     *	Create order
695
-     *	Note that this->ref can be set or empty. If empty, we will use "(PROV)"
696
-     *
697
-     *	@param		User	$user 		Objet user that make creation
698
-     *	@param		int	    $notrigger	Disable all triggers
699
-     *	@return 	int			        <0 if KO, >0 if OK
700
-     */
701
-    function create($user, $notrigger=0)
702
-    {
703
-        global $conf,$langs;
704
-        $error=0;
705
-
706
-        // Clean parameters
707
-        $this->brouillon = 1;		// set command as draft
417
+	/**
418
+	 *	Set draft status
419
+	 *
420
+	 *	@param	User	$user			Object user that modify
421
+	 *	@param	int		$idwarehouse	Id warehouse to use for stock change.
422
+	 *	@return	int						<0 if KO, >0 if OK
423
+	 */
424
+	function set_draft($user, $idwarehouse=-1)
425
+	{
426
+		global $conf,$langs;
427
+
428
+		$error=0;
708 429
 
709
-		// $date_commande is deprecated
710
-        $date = ($this->date_commande ? $this->date_commande : $this->date);
430
+		// Protection
431
+		if ($this->statut <= self::STATUS_DRAFT)
432
+		{
433
+			return 0;
434
+		}
711 435
 
712
-		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
713
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
714
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
715
-		if (empty($this->fk_multicurrency))
436
+		if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
437
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
716 438
 		{
717
-			$this->multicurrency_code = $conf->currency;
718
-			$this->fk_multicurrency = 0;
719
-			$this->multicurrency_tx = 1;
439
+			$this->error='Permission denied';
440
+			return -1;
720 441
 		}
721 442
 
722
-        dol_syslog(get_class($this)."::create user=".$user->id);
723
-
724
-        // Check parameters
725
-    	if (! empty($this->ref))	// We check that ref is not already used
726
-    	{
727
-    		$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
728
-    		if ($result > 0)
729
-    		{
730
-    			$this->error='ErrorRefAlreadyExists';
731
-    			dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
732
-    			$this->db->rollback();
733
-    			return -1;
734
-    		}
735
-    	}
736
-
737
-        $soc = new Societe($this->db);
738
-        $result=$soc->fetch($this->socid);
739
-        if ($result < 0)
740
-        {
741
-            $this->error="Failed to fetch company";
742
-            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
743
-            return -2;
744
-        }
745
-        if (! empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
746
-        {
747
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Source"));
748
-            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
749
-            return -1;
750
-        }
751
-
752
-        $now=dol_now();
753
-
754
-        $this->db->begin();
755
-
756
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
757
-        $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
758
-        $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
759
-        $sql.= ", fk_shipping_method";
760
-        $sql.= ", fk_warehouse";
761
-        $sql.= ", remise_absolue, remise_percent";
762
-        $sql.= ", fk_incoterms, location_incoterms";
763
-        $sql.= ", entity";
764
-        $sql.= ", fk_multicurrency";
765
-        $sql.= ", multicurrency_code";
766
-        $sql.= ", multicurrency_tx";
767
-        $sql.= ")";
768
-        $sql.= " VALUES ('(PROV)',".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
769
-        $sql.= ", ".($this->fk_project>0?$this->fk_project:"null");
770
-        $sql.= ", '".$this->db->idate($date)."'";
771
-        $sql.= ", ".($this->source>=0 && $this->source != '' ?$this->db->escape($this->source):'null');
772
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
773
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
774
-        $sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
775
-        $sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
776
-        $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
777
-        $sql.= ", '".$this->db->escape($this->modelpdf)."'";
778
-        $sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null");
779
-        $sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null");
780
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
781
-        $sql.= ", ".($this->availability_id>0?$this->availability_id:"null");
782
-        $sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null");
783
-        $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
784
-        $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL');
785
-        $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
786
-        $sql.= ", ".($this->warehouse_id>0?$this->warehouse_id:'NULL');
787
-        $sql.= ", ".($this->remise_absolue>0?$this->db->escape($this->remise_absolue):'NULL');
788
-        $sql.= ", ".($this->remise_percent>0?$this->db->escape($this->remise_percent):0);
789
-        $sql.= ", ".(int) $this->fk_incoterms;
790
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
791
-        $sql.= ", ".$conf->entity;
792
-		$sql.= ", ".(int) $this->fk_multicurrency;
793
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
794
-		$sql.= ", ".(double) $this->multicurrency_tx;
795
-        $sql.= ")";
443
+		$this->db->begin();
796 444
 
797
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
798
-        $resql=$this->db->query($sql);
799
-        if ($resql)
800
-        {
801
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
445
+		$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
446
+		$sql.= " SET fk_statut = ".self::STATUS_DRAFT;
447
+		$sql.= " WHERE rowid = ".$this->id;
802 448
 
803
-            if ($this->id)
804
-            {
805
-                $fk_parent_line=0;
806
-                $num=count($this->lines);
449
+		dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
450
+		if ($this->db->query($sql))
451
+		{
452
+			// If stock is decremented on validate order, we must reincrement it
453
+			if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
454
+			{
455
+				$result = 0;
807 456
 
808
-                /*
809
-                 *  Insert products details into db
810
-                 */
811
-                for ($i=0;$i<$num;$i++)
812
-                {
813
-                	$line = $this->lines[$i];
814
-
815
-                	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
816
-				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
817
-                	if (! is_object($line)) $line = (object) $line;
818
-
819
-                    // Reset fk_parent_line for no child products and special product
820
-                    if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
821
-                        $fk_parent_line = 0;
822
-                    }
823
-
824
-                    $result = $this->addline(
825
-                        $line->desc,
826
-                        $line->subprice,
827
-                        $line->qty,
828
-                        $line->tva_tx,
829
-                        $line->localtax1_tx,
830
-                        $line->localtax2_tx,
831
-                        $line->fk_product,
832
-                        $line->remise_percent,
833
-                        $line->info_bits,
834
-                        $line->fk_remise_except,
835
-                        'HT',
836
-                        0,
837
-                        $line->date_start,
838
-                        $line->date_end,
839
-                        $line->product_type,
840
-                        $line->rang,
841
-                        $line->special_code,
842
-                        $fk_parent_line,
843
-                        $line->fk_fournprice,
844
-                        $line->pa_ht,
845
-                    	$line->label,
846
-                    	$line->array_options,
847
-	                    $line->fk_unit,
848
-                        $this->element,
849
-                        $line->id
850
-                    );
851
-                    if ($result < 0)
852
-                    {
853
-                    	if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER)
854
-                    	{
855
-                        	$this->error=$this->db->lasterror();
856
-                        	dol_print_error($this->db);
857
-                    	}
858
-                        $this->db->rollback();
859
-                        return -1;
860
-                    }
861
-                    // Defined the new fk_parent_line
862
-                    if ($result > 0 && $line->product_type == 9) {
863
-                        $fk_parent_line = $result;
864
-                    }
865
-                }
866
-
867
-                // update ref
868
-                $initialref='(PROV'.$this->id.')';
869
-                if (! empty($this->ref)) $initialref=$this->ref;
870
-
871
-                $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
872
-                if ($this->db->query($sql))
873
-                {
874
-                    if ($this->id)
875
-                    {
876
-                    	$this->ref = $initialref;
877
-
878
-                        // Add object linked
879
-                        if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
880
-                        {
881
-                        	foreach($this->linked_objects as $origin => $tmp_origin_id)
882
-                        	{
883
-                        	    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
884
-                        	    {
885
-                        	        foreach($tmp_origin_id as $origin_id)
886
-                        	        {
887
-                        	            $ret = $this->add_object_linked($origin, $origin_id);
888
-                        	            if (! $ret)
889
-                        	            {
890
-                        	                dol_print_error($this->db);
891
-                        	                $error++;
892
-                        	            }
893
-                        	        }
894
-                        	    }
895
-                        	    else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
896
-                        	    {
897
-                        	        $origin_id = $tmp_origin_id;
898
-                        	        $ret = $this->add_object_linked($origin, $origin_id);
899
-                        	        if (! $ret)
900
-                        	        {
901
-                        	            dol_print_error($this->db);
902
-                        	            $error++;
903
-                        	        }
904
-                          	    }
905
-                        	}
906
-                        }
907
-
908
-            			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
909
-            			{
910
-            				$originforcontact = $this->origin;
911
-            				$originidforcontact = $this->origin_id;
912
-                		    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
913
-                		    {
914
-                		        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
915
-                		        $exp = new Expedition($db);
916
-                		        $exp->fetch($this->origin_id);
917
-                		        $exp->fetchObjectLinked();
918
-                		        if (count($exp->linkedObjectsIds['commande']) > 0)
919
-                		        {
920
-                		            foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
921
-                		            {
922
-                		                $originforcontact = 'commande';
923
-							            if (is_object($value)) $originidforcontact = $value->id;
924
-							            else $originidforcontact = $value;
925
-                		                break; // We take first one
926
-                		            }
927
-                		        }
928
-                		    }
929
-
930
-                		    $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
931
-                		    $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
932
-
933
-                		    $resqlcontact = $this->db->query($sqlcontact);
934
-                		    if ($resqlcontact)
935
-                		    {
936
-                		        while($objcontact = $this->db->fetch_object($resqlcontact))
937
-                		        {
938
-        					        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
939
-                		            $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
940
-                		        }
941
-                		    }
942
-                		    else dol_print_error($resqlcontact);
943
-                		}
944
-                    }
945
-
946
-                    if (! $error)
947
-                    {
948
-                   		$result=$this->insertExtraFields();
949
-                   		if ($result < 0) $error++;
950
-                    }
951
-
952
-                    if (! $error && ! $notrigger)
953
-                    {
954
-			            // Call trigger
955
-			            $result=$this->call_trigger('ORDER_CREATE',$user);
956
-			            if ($result < 0) $error++;
957
-			            // End call triggers
958
-                    }
959
-
960
-	                if (! $error)
961
-	                {
962
-		                $this->db->commit();
963
-		                return $this->id;
964
-	                }
965
-	                else
457
+				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
458
+				$langs->load("agenda");
459
+
460
+				$num=count($this->lines);
461
+				for ($i = 0; $i < $num; $i++)
462
+				{
463
+					if ($this->lines[$i]->fk_product > 0)
966 464
 					{
967
-	                	$this->db->rollback();
968
-	                	return -1*$error;
465
+						$mouvP = new MouvementStock($this->db);
466
+						$mouvP->origin = &$this;
467
+						// We increment stock of product (and sub-products)
468
+						$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr",$this->ref));
469
+						if ($result < 0) { $error++; $this->error=$mouvP->error; break; }
969 470
 					}
970
-                }
971
-                else
972
-				{
973
-					$this->error=$this->db->lasterror();
974
-                    $this->db->rollback();
975
-                    return -1;
976
-                }
977
-            }
978
-        }
979
-        else
980
-		{
981
-            dol_print_error($this->db);
982
-            $this->db->rollback();
983
-            return -1;
984
-        }
985
-    }
471
+				}
472
+			}
986 473
 
474
+			if (!$error) {
475
+				// Call trigger
476
+				$result=$this->call_trigger('ORDER_UNVALIDATE',$user);
477
+				if ($result < 0) $error++;
478
+			}
987 479
 
988
-    /**
989
-     *	Load an object from its id and create a new one in database
990
-     *
991
-     *	@param		int			$socid			Id of thirdparty
992
-     *	@return		int							New id of clone
993
-     */
994
-    function createFromClone($socid=0)
995
-    {
996
-        global $user,$hookmanager;
480
+			if (!$error) {
481
+		   		$this->statut=self::STATUS_DRAFT;
482
+				$this->db->commit();
483
+				return 1;
484
+			}else {
485
+				$this->db->rollback();
486
+				return -1;
487
+			}
488
+		}
489
+		else
490
+		{
491
+			$this->error=$this->db->error();
492
+			$this->db->rollback();
493
+			return -1;
494
+		}
495
+	}
997 496
 
998
-        $error=0;
999 497
 
1000
-        $this->context['createfromclone'] = 'createfromclone';
498
+	/**
499
+	 *	Tag the order as validated (opened)
500
+	 *	Function used when order is reopend after being closed.
501
+	 *
502
+	 *	@param      User	$user       Object user that change status
503
+	 *	@return     int         		<0 if KO, 0 if nothing is done, >0 if OK
504
+	 */
505
+	function set_reopen($user)
506
+	{
507
+		$error=0;
1001 508
 
1002
-        $this->db->begin();
509
+		if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED)
510
+		{
511
+			dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
512
+			return 0;
513
+		}
1003 514
 
1004
-		// get lines so they will be clone
1005
-		foreach($this->lines as $line)
1006
-			$line->fetch_optionals($line->rowid);
515
+		$this->db->begin();
1007 516
 
1008
-        // Load source object
1009
-        $objFrom = clone $this;
517
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
518
+		$sql.= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0';
519
+		$sql.= ' WHERE rowid = '.$this->id;
1010 520
 
1011
-        // Change socid if needed
1012
-        if (! empty($socid) && $socid != $this->socid)
1013
-        {
1014
-            $objsoc = new Societe($this->db);
521
+		dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
522
+		$resql = $this->db->query($sql);
523
+		if ($resql)
524
+		{
525
+			// Call trigger
526
+			$result=$this->call_trigger('ORDER_REOPEN',$user);
527
+			if ($result < 0) $error++;
528
+			// End call triggers
529
+		}
530
+		else
531
+		{
532
+			$error++;
533
+			$this->error=$this->db->lasterror();
534
+			dol_print_error($this->db);
535
+		}
1015 536
 
1016
-            if ($objsoc->fetch($socid)>0)
1017
-            {
1018
-                $this->socid 				= $objsoc->id;
1019
-                $this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1020
-                $this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1021
-                $this->fk_project			= '';
1022
-                $this->fk_delivery_address	= '';
1023
-            }
537
+		if (! $error)
538
+		{
539
+			$this->statut = self::STATUS_VALIDATED;
540
+			$this->billed = 0;
541
+			$this->facturee = 0; // deprecated
1024 542
 
1025
-            // TODO Change product price if multi-prices
1026
-        }
543
+			$this->db->commit();
544
+			return 1;
545
+		}
546
+		else
547
+		{
548
+			foreach($this->errors as $errmsg)
549
+			{
550
+				dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
551
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
552
+			}
553
+			$this->db->rollback();
554
+			return -1*$error;
555
+		}
556
+	}
1027 557
 
1028
-        $this->id=0;
1029
-		$this->ref = '';
1030
-        $this->statut=self::STATUS_DRAFT;
558
+	/**
559
+	 *  Close order
560
+	 *
561
+	 * 	@param      User	$user       Objet user that close
562
+	 *	@return		int					<0 if KO, >0 if OK
563
+	 */
564
+	function cloture($user)
565
+	{
566
+		global $conf;
1031 567
 
1032
-        // Clear fields
1033
-        $this->user_author_id     = $user->id;
1034
-        $this->user_valid         = '';
1035
-		$this->date				  = dol_now();
1036
-		$this->date_commande	  = dol_now();
1037
-        $this->date_creation      = '';
1038
-        $this->date_validation    = '';
1039
-        $this->ref_client         = '';
1040
-
1041
-        // Create clone
1042
-        $result=$this->create($user);
1043
-        if ($result < 0) $error++;
1044
-
1045
-        if (! $error)
1046
-        {
1047
-            // Hook of thirdparty module
1048
-            if (is_object($hookmanager))
1049
-            {
1050
-                $parameters=array('objFrom'=>$objFrom);
1051
-                $action='';
1052
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1053
-                if ($reshook < 0) $error++;
1054
-            }
1055
-
1056
-            // Call trigger
1057
-            $result=$this->call_trigger('ORDER_CLONE',$user);
1058
-            if ($result < 0) $error++;
1059
-            // End call triggers
1060
-        }
1061
-
1062
-        unset($this->context['createfromclone']);
1063
-
1064
-        // End
1065
-        if (! $error)
1066
-        {
1067
-            $this->db->commit();
1068
-            return $this->id;
1069
-        }
1070
-        else
1071
-        {
1072
-            $this->db->rollback();
1073
-            return -1;
1074
-        }
1075
-    }
1076
-
1077
-
1078
-    /**
1079
-     *  Load an object from a proposal and create a new order into database
1080
-     *
1081
-     *  @param      Object			$object 	        Object source
1082
-     *  @return     int             					<0 if KO, 0 if nothing done, 1 if OK
1083
-     */
1084
-    function createFromProposal($object)
1085
-    {
1086
-        global $conf,$user,$hookmanager;
568
+		$error=0;
1087 569
 
1088
-		dol_include_once('/core/class/extrafields.class.php');
570
+		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
571
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))
572
+		{
573
+			$this->db->begin();
1089 574
 
1090
-        $error=0;
1091
-
1092
-
1093
-        $this->date_commande = dol_now();
1094
-        $this->source = 0;
1095
-
1096
-        $num=count($object->lines);
1097
-        for ($i = 0; $i < $num; $i++)
1098
-        {
1099
-            $line = new OrderLine($this->db);
1100
-
1101
-            $line->libelle           = $object->lines[$i]->libelle;
1102
-            $line->label             = $object->lines[$i]->label;
1103
-            $line->desc              = $object->lines[$i]->desc;
1104
-            $line->price             = $object->lines[$i]->price;
1105
-            $line->subprice          = $object->lines[$i]->subprice;
1106
-            $line->vat_src_code      = $object->lines[$i]->vat_src_code;
1107
-            $line->tva_tx            = $object->lines[$i]->tva_tx;
1108
-            $line->localtax1_tx      = $object->lines[$i]->localtax1_tx;
1109
-            $line->localtax2_tx      = $object->lines[$i]->localtax2_tx;
1110
-            $line->qty               = $object->lines[$i]->qty;
1111
-            $line->fk_remise_except  = $object->lines[$i]->fk_remise_except;
1112
-            $line->remise_percent    = $object->lines[$i]->remise_percent;
1113
-            $line->fk_product        = $object->lines[$i]->fk_product;
1114
-            $line->info_bits         = $object->lines[$i]->info_bits;
1115
-            $line->product_type      = $object->lines[$i]->product_type;
1116
-            $line->rang              = $object->lines[$i]->rang;
1117
-            $line->special_code      = $object->lines[$i]->special_code;
1118
-            $line->fk_parent_line    = $object->lines[$i]->fk_parent_line;
1119
-	        $line->fk_unit			 = $object->lines[$i]->fk_unit;
1120
-
1121
-            $line->date_start      	= $object->lines[$i]->date_start;
1122
-            $line->date_end    		= $object->lines[$i]->date_end;
575
+			$now=dol_now();
1123 576
 
1124
-			$line->fk_fournprice	= $object->lines[$i]->fk_fournprice;
1125
-			$marginInfos			= getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1126
-			$line->pa_ht			= $marginInfos[0];
1127
-			$line->marge_tx			= $marginInfos[1];
1128
-			$line->marque_tx		= $marginInfos[2];
577
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
578
+			$sql.= ' SET fk_statut = '.self::STATUS_CLOSED.',';
579
+			$sql.= ' fk_user_cloture = '.$user->id.',';
580
+			$sql.= " date_cloture = '".$this->db->idate($now)."'";
581
+			$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
1129 582
 
1130
-            // get extrafields from original line
1131
-			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
1132
-			foreach($object->lines[$i]->array_options as $options_key => $value)
1133
-				$line->array_options[$options_key] = $value;
583
+			if ($this->db->query($sql))
584
+			{
585
+				// Call trigger
586
+				$result=$this->call_trigger('ORDER_CLOSE',$user);
587
+				if ($result < 0) $error++;
588
+				// End call triggers
1134 589
 
1135
-			$this->lines[$i] = $line;
1136
-        }
1137
-
1138
-        $this->socid                = $object->socid;
1139
-        $this->fk_project           = $object->fk_project;
1140
-        $this->cond_reglement_id    = $object->cond_reglement_id;
1141
-        $this->mode_reglement_id    = $object->mode_reglement_id;
1142
-        $this->fk_account           = $object->fk_account;
1143
-        $this->availability_id      = $object->availability_id;
1144
-        $this->demand_reason_id     = $object->demand_reason_id;
1145
-        $this->date_livraison       = $object->date_livraison;
1146
-        $this->shipping_method_id   = $object->shipping_method_id;
1147
-        $this->warehouse_id         = $object->warehouse_id;
1148
-        $this->fk_delivery_address  = $object->fk_delivery_address;
1149
-        $this->contact_id           = $object->contactid;
1150
-        $this->ref_client           = $object->ref_client;
1151
-        $this->note_private         = $object->note_private;
1152
-        $this->note_public          = $object->note_public;
1153
-
1154
-        $this->origin				= $object->element;
1155
-        $this->origin_id			= $object->id;
1156
-
1157
-        // get extrafields from original line
1158
-		$object->fetch_optionals($object->id);
590
+				if (! $error)
591
+				{
592
+					$this->statut=self::STATUS_CLOSED;
1159 593
 
1160
-		$e = new ExtraFields($this->db);
1161
-		$element_extrafields = $e->fetch_name_optionals_label($this->element);
594
+					$this->db->commit();
595
+					return 1;
596
+				}
597
+				else
598
+				{
599
+					$this->db->rollback();
600
+					return -1;
601
+				}
602
+			}
603
+			else
604
+			{
605
+				$this->error=$this->db->lasterror();
1162 606
 
1163
-		foreach($object->array_options as $options_key => $value) {
1164
-			if(array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)){
1165
-				$this->array_options[$options_key] = $value;
607
+				$this->db->rollback();
608
+				return -1;
1166 609
 			}
1167 610
 		}
1168
-        // Possibility to add external linked objects with hooks
1169
-        $this->linked_objects[$this->origin] = $this->origin_id;
1170
-        if (is_array($object->other_linked_objects) && ! empty($object->other_linked_objects))
1171
-        {
1172
-           	$this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1173
-        }
1174
-
1175
-        $ret = $this->create($user);
1176
-
1177
-        if ($ret > 0)
1178
-        {
1179
-            // Actions hooked (by external module)
1180
-            $hookmanager->initHooks(array('orderdao'));
1181
-
1182
-            $parameters=array('objFrom'=>$object);
1183
-            $action='';
1184
-            $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1185
-            if ($reshook < 0) $error++;
1186
-
1187
-            if (! $error)
1188
-            {
1189
-                // Ne pas passer par la commande provisoire
1190
-                if ($conf->global->COMMANDE_VALID_AFTER_CLOSE_PROPAL == 1)
1191
-                {
1192
-                    $this->fetch($ret);
1193
-                    $this->valid($user);
1194
-                }
1195
-                return $ret;
1196
-            }
1197
-            else return -1;
1198
-        }
1199
-        else return -1;
1200
-    }
1201
-
1202
-
1203
-    /**
1204
-     *	Add an order line into database (linked to product/service or not)
1205
-     *
1206
-     *	@param      string			$desc            	Description of line
1207
-     *	@param      float			$pu_ht    	        Unit price (without tax)
1208
-     *	@param      float			$qty             	Quantite
1209
-     *	@param      float			$txtva           	Taux de tva force, sinon -1
1210
-     *	@param      float			$txlocaltax1		Local tax 1 rate
1211
-     *	@param      float			$txlocaltax2		Local tax 2 rate
1212
-     *	@param      int				$fk_product      	Id of product
1213
-     *	@param      float			$remise_percent  	Pourcentage de remise de la ligne
1214
-     *	@param      int				$info_bits			Bits de type de lignes
1215
-     *	@param      int				$fk_remise_except	Id remise
1216
-     *	@param      string			$price_base_type	HT or TTC
1217
-     *	@param      float			$pu_ttc    		    Prix unitaire TTC
1218
-     *	@param      int				$date_start       	Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1219
-     *	@param      int				$date_end         	End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1220
-     *	@param      int				$type				Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
1221
-     *	@param      int				$rang             	Position of line
1222
-     *	@param		int				$special_code		Special code (also used by externals modules!)
1223
-     *	@param		int				$fk_parent_line		Parent line
1224
-     *  @param		int				$fk_fournprice		Id supplier price
1225
-     *  @param		int				$pa_ht				Buying price (without tax)
1226
-     *  @param		string			$label				Label
1227
-	 *  @param		array			$array_options		extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
1228
-     * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
1229
-     * 	@param		string		    $origin				'order', ...
1230
-     *  @param		int			    $origin_id			Id of origin object
1231
-	 * 	@param		double			$pu_ht_devise		Unit price in currency
1232
-     *	@return     int             					>0 if OK, <0 if KO
1233
-     *
1234
-     *	@see        add_product
1235
-     *
1236
-     *	Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
1237
-     *	de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
1238
-     *	par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
1239
-     *	et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
1240
-     */
1241
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise = 0)
1242
-    {
1243
-    	global $mysoc, $conf, $langs, $user;
1244
-
1245
-        dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit", LOG_DEBUG);
1246
-
1247
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1248
-
1249
-        // Clean parameters
1250
-        if (empty($remise_percent)) $remise_percent=0;
1251
-        if (empty($qty)) $qty=0;
1252
-        if (empty($info_bits)) $info_bits=0;
1253
-        if (empty($rang)) $rang=0;
1254
-        if (empty($txtva)) $txtva=0;
1255
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1256
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1257
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
1258
-        if (empty($this->fk_multicurrency)) $this->fk_multicurrency=0;
1259
-
1260
-        $remise_percent=price2num($remise_percent);
1261
-        $qty=price2num($qty);
1262
-        $pu_ht=price2num($pu_ht);
1263
-        $pu_ttc=price2num($pu_ttc);
1264
-    	$pa_ht=price2num($pa_ht);
1265
-        $txtva = price2num($txtva);
1266
-        $txlocaltax1 = price2num($txlocaltax1);
1267
-        $txlocaltax2 = price2num($txlocaltax2);
1268
-        if ($price_base_type=='HT')
1269
-        {
1270
-            $pu=$pu_ht;
1271
-        }
1272
-        else
1273
-        {
1274
-            $pu=$pu_ttc;
1275
-        }
1276
-        $label=trim($label);
1277
-        $desc=trim($desc);
1278
-
1279
-        // Check parameters
1280
-        if ($type < 0) return -1;
1281
-
1282
-        if ($this->statut == self::STATUS_DRAFT)
1283
-        {
1284
-            $this->db->begin();
1285
-
1286
-        	$product_type=$type;
1287
-			if (!empty($fk_product))
611
+	}
612
+
613
+	/**
614
+	 * 	Cancel an order
615
+	 * 	If stock is decremented on order validation, we must reincrement it
616
+	 *
617
+	 *	@param	int		$idwarehouse	Id warehouse to use for stock change.
618
+	 *	@return	int						<0 if KO, >0 if OK
619
+	 */
620
+	function cancel($idwarehouse=-1)
621
+	{
622
+		global $conf,$user,$langs;
623
+
624
+		$error=0;
625
+
626
+		$this->db->begin();
627
+
628
+		$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
629
+		$sql.= " SET fk_statut = ".self::STATUS_CANCELED;
630
+		$sql.= " WHERE rowid = ".$this->id;
631
+		$sql.= " AND fk_statut = ".self::STATUS_VALIDATED;
632
+
633
+		dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
634
+		if ($this->db->query($sql))
635
+		{
636
+			// If stock is decremented on validate order, we must reincrement it
637
+			if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
1288 638
 			{
1289
-				$product=new Product($this->db);
1290
-				$result=$product->fetch($fk_product);
1291
-				$product_type=$product->type;
639
+				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
640
+				$langs->load("agenda");
1292 641
 
1293
-				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
642
+				$num=count($this->lines);
643
+				for ($i = 0; $i < $num; $i++)
1294 644
 				{
1295
-                    $langs->load("errors");
1296
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1297
-					dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1298
-					$this->db->rollback();
1299
-					return self::STOCK_NOT_ENOUGH_FOR_ORDER;
645
+					if ($this->lines[$i]->fk_product > 0)
646
+					{
647
+						$mouvP = new MouvementStock($this->db);
648
+						// We increment stock of product (and sub-products)
649
+						$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr",$this->ref));  // price is 0, we don't want WAP to be changed
650
+						if ($result < 0)
651
+						{
652
+							$error++;
653
+							$this->error=$mouvP->error;
654
+							break;
655
+						}
656
+					}
1300 657
 				}
1301 658
 			}
1302
-			// Calcul du total TTC et de la TVA pour la ligne a partir de
1303
-            // qty, pu, remise_percent et txtva
1304
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1305
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1306
-
1307
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
1308
-
1309
-       		// Clean vat code
1310
-    		$vat_src_code='';
1311
-    		if (preg_match('/\((.*)\)/', $txtva, $reg))
1312
-    		{
1313
-    		    $vat_src_code = $reg[1];
1314
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1315
-    		}
1316
-
1317
-            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1318
-
1319
-            $total_ht  = $tabprice[0];
1320
-            $total_tva = $tabprice[1];
1321
-            $total_ttc = $tabprice[2];
1322
-            $total_localtax1 = $tabprice[9];
1323
-            $total_localtax2 = $tabprice[10];
1324
-			$pu_ht = $tabprice[3];
1325 659
 
1326
-			// MultiCurrency
1327
-			$multicurrency_total_ht  = $tabprice[16];
1328
-            $multicurrency_total_tva = $tabprice[17];
1329
-            $multicurrency_total_ttc = $tabprice[18];
1330
-			$pu_ht_devise = $tabprice[19];
660
+			if (! $error)
661
+			{
662
+				// Call trigger
663
+				$result=$this->call_trigger('ORDER_CANCEL',$user);
664
+				if ($result < 0) $error++;
665
+				// End call triggers
666
+			}
667
+
668
+			if (! $error)
669
+			{
670
+				$this->statut=self::STATUS_CANCELED;
671
+				$this->db->commit();
672
+				return 1;
673
+			}
674
+			else
675
+			{
676
+				foreach($this->errors as $errmsg)
677
+				{
678
+					dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
679
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
680
+				}
681
+				$this->db->rollback();
682
+				return -1*$error;
683
+			}
684
+		}
685
+		else
686
+		{
687
+			$this->error=$this->db->error();
688
+			$this->db->rollback();
689
+			return -1;
690
+		}
691
+	}
1331 692
 
1332
-            // Rang to use
1333
-            $rangtouse = $rang;
1334
-            if ($rangtouse == -1)
1335
-            {
1336
-                $rangmax = $this->line_max($fk_parent_line);
1337
-                $rangtouse = $rangmax + 1;
1338
-            }
1339
-
1340
-            // TODO A virer
1341
-            // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1342
-            $price = $pu;
1343
-            $remise = 0;
1344
-            if ($remise_percent > 0)
1345
-            {
1346
-                $remise = round(($pu * $remise_percent / 100), 2);
1347
-                $price = $pu - $remise;
1348
-            }
1349
-
1350
-            // Insert line
1351
-            $this->line=new OrderLine($this->db);
1352
-
1353
-            $this->line->context = $this->context;
1354
-
1355
-            $this->line->fk_commande=$this->id;
1356
-            $this->line->label=$label;
1357
-            $this->line->desc=$desc;
1358
-            $this->line->qty=$qty;
693
+	/**
694
+	 *	Create order
695
+	 *	Note that this->ref can be set or empty. If empty, we will use "(PROV)"
696
+	 *
697
+	 *	@param		User	$user 		Objet user that make creation
698
+	 *	@param		int	    $notrigger	Disable all triggers
699
+	 *	@return 	int			        <0 if KO, >0 if OK
700
+	 */
701
+	function create($user, $notrigger=0)
702
+	{
703
+		global $conf,$langs;
704
+		$error=0;
1359 705
 
1360
-			$this->line->vat_src_code=$vat_src_code;
1361
-            $this->line->tva_tx=$txtva;
1362
-            $this->line->localtax1_tx=$localtaxes_type[1];
1363
-            $this->line->localtax2_tx=$localtaxes_type[3];
1364
-			$this->line->localtax1_type=$localtaxes_type[0];
1365
-			$this->line->localtax2_type=$localtaxes_type[2];
1366
-            $this->line->fk_product=$fk_product;
1367
-			$this->line->product_type=$product_type;
1368
-            $this->line->fk_remise_except=$fk_remise_except;
1369
-            $this->line->remise_percent=$remise_percent;
1370
-            $this->line->subprice=$pu_ht;
1371
-            $this->line->rang=$rangtouse;
1372
-            $this->line->info_bits=$info_bits;
1373
-            $this->line->total_ht=$total_ht;
1374
-            $this->line->total_tva=$total_tva;
1375
-            $this->line->total_localtax1=$total_localtax1;
1376
-            $this->line->total_localtax2=$total_localtax2;
1377
-            $this->line->total_ttc=$total_ttc;
1378
-            $this->line->product_type=$type;
1379
-            $this->line->special_code=$special_code;
1380
-            $this->line->origin=$origin;
1381
-            $this->line->origin_id=$origin_id;
1382
-            $this->line->fk_parent_line=$fk_parent_line;
1383
-	        $this->line->fk_unit=$fk_unit;
1384
-
1385
-            $this->line->date_start=$date_start;
1386
-            $this->line->date_end=$date_end;
706
+		// Clean parameters
707
+		$this->brouillon = 1;		// set command as draft
1387 708
 
1388
-			$this->line->fk_fournprice = $fk_fournprice;
1389
-			$this->line->pa_ht = $pa_ht;
709
+		// $date_commande is deprecated
710
+		$date = ($this->date_commande ? $this->date_commande : $this->date);
1390 711
 
1391
-			// Multicurrency
1392
-			$this->line->fk_multicurrency			= $this->fk_multicurrency;
1393
-			$this->line->multicurrency_code			= $this->multicurrency_code;
1394
-			$this->line->multicurrency_subprice		= $pu_ht_devise;
1395
-			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1396
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1397
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
712
+		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
713
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
714
+		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
715
+		if (empty($this->fk_multicurrency))
716
+		{
717
+			$this->multicurrency_code = $conf->currency;
718
+			$this->fk_multicurrency = 0;
719
+			$this->multicurrency_tx = 1;
720
+		}
1398 721
 
1399
-            // TODO Ne plus utiliser
1400
-            $this->line->price=$price;
1401
-            $this->line->remise=$remise;
722
+		dol_syslog(get_class($this)."::create user=".$user->id);
1402 723
 
1403
-			if (is_array($array_options) && count($array_options)>0) {
1404
-				$this->line->array_options=$array_options;
724
+		// Check parameters
725
+		if (! empty($this->ref))	// We check that ref is not already used
726
+		{
727
+			$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
728
+			if ($result > 0)
729
+			{
730
+				$this->error='ErrorRefAlreadyExists';
731
+				dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
732
+				$this->db->rollback();
733
+				return -1;
1405 734
 			}
735
+		}
1406 736
 
1407
-            $result=$this->line->insert($user);
1408
-            if ($result > 0)
1409
-            {
1410
-                // Reorder if child line
1411
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1412
-
1413
-                // Mise a jour informations denormalisees au niveau de la commande meme
1414
-                $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1415
-                if ($result > 0)
1416
-                {
1417
-                    $this->db->commit();
1418
-                    return $this->line->rowid;
1419
-                }
1420
-                else
1421
-                {
1422
-                    $this->db->rollback();
1423
-                    return -1;
1424
-                }
1425
-            }
1426
-            else
1427
-            {
1428
-                $this->error=$this->line->error;
1429
-                dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1430
-                $this->db->rollback();
1431
-                return -2;
1432
-            }
1433
-        }
1434
-        else
1435
-        {
1436
-            dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1437
-            return -3;
1438
-        }
1439
-    }
1440
-
1441
-
1442
-    /**
1443
-     *	Add line into array
1444
-     *	$this->client must be loaded
1445
-     *
1446
-     *	@param		int				$idproduct			Product Id
1447
-     *	@param		float			$qty				Quantity
1448
-     *	@param		float			$remise_percent		Product discount relative
1449
-     * 	@param    	int		$date_start         Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1450
-     * 	@param    	int		$date_end           End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1451
-     * 	@return    	void
1452
-     *
1453
-     *	TODO	Remplacer les appels a cette fonction par generation objet Ligne
1454
-     *			insere dans tableau $this->products
1455
-     */
1456
-    function add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
1457
-    {
1458
-        global $conf, $mysoc;
1459
-
1460
-        if (! $qty) $qty = 1;
1461
-
1462
-        if ($idproduct > 0)
1463
-        {
1464
-            $prod=new Product($this->db);
1465
-            $prod->fetch($idproduct);
1466
-
1467
-            $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
1468
-            $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
1469
-            if (empty($tva_tx)) $tva_npr=0;
1470
-            $vat_src_code = '';     // May be defined into tva_tx
1471
-
1472
-            $localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
1473
-            $localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
1474
-
1475
-            // multiprix
1476
-            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
1477
-            $price = $prod->multiprices[$this->thirdparty->price_level];
1478
-            else
1479
-            $price = $prod->price;
1480
-
1481
-            $line=new OrderLine($this->db);
1482
-
1483
-            $line->context = $this->context;
1484
-
1485
-            $line->fk_product=$idproduct;
1486
-            $line->desc=$prod->description;
1487
-            $line->qty=$qty;
1488
-            $line->subprice=$price;
1489
-            $line->remise_percent=$remise_percent;
1490
-            $line->vat_src_code=$vat_src_code;
1491
-            $line->tva_tx=$tva_tx;
1492
-            $line->localtax1_tx=$localtax1_tx;
1493
-            $line->localtax2_tx=$localtax2_tx;
1494
-            $line->ref=$prod->ref;
1495
-            $line->libelle=$prod->label;
1496
-            $line->product_desc=$prod->description;
1497
-	        $line->fk_unit=$prod->fk_unit;
1498
-
1499
-            // Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1500
-            // Save the start and end date of the line in the object
1501
-            if ($date_start) { $line->date_start = $date_start; }
1502
-            if ($date_end)   { $line->date_end = $date_end; }
1503
-
1504
-            $this->lines[] = $line;
1505
-
1506
-            /** POUR AJOUTER AUTOMATIQUEMENT LES SOUSPRODUITS a LA COMMANDE
1507
-             if (! empty($conf->global->PRODUIT_SOUSPRODUITS))
1508
-             {
1509
-             $prod = new Product($this->db);
1510
-             $prod->fetch($idproduct);
1511
-             $prod -> get_sousproduits_arbo ();
1512
-             $prods_arbo = $prod->get_each_prod();
1513
-             if(count($prods_arbo) > 0)
1514
-             {
1515
-             foreach($prods_arbo as $key => $value)
1516
-             {
1517
-             // print "id : ".$value[1].' :qty: '.$value[0].'<br>';
1518
-             if(! in_array($value[1],$this->products))
1519
-             $this->add_product($value[1], $value[0]);
737
+		$soc = new Societe($this->db);
738
+		$result=$soc->fetch($this->socid);
739
+		if ($result < 0)
740
+		{
741
+			$this->error="Failed to fetch company";
742
+			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
743
+			return -2;
744
+		}
745
+		if (! empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
746
+		{
747
+			$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Source"));
748
+			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
749
+			return -1;
750
+		}
1520 751
 
1521
-             }
1522
-             }
752
+		$now=dol_now();
1523 753
 
1524
-             }
1525
-             **/
1526
-        }
1527
-    }
1528
-
1529
-
1530
-    /**
1531
-     *	Get object and lines from database
1532
-     *
1533
-     *	@param      int			$id       		Id of object to load
1534
-     * 	@param		string		$ref			Ref of object
1535
-     * 	@param		string		$ref_ext		External reference of object
1536
-     * 	@param		string		$ref_int		Internal reference of other object
1537
-     *	@return     int         				>0 if OK, <0 if KO, 0 if not found
1538
-     */
1539
-    function fetch($id, $ref='', $ref_ext='', $ref_int='')
1540
-    {
1541
-
1542
-        // Check parameters
1543
-        if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1544
-
1545
-        $sql = 'SELECT c.rowid, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
1546
-        $sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1547
-        $sql.= ', c.fk_account';
1548
-        $sql.= ', c.date_commande';
1549
-        $sql.= ', c.date_livraison';
1550
-        $sql.= ', c.fk_shipping_method';
1551
-        $sql.= ', c.fk_warehouse';
1552
-        $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
1553
-        $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
1554
-        $sql.= ', c.fk_incoterms, c.location_incoterms';
1555
-		$sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
1556
-        $sql.= ", i.libelle as libelle_incoterms";
1557
-        $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1558
-        $sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
1559
-        $sql.= ', ca.code as availability_code, ca.label as availability_label';
1560
-        $sql.= ', dr.code as demand_reason_code';
1561
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
1562
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term') . ')';
1563
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement') . ')';
1564
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
1565
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1566
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1567
-        $sql.= " WHERE c.entity IN (".getEntity('commande').")";
1568
-        if ($id)   	  $sql.= " AND c.rowid=".$id;
1569
-        if ($ref)     $sql.= " AND c.ref='".$this->db->escape($ref)."'";
1570
-        if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1571
-        if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1572
-
1573
-        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1574
-        $result = $this->db->query($sql);
1575
-        if ($result)
1576
-        {
1577
-            $obj = $this->db->fetch_object($result);
1578
-            if ($obj)
1579
-            {
1580
-                $this->id					= $obj->rowid;
1581
-                $this->ref					= $obj->ref;
1582
-                $this->ref_client			= $obj->ref_client;
1583
-                $this->ref_customer			= $obj->ref_client;
1584
-                $this->ref_ext				= $obj->ref_ext;
1585
-                $this->ref_int				= $obj->ref_int;
1586
-                $this->socid				= $obj->fk_soc;
1587
-                $this->statut				= $obj->fk_statut;
1588
-                $this->user_author_id		= $obj->fk_user_author;
1589
-                $this->user_valid           = $obj->fk_user_valid;
1590
-                $this->total_ht				= $obj->total_ht;
1591
-                $this->total_tva			= $obj->total_tva;
1592
-                $this->total_localtax1		= $obj->total_localtax1;
1593
-                $this->total_localtax2		= $obj->total_localtax2;
1594
-                $this->total_ttc			= $obj->total_ttc;
1595
-                $this->date					= $this->db->jdate($obj->date_commande);
1596
-                $this->date_commande		= $this->db->jdate($obj->date_commande);
1597
-                $this->remise				= $obj->remise;
1598
-                $this->remise_percent		= $obj->remise_percent;
1599
-                $this->remise_absolue		= $obj->remise_absolue;
1600
-                $this->source				= $obj->source;
1601
-                $this->facturee				= $obj->billed;			// deprecated
1602
-                $this->billed				= $obj->billed;
1603
-                $this->note					= $obj->note_private;	// deprecated
1604
-                $this->note_private			= $obj->note_private;
1605
-                $this->note_public			= $obj->note_public;
1606
-                $this->fk_project			= $obj->fk_projet;
1607
-                $this->modelpdf				= $obj->model_pdf;
1608
-                $this->mode_reglement_id	= $obj->fk_mode_reglement;
1609
-                $this->mode_reglement_code	= $obj->mode_reglement_code;
1610
-                $this->mode_reglement		= $obj->mode_reglement_libelle;
1611
-                $this->cond_reglement_id	= $obj->fk_cond_reglement;
1612
-                $this->cond_reglement_code	= $obj->cond_reglement_code;
1613
-                $this->cond_reglement		= $obj->cond_reglement_libelle;
1614
-                $this->cond_reglement_doc	= $obj->cond_reglement_libelle_doc;
1615
-                $this->fk_account           = $obj->fk_account;
1616
-                $this->availability_id		= $obj->fk_availability;
1617
-                $this->availability_code	= $obj->availability_code;
1618
-                $this->availability	    	= $obj->availability_label;
1619
-                $this->demand_reason_id		= $obj->fk_input_reason;
1620
-                $this->demand_reason_code	= $obj->demand_reason_code;
1621
-                $this->date_livraison		= $this->db->jdate($obj->date_livraison);
1622
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1623
-                $this->warehouse_id           = ($obj->fk_warehouse>0)?$obj->fk_warehouse:null;
1624
-                $this->fk_delivery_address	= $obj->fk_delivery_address;
754
+		$this->db->begin();
1625 755
 
1626
-				//Incoterms
1627
-				$this->fk_incoterms = $obj->fk_incoterms;
1628
-				$this->location_incoterms = $obj->location_incoterms;
1629
-				$this->libelle_incoterms = $obj->libelle_incoterms;
756
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
757
+		$sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
758
+		$sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
759
+		$sql.= ", fk_shipping_method";
760
+		$sql.= ", fk_warehouse";
761
+		$sql.= ", remise_absolue, remise_percent";
762
+		$sql.= ", fk_incoterms, location_incoterms";
763
+		$sql.= ", entity";
764
+		$sql.= ", fk_multicurrency";
765
+		$sql.= ", multicurrency_code";
766
+		$sql.= ", multicurrency_tx";
767
+		$sql.= ")";
768
+		$sql.= " VALUES ('(PROV)',".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
769
+		$sql.= ", ".($this->fk_project>0?$this->fk_project:"null");
770
+		$sql.= ", '".$this->db->idate($date)."'";
771
+		$sql.= ", ".($this->source>=0 && $this->source != '' ?$this->db->escape($this->source):'null');
772
+		$sql.= ", '".$this->db->escape($this->note_private)."'";
773
+		$sql.= ", '".$this->db->escape($this->note_public)."'";
774
+		$sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
775
+		$sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
776
+		$sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
777
+		$sql.= ", '".$this->db->escape($this->modelpdf)."'";
778
+		$sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null");
779
+		$sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null");
780
+		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
781
+		$sql.= ", ".($this->availability_id>0?$this->availability_id:"null");
782
+		$sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null");
783
+		$sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
784
+		$sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL');
785
+		$sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
786
+		$sql.= ", ".($this->warehouse_id>0?$this->warehouse_id:'NULL');
787
+		$sql.= ", ".($this->remise_absolue>0?$this->db->escape($this->remise_absolue):'NULL');
788
+		$sql.= ", ".($this->remise_percent>0?$this->db->escape($this->remise_percent):0);
789
+		$sql.= ", ".(int) $this->fk_incoterms;
790
+		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
791
+		$sql.= ", ".$conf->entity;
792
+		$sql.= ", ".(int) $this->fk_multicurrency;
793
+		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
794
+		$sql.= ", ".(double) $this->multicurrency_tx;
795
+		$sql.= ")";
1630 796
 
1631
-				// Multicurrency
1632
-				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1633
-				$this->multicurrency_code 		= $obj->multicurrency_code;
1634
-				$this->multicurrency_tx 		= $obj->multicurrency_tx;
1635
-				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1636
-				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1637
-				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
797
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
798
+		$resql=$this->db->query($sql);
799
+		if ($resql)
800
+		{
801
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
1638 802
 
1639
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
803
+			if ($this->id)
804
+			{
805
+				$fk_parent_line=0;
806
+				$num=count($this->lines);
1640 807
 
1641
-                $this->lines				= array();
808
+				/*
809
+                 *  Insert products details into db
810
+                 */
811
+				for ($i=0;$i<$num;$i++)
812
+				{
813
+					$line = $this->lines[$i];
1642 814
 
1643
-                if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
815
+					// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
816
+					//if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
817
+					if (! is_object($line)) $line = (object) $line;
1644 818
 
1645
-                // Retrieve all extrafields for invoice
1646
-                // fetch optionals attributes and labels
1647
-                require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1648
-                $extrafields=new ExtraFields($this->db);
1649
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1650
-               	$this->fetch_optionals($this->id,$extralabels);
819
+					// Reset fk_parent_line for no child products and special product
820
+					if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
821
+						$fk_parent_line = 0;
822
+					}
1651 823
 
1652
-                $this->db->free($result);
824
+					$result = $this->addline(
825
+						$line->desc,
826
+						$line->subprice,
827
+						$line->qty,
828
+						$line->tva_tx,
829
+						$line->localtax1_tx,
830
+						$line->localtax2_tx,
831
+						$line->fk_product,
832
+						$line->remise_percent,
833
+						$line->info_bits,
834
+						$line->fk_remise_except,
835
+						'HT',
836
+						0,
837
+						$line->date_start,
838
+						$line->date_end,
839
+						$line->product_type,
840
+						$line->rang,
841
+						$line->special_code,
842
+						$fk_parent_line,
843
+						$line->fk_fournprice,
844
+						$line->pa_ht,
845
+						$line->label,
846
+						$line->array_options,
847
+						$line->fk_unit,
848
+						$this->element,
849
+						$line->id
850
+					);
851
+					if ($result < 0)
852
+					{
853
+						if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER)
854
+						{
855
+							$this->error=$this->db->lasterror();
856
+							dol_print_error($this->db);
857
+						}
858
+						$this->db->rollback();
859
+						return -1;
860
+					}
861
+					// Defined the new fk_parent_line
862
+					if ($result > 0 && $line->product_type == 9) {
863
+						$fk_parent_line = $result;
864
+					}
865
+				}
1653 866
 
1654
-                /*
1655
-                 * Lines
1656
-                 */
1657
-                $result=$this->fetch_lines();
1658
-                if ($result < 0)
1659
-                {
1660
-                    return -3;
1661
-                }
1662
-                return 1;
1663
-            }
1664
-            else
1665
-            {
1666
-                $this->error='Order with id '.$id.' not found sql='.$sql;
1667
-                return 0;
1668
-            }
1669
-        }
1670
-        else
1671
-        {
1672
-            $this->error=$this->db->error();
1673
-            return -1;
1674
-        }
1675
-    }
1676
-
1677
-
1678
-    /**
1679
-     *	Adding line of fixed discount in the order in DB
1680
-     *
1681
-     *	@param     int	$idremise			Id de la remise fixe
1682
-     *	@return    int          			>0 si ok, <0 si ko
1683
-     */
1684
-    function insert_discount($idremise)
1685
-    {
1686
-        global $langs;
1687
-
1688
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1689
-        include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1690
-
1691
-        $this->db->begin();
1692
-
1693
-        $remise=new DiscountAbsolute($this->db);
1694
-        $result=$remise->fetch($idremise);
1695
-
1696
-        if ($result > 0)
1697
-        {
1698
-            if ($remise->fk_facture)	// Protection against multiple submission
1699
-            {
1700
-                $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1701
-                $this->db->rollback();
1702
-                return -5;
1703
-            }
1704
-
1705
-            $line = new OrderLine($this->db);
1706
-
1707
-            $line->fk_commande=$this->id;
1708
-            $line->fk_remise_except=$remise->id;
1709
-            $line->desc=$remise->description;   	// Description ligne
1710
-            $line->vat_src_code=$remise->vat_src_code;
1711
-            $line->tva_tx=$remise->tva_tx;
1712
-            $line->subprice=-$remise->amount_ht;
1713
-            $line->price=-$remise->amount_ht;
1714
-            $line->fk_product=0;					// Id produit predefini
1715
-            $line->qty=1;
1716
-            $line->remise=0;
1717
-            $line->remise_percent=0;
1718
-            $line->rang=-1;
1719
-            $line->info_bits=2;
1720
-
1721
-            $line->total_ht  = -$remise->amount_ht;
1722
-            $line->total_tva = -$remise->amount_tva;
1723
-            $line->total_ttc = -$remise->amount_ttc;
1724
-
1725
-            $result=$line->insert();
1726
-            if ($result > 0)
1727
-            {
1728
-                $result=$this->update_price(1);
1729
-                if ($result > 0)
1730
-                {
1731
-                    $this->db->commit();
1732
-                    return 1;
1733
-                }
1734
-                else
1735
-                {
1736
-                    $this->db->rollback();
1737
-                    return -1;
1738
-                }
1739
-            }
1740
-            else
1741
-            {
1742
-                $this->error=$line->error;
1743
-                $this->db->rollback();
1744
-                return -2;
1745
-            }
1746
-        }
1747
-        else
1748
-        {
1749
-            $this->db->rollback();
1750
-            return -2;
1751
-        }
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     *	Load array lines
1757
-     *
1758
-     *	@param		int		$only_product	Return only physical products
1759
-     *	@return		int						<0 if KO, >0 if OK
1760
-     */
1761
-    function fetch_lines($only_product=0)
1762
-    {
1763
-        $this->lines=array();
1764
-
1765
-        $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,';
1766
-        $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
1767
-        $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
1768
-	    $sql.= ' l.fk_unit,';
1769
-		$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1770
-        $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,';
1771
-        $sql.= ' p.weight, p.weight_units, p.volume, p.volume_units';
1772
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1773
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1774
-        $sql.= ' WHERE l.fk_commande = '.$this->id;
1775
-        if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1776
-        $sql .= ' ORDER BY l.rang, l.rowid';
1777
-
1778
-        dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1779
-        $result = $this->db->query($sql);
1780
-        if ($result)
1781
-        {
1782
-            $num = $this->db->num_rows($result);
1783
-
1784
-            $i = 0;
1785
-            while ($i < $num)
1786
-            {
1787
-                $objp = $this->db->fetch_object($result);
1788
-
1789
-                $line = new OrderLine($this->db);
1790
-
1791
-                $line->rowid            = $objp->rowid;
1792
-                $line->id               = $objp->rowid;
1793
-                $line->fk_commande      = $objp->fk_commande;
1794
-                $line->commande_id      = $objp->fk_commande;
1795
-                $line->label            = $objp->custom_label;
1796
-                $line->desc             = $objp->description;
1797
-                $line->description      = $objp->description;		// Description line
1798
-                $line->product_type     = $objp->product_type;
1799
-                $line->qty              = $objp->qty;
1800
-
1801
-                $line->vat_src_code     = $objp->vat_src_code;
1802
-                $line->tva_tx           = $objp->tva_tx;
1803
-	            $line->localtax1_tx     = $objp->localtax1_tx;
1804
-                $line->localtax2_tx     = $objp->localtax2_tx;
1805
-	            $line->localtax1_type	= $objp->localtax1_type;
1806
-	            $line->localtax2_type	= $objp->localtax2_type;
1807
-	            $line->total_ht         = $objp->total_ht;
1808
-                $line->total_ttc        = $objp->total_ttc;
1809
-                $line->total_tva        = $objp->total_tva;
1810
-                $line->total_localtax1  = $objp->total_localtax1;
1811
-                $line->total_localtax2  = $objp->total_localtax2;
1812
-                $line->subprice         = $objp->subprice;
1813
-                $line->fk_remise_except = $objp->fk_remise_except;
1814
-                $line->remise_percent   = $objp->remise_percent;
1815
-                $line->price            = $objp->price;
1816
-                $line->fk_product       = $objp->fk_product;
1817
-				$line->fk_fournprice 	= $objp->fk_fournprice;
1818
-		      	$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1819
-		   		$line->pa_ht 			= $marginInfos[0];
1820
-		    	$line->marge_tx			= $marginInfos[1];
1821
-		     	$line->marque_tx		= $marginInfos[2];
1822
-                $line->rang             = $objp->rang;
1823
-                $line->info_bits        = $objp->info_bits;
1824
-                $line->special_code		= $objp->special_code;
1825
-                $line->fk_parent_line	= $objp->fk_parent_line;
1826
-
1827
-                $line->ref				= $objp->product_ref;
1828
-                $line->product_ref		= $objp->product_ref;
1829
-                $line->libelle			= $objp->product_label;
1830
-                $line->product_label	= $objp->product_label;
1831
-                $line->product_desc     = $objp->product_desc;
1832
-                $line->product_tobatch  = $objp->product_tobatch;
1833
-                $line->fk_product_type  = $objp->fk_product_type;	// Produit ou service
1834
-	            $line->fk_unit          = $objp->fk_unit;
1835
-
1836
-	            $line->weight           = $objp->weight;
1837
-	            $line->weight_units     = $objp->weight_units;
1838
-	            $line->volume           = $objp->volume;
1839
-	            $line->volume_units     = $objp->volume_units;
1840
-
1841
-                $line->date_start       = $this->db->jdate($objp->date_start);
1842
-                $line->date_end         = $this->db->jdate($objp->date_end);
867
+				// update ref
868
+				$initialref='(PROV'.$this->id.')';
869
+				if (! empty($this->ref)) $initialref=$this->ref;
1843 870
 
1844
-				// Multicurrency
1845
-				$line->fk_multicurrency 		= $objp->fk_multicurrency;
1846
-				$line->multicurrency_code 		= $objp->multicurrency_code;
1847
-				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
1848
-				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
1849
-				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
1850
-				$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
871
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
872
+				if ($this->db->query($sql))
873
+				{
874
+					if ($this->id)
875
+					{
876
+						$this->ref = $initialref;
1851 877
 
1852
-                $this->lines[$i] = $line;
1853
-
1854
-                $i++;
1855
-            }
1856
-
1857
-            $this->db->free($result);
1858
-
1859
-            return 1;
1860
-        }
1861
-        else
1862
-        {
1863
-            $this->error=$this->db->error();
1864
-            return -3;
1865
-        }
1866
-    }
1867
-
1868
-
1869
-    /**
1870
-     *	Return number of line with type product.
1871
-     *
1872
-     *	@return		int		<0 if KO, Nbr of product lines if OK
1873
-     */
1874
-    function getNbOfProductsLines()
1875
-    {
1876
-        $nb=0;
1877
-        foreach($this->lines as $line)
1878
-        {
1879
-            if ($line->product_type == 0) $nb++;
1880
-        }
1881
-        return $nb;
1882
-    }
1883
-
1884
-    /**
1885
-     *	Return number of line with type service.
1886
-     *
1887
-     *	@return		int		<0 if KO, Nbr of service lines if OK
1888
-     */
1889
-    function getNbOfServicesLines()
1890
-    {
1891
-        $nb=0;
1892
-        foreach($this->lines as $line)
1893
-        {
1894
-            if ($line->product_type == 1) $nb++;
1895
-        }
1896
-        return $nb;
1897
-    }
1898
-
1899
-    /**
1900
-     *	Load array this->expeditions of lines of shipments with nb of products sent for each order line
1901
-     *  Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order
1902
-     *
1903
-     *	@param      int		$filtre_statut      Filter on shipment status
1904
-     * 	@return     int                			<0 if KO, Nb of lines found if OK
1905
-     */
1906
-    function loadExpeditions($filtre_statut=-1)
1907
-    {
1908
-        $this->expeditions = array();
1909
-
1910
-        $sql = 'SELECT cd.rowid, cd.fk_product,';
1911
-        $sql.= ' sum(ed.qty) as qty';
1912
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
1913
-        if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
1914
-        $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
1915
-        $sql.= ' WHERE';
1916
-        if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND';
1917
-        $sql.= ' ed.fk_origin_line = cd.rowid';
1918
-        $sql.= ' AND cd.fk_commande =' .$this->id;
1919
-        if ($this->fk_product > 0) $sql.= ' AND cd.fk_product = '.$this->fk_product;
1920
-        if ($filtre_statut >= 0) $sql.=' AND e.fk_statut >= '.$filtre_statut;
1921
-        $sql.= ' GROUP BY cd.rowid, cd.fk_product';
1922
-        //print $sql;
1923
-
1924
-        dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
1925
-        $result = $this->db->query($sql);
1926
-        if ($result)
1927
-        {
1928
-            $num = $this->db->num_rows($result);
1929
-            $i = 0;
1930
-            while ($i < $num)
1931
-            {
1932
-                $obj = $this->db->fetch_object($result);
1933
-                $this->expeditions[$obj->rowid] = $obj->qty;
1934
-                $i++;
1935
-            }
1936
-            $this->db->free();
1937
-            return $num;
1938
-        }
1939
-        else
1940
-        {
1941
-            $this->error=$this->db->lasterror();
1942
-            return -1;
1943
-        }
1944
-
1945
-    }
1946
-
1947
-    /**
1948
-     * Returns a array with expeditions lines number
1949
-     *
1950
-     * @return	int		Nb of shipments
1951
-     *
1952
-     * TODO deprecate, move to Shipping class
1953
-     */
1954
-    function nb_expedition()
1955
-    {
1956
-        $sql = 'SELECT count(*)';
1957
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
1958
-        $sql.= ', '.MAIN_DB_PREFIX.'element_element as el';
1959
-        $sql.= ' WHERE el.fk_source = '.$this->id;
1960
-        $sql.= " AND el.fk_target = e.rowid";
1961
-        $sql.= " AND el.targettype = 'shipping'";
1962
-
1963
-        $resql = $this->db->query($sql);
1964
-        if ($resql)
1965
-        {
1966
-            $row = $this->db->fetch_row($resql);
1967
-            return $row[0];
1968
-        }
1969
-        else dol_print_error($this->db);
1970
-    }
1971
-
1972
-    /**
1973
-     *	Return a array with the pending stock by product
1974
-     *
1975
-     *	@param      int		$filtre_statut      Filtre sur statut
1976
-     *	@return     int                 		0 si OK, <0 si KO
1977
-     *
1978
-     *	TODO		FONCTION NON FINIE A FINIR
1979
-     */
1980
-    function stock_array($filtre_statut=self::STATUS_CANCELED)
1981
-    {
1982
-        $this->stocks = array();
1983
-
1984
-        // Tableau des id de produit de la commande
1985
-		$array_of_product=array();
878
+						// Add object linked
879
+						if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
880
+						{
881
+							foreach($this->linked_objects as $origin => $tmp_origin_id)
882
+							{
883
+								if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
884
+								{
885
+									foreach($tmp_origin_id as $origin_id)
886
+									{
887
+										$ret = $this->add_object_linked($origin, $origin_id);
888
+										if (! $ret)
889
+										{
890
+											dol_print_error($this->db);
891
+											$error++;
892
+										}
893
+									}
894
+								}
895
+								else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
896
+								{
897
+									$origin_id = $tmp_origin_id;
898
+									$ret = $this->add_object_linked($origin, $origin_id);
899
+									if (! $ret)
900
+									{
901
+										dol_print_error($this->db);
902
+										$error++;
903
+									}
904
+						  		}
905
+							}
906
+						}
1986 907
 
1987
-        // Recherche total en stock pour chaque produit
1988
-        // TODO $array_of_product est défini vide juste au dessus !!
1989
-        if (count($array_of_product))
1990
-        {
1991
-            $sql = "SELECT fk_product, sum(ps.reel) as total";
1992
-            $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
1993
-            $sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")";
1994
-            $sql.= ' GROUP BY fk_product ';
1995
-            $result = $this->db->query($sql);
1996
-            if ($result)
1997
-            {
1998
-                $num = $this->db->num_rows($result);
1999
-                $i = 0;
2000
-                while ($i < $num)
2001
-                {
2002
-                    $obj = $this->db->fetch_object($result);
2003
-                    $this->stocks[$obj->fk_product] = $obj->total;
2004
-                    $i++;
2005
-                }
2006
-                $this->db->free();
2007
-            }
2008
-        }
2009
-        return 0;
2010
-    }
2011
-
2012
-    /**
2013
-     *  Delete an order line
2014
-     *
2015
-     *	@param      User	$user		User object
2016
-     *  @param      int		$lineid		Id of line to delete
2017
-     *  @return     int        		 	>0 if OK, 0 if nothing to do, <0 if KO
2018
-     */
2019
-    function deleteline($user=null, $lineid=0)
2020
-    {
2021
-
2022
-        if ($this->statut == self::STATUS_DRAFT)
2023
-        {
2024
-            $this->db->begin();
2025
-
2026
-            $sql = "SELECT fk_product, qty";
2027
-            $sql.= " FROM ".MAIN_DB_PREFIX."commandedet";
2028
-            $sql.= " WHERE rowid = ".$lineid;
2029
-
2030
-            $result = $this->db->query($sql);
2031
-            if ($result)
2032
-            {
2033
-                $obj = $this->db->fetch_object($result);
2034
-
2035
-                if ($obj)
2036
-                {
2037
-                    $product = new Product($this->db);
2038
-                    $product->id = $obj->fk_product;
2039
-
2040
-                    // Delete line
2041
-                    $line = new OrderLine($this->db);
2042
-
2043
-                    // For triggers
2044
-                    $line->fetch($lineid);
2045
-
2046
-                    if ($line->delete($user) > 0)
2047
-                    {
2048
-                        $result=$this->update_price(1);
2049
-
2050
-                        if ($result > 0)
2051
-                        {
2052
-                            $this->db->commit();
2053
-                            return 1;
2054
-                        }
2055
-                        else
2056
-                        {
2057
-                            $this->db->rollback();
2058
-                            $this->error=$this->db->lasterror();
2059
-                            return -1;
2060
-                        }
2061
-                    }
2062
-                    else
2063
-                    {
2064
-                        $this->db->rollback();
2065
-                        $this->error=$line->error;
2066
-                        return -1;
2067
-                    }
2068
-                }
2069
-                else
2070
-                {
2071
-                    $this->db->rollback();
2072
-                    return 0;
2073
-                }
2074
-            }
2075
-            else
2076
-            {
2077
-                $this->db->rollback();
2078
-                $this->error=$this->db->lasterror();
2079
-                return -1;
2080
-            }
2081
-        }
2082
-        else
2083
-        {
2084
-            return -1;
2085
-        }
2086
-    }
2087
-
2088
-    /**
2089
-     * 	Applique une remise relative
2090
-     *
2091
-     * 	@param     	User		$user		User qui positionne la remise
2092
-     * 	@param     	float		$remise		Discount (percent)
2093
-     * 	@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2094
-     *	@return		int 					<0 if KO, >0 if OK
2095
-     */
2096
-    function set_remise($user, $remise, $notrigger=0)
2097
-    {
2098
-        $remise=trim($remise)?trim($remise):0;
2099
-
2100
-        if ($user->rights->commande->creer)
2101
-        {
2102
-        	$error=0;
2103
-
2104
-        	$this->db->begin();
2105
-
2106
-            $remise=price2num($remise);
2107
-
2108
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2109
-            $sql.= ' SET remise_percent = '.$remise;
2110
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2111
-
2112
-            dol_syslog(__METHOD__, LOG_DEBUG);
2113
-            $resql=$this->db->query($sql);
2114
-            if (!$resql)
2115
-            {
2116
-            	$this->errors[]=$this->db->error();
2117
-            	$error++;
2118
-            }
2119
-
2120
-            if (! $error)
2121
-            {
2122
-            	$this->oldcopy= clone $this;
2123
-            	$this->remise_percent = $remise;
2124
-            	$this->update_price(1);
2125
-            }
2126
-
2127
-            if (! $notrigger && empty($error))
2128
-            {
2129
-            	// Call trigger
2130
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2131
-            	if ($result < 0) $error++;
2132
-            	// End call triggers
2133
-            }
2134
-
2135
-            if (! $error)
2136
-            {
2137
-            	$this->db->commit();
2138
-            	return 1;
2139
-            }
2140
-            else
2141
-            {
2142
-            	foreach($this->errors as $errmsg)
2143
-            	{
2144
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2145
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2146
-            	}
2147
-            	$this->db->rollback();
2148
-            	return -1*$error;
2149
-            }
2150
-        }
2151
-    }
2152
-
2153
-
2154
-    /**
2155
-     * 		Applique une remise absolue
2156
-     *
2157
-     * 		@param     	User		$user 		User qui positionne la remise
2158
-     * 		@param     	float		$remise		Discount
2159
-     * 		@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2160
-     *		@return		int 					<0 if KO, >0 if OK
2161
-     */
2162
-    function set_remise_absolue($user, $remise, $notrigger=0)
2163
-    {
2164
-        $remise=trim($remise)?trim($remise):0;
2165
-
2166
-        if ($user->rights->commande->creer)
2167
-        {
2168
-        	$error=0;
2169
-
2170
-        	$this->db->begin();
2171
-
2172
-            $remise=price2num($remise);
2173
-
2174
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2175
-            $sql.= ' SET remise_absolue = '.$remise;
2176
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2177
-
2178
-            dol_syslog(__METHOD__, LOG_DEBUG);
2179
-            $resql=$this->db->query($sql);
2180
-            if (!$resql)
2181
-            {
2182
-            	$this->errors[]=$this->db->error();
2183
-            	$error++;
2184
-            }
2185
-
2186
-            if (! $error)
2187
-            {
2188
-            	$this->oldcopy= clone $this;
2189
-            	$this->remise_absolue = $remise;
2190
-            	$this->update_price(1);
2191
-            }
2192
-
2193
-            if (! $notrigger && empty($error))
2194
-            {
2195
-            	// Call trigger
2196
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2197
-            	if ($result < 0) $error++;
2198
-            	// End call triggers
2199
-            }
2200
-
2201
-            if (! $error)
2202
-            {
2203
-            	$this->db->commit();
2204
-            	return 1;
2205
-            }
2206
-            else
2207
-            {
2208
-            	foreach($this->errors as $errmsg)
2209
-            	{
2210
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2211
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2212
-            	}
2213
-            	$this->db->rollback();
2214
-            	return -1*$error;
2215
-            }
2216
-        }
2217
-    }
2218
-
2219
-
2220
-    /**
2221
-     *	Set the order date
2222
-     *
2223
-     *	@param      User	$user       Object user making change
2224
-     *	@param      int		$date		Date
2225
-     * 	@param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2226
-     *	@return     int         		<0 if KO, >0 if OK
2227
-     */
2228
-    function set_date($user, $date, $notrigger=0)
2229
-    {
2230
-        if ($user->rights->commande->creer)
2231
-        {
2232
-        	$error=0;
2233
-
2234
-        	$this->db->begin();
2235
-
2236
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2237
-            $sql.= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2238
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2239
-
2240
-            dol_syslog(__METHOD__, LOG_DEBUG);
2241
-            $resql=$this->db->query($sql);
2242
-            if (!$resql)
2243
-            {
2244
-            	$this->errors[]=$this->db->error();
2245
-            	$error++;
2246
-            }
2247
-
2248
-            if (! $error)
2249
-            {
2250
-            	$this->oldcopy= clone $this;
2251
-            	$this->date = $date;
2252
-            }
2253
-
2254
-            if (! $notrigger && empty($error))
2255
-            {
2256
-            	// Call trigger
2257
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2258
-            	if ($result < 0) $error++;
2259
-            	// End call triggers
2260
-            }
2261
-
2262
-            if (! $error)
2263
-            {
2264
-            	$this->db->commit();
2265
-            	return 1;
2266
-            }
2267
-            else
2268
-            {
2269
-            	foreach($this->errors as $errmsg)
2270
-            	{
2271
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2272
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2273
-            	}
2274
-            	$this->db->rollback();
2275
-            	return -1*$error;
2276
-            }
2277
-        }
2278
-        else
2279
-        {
2280
-            return -2;
2281
-        }
2282
-    }
2283
-
2284
-    /**
2285
-     *	Set the planned delivery date
2286
-     *
2287
-     *	@param      User	$user        		Objet utilisateur qui modifie
2288
-     *	@param      int		$date_livraison     Date de livraison
2289
-     *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2290
-     *	@return     int         				<0 si ko, >0 si ok
2291
-     */
2292
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
2293
-    {
2294
-        if ($user->rights->commande->creer)
2295
-        {
2296
-        	$error=0;
2297
-
2298
-        	$this->db->begin();
2299
-
2300
-            $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2301
-            $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2302
-            $sql.= " WHERE rowid = ".$this->id;
2303
-
2304
-            dol_syslog(__METHOD__, LOG_DEBUG);
2305
-            $resql=$this->db->query($sql);
2306
-            if (!$resql)
2307
-            {
2308
-            	$this->errors[]=$this->db->error();
2309
-            	$error++;
2310
-            }
2311
-
2312
-            if (! $error)
2313
-            {
2314
-            	$this->oldcopy= clone $this;
2315
-            	$this->date_livraison = $date_livraison;
2316
-            }
2317
-
2318
-            if (! $notrigger && empty($error))
2319
-            {
2320
-            	// Call trigger
2321
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2322
-            	if ($result < 0) $error++;
2323
-            	// End call triggers
2324
-            }
2325
-
2326
-            if (! $error)
2327
-            {
2328
-            	$this->db->commit();
2329
-            	return 1;
2330
-            }
2331
-            else
2332
-            {
2333
-            	foreach($this->errors as $errmsg)
2334
-            	{
2335
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2336
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2337
-            	}
2338
-            	$this->db->rollback();
2339
-            	return -1*$error;
2340
-            }
2341
-        }
2342
-        else
2343
-        {
2344
-            return -2;
2345
-        }
2346
-    }
2347
-
2348
-    /**
2349
-     *  Return list of orders (eventuelly filtered on a user) into an array
2350
-     *
2351
-     *  @param		int		$shortlist		0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
2352
-     *  @param      int		$draft      	0=not draft, 1=draft
2353
-     *  @param      User	$excluser      	Objet user to exclude
2354
-     *  @param    	int		$socid			Id third pary
2355
-     *  @param    	int		$limit			For pagination
2356
-     *  @param    	int		$offset			For pagination
2357
-     *  @param    	string	$sortfield		Sort criteria
2358
-     *  @param    	string	$sortorder		Sort order
2359
-     *  @return     int             		-1 if KO, array with result if OK
2360
-     */
2361
-    function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
2362
-    {
2363
-        global $user;
2364
-
2365
-        $ga = array();
2366
-
2367
-        $sql = "SELECT s.rowid, s.nom as name, s.client,";
2368
-        $sql.= " c.rowid as cid, c.ref";
2369
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2370
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2371
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2372
-        $sql.= " WHERE c.entity IN (".getEntity('commande').")";
2373
-        $sql.= " AND c.fk_soc = s.rowid";
2374
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2375
-        {
2376
-        	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2377
-        }
2378
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2379
-        if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2380
-        if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id;
2381
-        $sql.= $this->db->order($sortfield,$sortorder);
2382
-        $sql.= $this->db->plimit($limit,$offset);
2383
-
2384
-        $result=$this->db->query($sql);
2385
-        if ($result)
2386
-        {
2387
-            $numc = $this->db->num_rows($result);
2388
-            if ($numc)
2389
-            {
2390
-                $i = 0;
2391
-                while ($i < $numc)
2392
-                {
2393
-                    $obj = $this->db->fetch_object($result);
2394
-
2395
-                    if ($shortlist == 1)
2396
-                    {
2397
-                    	$ga[$obj->cid] = $obj->ref;
2398
-                    }
2399
-                    else if ($shortlist == 2)
2400
-                    {
2401
-                    	$ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2402
-                    }
2403
-                    else
908
+						if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
909
+						{
910
+							$originforcontact = $this->origin;
911
+							$originidforcontact = $this->origin_id;
912
+							if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
913
+							{
914
+								require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
915
+								$exp = new Expedition($db);
916
+								$exp->fetch($this->origin_id);
917
+								$exp->fetchObjectLinked();
918
+								if (count($exp->linkedObjectsIds['commande']) > 0)
919
+								{
920
+									foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
921
+									{
922
+										$originforcontact = 'commande';
923
+										if (is_object($value)) $originidforcontact = $value->id;
924
+										else $originidforcontact = $value;
925
+										break; // We take first one
926
+									}
927
+								}
928
+							}
929
+
930
+							$sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
931
+							$sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
932
+
933
+							$resqlcontact = $this->db->query($sqlcontact);
934
+							if ($resqlcontact)
935
+							{
936
+								while($objcontact = $this->db->fetch_object($resqlcontact))
937
+								{
938
+									//print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
939
+									$this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
940
+								}
941
+							}
942
+							else dol_print_error($resqlcontact);
943
+						}
944
+					}
945
+
946
+					if (! $error)
947
+					{
948
+				   		$result=$this->insertExtraFields();
949
+				   		if ($result < 0) $error++;
950
+					}
951
+
952
+					if (! $error && ! $notrigger)
953
+					{
954
+						// Call trigger
955
+						$result=$this->call_trigger('ORDER_CREATE',$user);
956
+						if ($result < 0) $error++;
957
+						// End call triggers
958
+					}
959
+
960
+					if (! $error)
2404 961
 					{
2405
-                    	$ga[$i]['id']	= $obj->cid;
2406
-                    	$ga[$i]['ref'] 	= $obj->ref;
2407
-                    	$ga[$i]['name'] = $obj->name;
2408
-                    }
2409
-                    $i++;
2410
-                }
2411
-            }
2412
-            return $ga;
2413
-        }
2414
-        else
2415
-        {
2416
-            dol_print_error($this->db);
2417
-            return -1;
2418
-        }
2419
-    }
2420
-
2421
-    /**
2422
-     *	Update delivery delay
2423
-     *
2424
-     *	@param      int		$availability_id	Id du nouveau mode
2425
-     *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2426
-     *	@return     int         				>0 if OK, <0 if KO
2427
-     */
2428
-    function availability($availability_id, $notrigger=0)
2429
-    {
2430
-        global $user;
2431
-
2432
-        dol_syslog('Commande::availability('.$availability_id.')');
2433
-        if ($this->statut >= self::STATUS_DRAFT)
2434
-        {
2435
-        	$error=0;
2436
-
2437
-        	$this->db->begin();
2438
-
2439
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2440
-            $sql .= ' SET fk_availability = '.$availability_id;
2441
-            $sql .= ' WHERE rowid='.$this->id;
2442
-
2443
-            dol_syslog(__METHOD__, LOG_DEBUG);
2444
-            $resql=$this->db->query($sql);
2445
-            if (!$resql)
2446
-            {
2447
-            	$this->errors[]=$this->db->error();
2448
-            	$error++;
2449
-            }
2450
-
2451
-            if (! $error)
2452
-            {
2453
-            	$this->oldcopy= clone $this;
2454
-            	$this->availability_id = $availability_id;
2455
-            }
2456
-
2457
-            if (! $notrigger && empty($error))
2458
-            {
2459
-            	// Call trigger
2460
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2461
-            	if ($result < 0) $error++;
2462
-            	// End call triggers
2463
-            }
2464
-
2465
-            if (! $error)
2466
-            {
2467
-            	$this->db->commit();
2468
-            	return 1;
2469
-            }
2470
-            else
2471
-            {
2472
-            	foreach($this->errors as $errmsg)
2473
-            	{
2474
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2475
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2476
-            	}
2477
-            	$this->db->rollback();
2478
-            	return -1*$error;
2479
-            }
2480
-        }
2481
-        else
2482
-        {
2483
-        	$error_str='Command status do not meet requirement '.$this->statut;
2484
-            dol_syslog(__METHOD__.$error_str, LOG_ERR);
2485
-            $this->error=$error_str;
2486
-            $this->errors[]= $this->error;
2487
-            return -2;
2488
-        }
2489
-    }
2490
-
2491
-    /**
2492
-     *	Update order demand_reason
2493
-     *
2494
-     *  @param      int		$demand_reason_id	Id of new demand
2495
-     *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2496
-     *  @return     int        			 		>0 if ok, <0 if ko
2497
-     */
2498
-    function demand_reason($demand_reason_id, $notrigger=0)
2499
-    {
2500
-        global $user;
2501
-
2502
-        dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2503
-        if ($this->statut >= self::STATUS_DRAFT)
2504
-        {
2505
-        	$error=0;
2506
-
2507
-        	$this->db->begin();
2508
-
2509
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2510
-            $sql .= ' SET fk_input_reason = '.$demand_reason_id;
2511
-            $sql .= ' WHERE rowid='.$this->id;
2512
-
2513
-            dol_syslog(__METHOD__, LOG_DEBUG);
2514
-            $resql=$this->db->query($sql);
2515
-            if (!$resql)
2516
-            {
2517
-            	$this->errors[]=$this->db->error();
2518
-            	$error++;
2519
-            }
2520
-
2521
-            if (! $error)
2522
-            {
2523
-            	$this->oldcopy= clone $this;
2524
-            	$this->demand_reason_id = $demand_reason_id;
2525
-            }
2526
-
2527
-            if (! $notrigger && empty($error))
2528
-            {
2529
-            	// Call trigger
2530
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2531
-            	if ($result < 0) $error++;
2532
-            	// End call triggers
2533
-            }
2534
-
2535
-            if (! $error)
2536
-            {
2537
-            	$this->db->commit();
2538
-            	return 1;
2539
-            }
2540
-            else
2541
-            {
2542
-            	foreach($this->errors as $errmsg)
2543
-            	{
2544
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2545
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2546
-            	}
2547
-            	$this->db->rollback();
2548
-            	return -1*$error;
2549
-            }
2550
-        }
2551
-        else
2552
-        {
2553
-        	$error_str='order status do not meet requirement '.$this->statut;
2554
-        	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2555
-        	$this->error=$error_str;
2556
-        	$this->errors[]= $this->error;
2557
-            return -2;
2558
-        }
2559
-    }
2560
-
2561
-    /**
2562
-     *	Set customer ref
2563
-     *
2564
-     *	@param      User	$user           User that make change
2565
-     *	@param      string	$ref_client     Customer ref
2566
-     *  @param     	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2567
-     *	@return     int             		<0 if KO, >0 if OK
2568
-     */
2569
-    function set_ref_client($user, $ref_client, $notrigger=0)
2570
-    {
2571
-        if ($user->rights->commande->creer)
2572
-        {
2573
-        	$error=0;
2574
-
2575
-        	$this->db->begin();
2576
-
2577
-            $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET';
2578
-            $sql.= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2579
-            $sql.= ' WHERE rowid = '.$this->id;
2580
-
2581
-            dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2582
-            $resql=$this->db->query($sql);
2583
-            if (!$resql)
2584
-            {
2585
-            	$this->errors[]=$this->db->error();
2586
-            	$error++;
2587
-            }
2588
-
2589
-            if (! $error)
2590
-            {
2591
-            	$this->oldcopy= clone $this;
2592
-            	$this->ref_client = $ref_client;
2593
-            }
2594
-
2595
-            if (! $notrigger && empty($error))
2596
-            {
2597
-            	// Call trigger
2598
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2599
-            	if ($result < 0) $error++;
2600
-            	// End call triggers
2601
-            }
2602
-            if (! $error)
2603
-            {
2604
-            	$this->db->commit();
2605
-            	return 1;
2606
-            }
2607
-            else
2608
-            {
2609
-            	foreach($this->errors as $errmsg)
2610
-            	{
2611
-            		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2612
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2613
-            	}
2614
-            	$this->db->rollback();
2615
-            	return -1*$error;
2616
-            }
2617
-        }
2618
-        else
2619
-        {
2620
-            return -1;
2621
-        }
2622
-    }
962
+						$this->db->commit();
963
+						return $this->id;
964
+					}
965
+					else
966
+					{
967
+						$this->db->rollback();
968
+						return -1*$error;
969
+					}
970
+				}
971
+				else
972
+				{
973
+					$this->error=$this->db->lasterror();
974
+					$this->db->rollback();
975
+					return -1;
976
+				}
977
+			}
978
+		}
979
+		else
980
+		{
981
+			dol_print_error($this->db);
982
+			$this->db->rollback();
983
+			return -1;
984
+		}
985
+	}
986
+
987
+
988
+	/**
989
+	 *	Load an object from its id and create a new one in database
990
+	 *
991
+	 *	@param		int			$socid			Id of thirdparty
992
+	 *	@return		int							New id of clone
993
+	 */
994
+	function createFromClone($socid=0)
995
+	{
996
+		global $user,$hookmanager;
997
+
998
+		$error=0;
999
+
1000
+		$this->context['createfromclone'] = 'createfromclone';
1001
+
1002
+		$this->db->begin();
1003
+
1004
+		// get lines so they will be clone
1005
+		foreach($this->lines as $line)
1006
+			$line->fetch_optionals($line->rowid);
1007
+
1008
+		// Load source object
1009
+		$objFrom = clone $this;
1010
+
1011
+		// Change socid if needed
1012
+		if (! empty($socid) && $socid != $this->socid)
1013
+		{
1014
+			$objsoc = new Societe($this->db);
1015
+
1016
+			if ($objsoc->fetch($socid)>0)
1017
+			{
1018
+				$this->socid 				= $objsoc->id;
1019
+				$this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1020
+				$this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1021
+				$this->fk_project			= '';
1022
+				$this->fk_delivery_address	= '';
1023
+			}
1024
+
1025
+			// TODO Change product price if multi-prices
1026
+		}
1027
+
1028
+		$this->id=0;
1029
+		$this->ref = '';
1030
+		$this->statut=self::STATUS_DRAFT;
1031
+
1032
+		// Clear fields
1033
+		$this->user_author_id     = $user->id;
1034
+		$this->user_valid         = '';
1035
+		$this->date				  = dol_now();
1036
+		$this->date_commande	  = dol_now();
1037
+		$this->date_creation      = '';
1038
+		$this->date_validation    = '';
1039
+		$this->ref_client         = '';
1040
+
1041
+		// Create clone
1042
+		$result=$this->create($user);
1043
+		if ($result < 0) $error++;
1044
+
1045
+		if (! $error)
1046
+		{
1047
+			// Hook of thirdparty module
1048
+			if (is_object($hookmanager))
1049
+			{
1050
+				$parameters=array('objFrom'=>$objFrom);
1051
+				$action='';
1052
+				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1053
+				if ($reshook < 0) $error++;
1054
+			}
1055
+
1056
+			// Call trigger
1057
+			$result=$this->call_trigger('ORDER_CLONE',$user);
1058
+			if ($result < 0) $error++;
1059
+			// End call triggers
1060
+		}
1061
+
1062
+		unset($this->context['createfromclone']);
1063
+
1064
+		// End
1065
+		if (! $error)
1066
+		{
1067
+			$this->db->commit();
1068
+			return $this->id;
1069
+		}
1070
+		else
1071
+		{
1072
+			$this->db->rollback();
1073
+			return -1;
1074
+		}
1075
+	}
1076
+
1077
+
1078
+	/**
1079
+	 *  Load an object from a proposal and create a new order into database
1080
+	 *
1081
+	 *  @param      Object			$object 	        Object source
1082
+	 *  @return     int             					<0 if KO, 0 if nothing done, 1 if OK
1083
+	 */
1084
+	function createFromProposal($object)
1085
+	{
1086
+		global $conf,$user,$hookmanager;
1087
+
1088
+		dol_include_once('/core/class/extrafields.class.php');
1089
+
1090
+		$error=0;
1091
+
1092
+
1093
+		$this->date_commande = dol_now();
1094
+		$this->source = 0;
1095
+
1096
+		$num=count($object->lines);
1097
+		for ($i = 0; $i < $num; $i++)
1098
+		{
1099
+			$line = new OrderLine($this->db);
1100
+
1101
+			$line->libelle           = $object->lines[$i]->libelle;
1102
+			$line->label             = $object->lines[$i]->label;
1103
+			$line->desc              = $object->lines[$i]->desc;
1104
+			$line->price             = $object->lines[$i]->price;
1105
+			$line->subprice          = $object->lines[$i]->subprice;
1106
+			$line->vat_src_code      = $object->lines[$i]->vat_src_code;
1107
+			$line->tva_tx            = $object->lines[$i]->tva_tx;
1108
+			$line->localtax1_tx      = $object->lines[$i]->localtax1_tx;
1109
+			$line->localtax2_tx      = $object->lines[$i]->localtax2_tx;
1110
+			$line->qty               = $object->lines[$i]->qty;
1111
+			$line->fk_remise_except  = $object->lines[$i]->fk_remise_except;
1112
+			$line->remise_percent    = $object->lines[$i]->remise_percent;
1113
+			$line->fk_product        = $object->lines[$i]->fk_product;
1114
+			$line->info_bits         = $object->lines[$i]->info_bits;
1115
+			$line->product_type      = $object->lines[$i]->product_type;
1116
+			$line->rang              = $object->lines[$i]->rang;
1117
+			$line->special_code      = $object->lines[$i]->special_code;
1118
+			$line->fk_parent_line    = $object->lines[$i]->fk_parent_line;
1119
+			$line->fk_unit			 = $object->lines[$i]->fk_unit;
1120
+
1121
+			$line->date_start      	= $object->lines[$i]->date_start;
1122
+			$line->date_end    		= $object->lines[$i]->date_end;
1123
+
1124
+			$line->fk_fournprice	= $object->lines[$i]->fk_fournprice;
1125
+			$marginInfos			= getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1126
+			$line->pa_ht			= $marginInfos[0];
1127
+			$line->marge_tx			= $marginInfos[1];
1128
+			$line->marque_tx		= $marginInfos[2];
1129
+
1130
+			// get extrafields from original line
1131
+			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
1132
+			foreach($object->lines[$i]->array_options as $options_key => $value)
1133
+				$line->array_options[$options_key] = $value;
1134
+
1135
+			$this->lines[$i] = $line;
1136
+		}
1137
+
1138
+		$this->socid                = $object->socid;
1139
+		$this->fk_project           = $object->fk_project;
1140
+		$this->cond_reglement_id    = $object->cond_reglement_id;
1141
+		$this->mode_reglement_id    = $object->mode_reglement_id;
1142
+		$this->fk_account           = $object->fk_account;
1143
+		$this->availability_id      = $object->availability_id;
1144
+		$this->demand_reason_id     = $object->demand_reason_id;
1145
+		$this->date_livraison       = $object->date_livraison;
1146
+		$this->shipping_method_id   = $object->shipping_method_id;
1147
+		$this->warehouse_id         = $object->warehouse_id;
1148
+		$this->fk_delivery_address  = $object->fk_delivery_address;
1149
+		$this->contact_id           = $object->contactid;
1150
+		$this->ref_client           = $object->ref_client;
1151
+		$this->note_private         = $object->note_private;
1152
+		$this->note_public          = $object->note_public;
1153
+
1154
+		$this->origin				= $object->element;
1155
+		$this->origin_id			= $object->id;
1156
+
1157
+		// get extrafields from original line
1158
+		$object->fetch_optionals($object->id);
1159
+
1160
+		$e = new ExtraFields($this->db);
1161
+		$element_extrafields = $e->fetch_name_optionals_label($this->element);
1162
+
1163
+		foreach($object->array_options as $options_key => $value) {
1164
+			if(array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)){
1165
+				$this->array_options[$options_key] = $value;
1166
+			}
1167
+		}
1168
+		// Possibility to add external linked objects with hooks
1169
+		$this->linked_objects[$this->origin] = $this->origin_id;
1170
+		if (is_array($object->other_linked_objects) && ! empty($object->other_linked_objects))
1171
+		{
1172
+		   	$this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1173
+		}
1174
+
1175
+		$ret = $this->create($user);
1176
+
1177
+		if ($ret > 0)
1178
+		{
1179
+			// Actions hooked (by external module)
1180
+			$hookmanager->initHooks(array('orderdao'));
1181
+
1182
+			$parameters=array('objFrom'=>$object);
1183
+			$action='';
1184
+			$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1185
+			if ($reshook < 0) $error++;
1186
+
1187
+			if (! $error)
1188
+			{
1189
+				// Ne pas passer par la commande provisoire
1190
+				if ($conf->global->COMMANDE_VALID_AFTER_CLOSE_PROPAL == 1)
1191
+				{
1192
+					$this->fetch($ret);
1193
+					$this->valid($user);
1194
+				}
1195
+				return $ret;
1196
+			}
1197
+			else return -1;
1198
+		}
1199
+		else return -1;
1200
+	}
1201
+
1202
+
1203
+	/**
1204
+	 *	Add an order line into database (linked to product/service or not)
1205
+	 *
1206
+	 *	@param      string			$desc            	Description of line
1207
+	 *	@param      float			$pu_ht    	        Unit price (without tax)
1208
+	 *	@param      float			$qty             	Quantite
1209
+	 *	@param      float			$txtva           	Taux de tva force, sinon -1
1210
+	 *	@param      float			$txlocaltax1		Local tax 1 rate
1211
+	 *	@param      float			$txlocaltax2		Local tax 2 rate
1212
+	 *	@param      int				$fk_product      	Id of product
1213
+	 *	@param      float			$remise_percent  	Pourcentage de remise de la ligne
1214
+	 *	@param      int				$info_bits			Bits de type de lignes
1215
+	 *	@param      int				$fk_remise_except	Id remise
1216
+	 *	@param      string			$price_base_type	HT or TTC
1217
+	 *	@param      float			$pu_ttc    		    Prix unitaire TTC
1218
+	 *	@param      int				$date_start       	Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1219
+	 *	@param      int				$date_end         	End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1220
+	 *	@param      int				$type				Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
1221
+	 *	@param      int				$rang             	Position of line
1222
+	 *	@param		int				$special_code		Special code (also used by externals modules!)
1223
+	 *	@param		int				$fk_parent_line		Parent line
1224
+	 *  @param		int				$fk_fournprice		Id supplier price
1225
+	 *  @param		int				$pa_ht				Buying price (without tax)
1226
+	 *  @param		string			$label				Label
1227
+	 *  @param		array			$array_options		extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
1228
+	 * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
1229
+	 * 	@param		string		    $origin				'order', ...
1230
+	 *  @param		int			    $origin_id			Id of origin object
1231
+	 * 	@param		double			$pu_ht_devise		Unit price in currency
1232
+	 *	@return     int             					>0 if OK, <0 if KO
1233
+	 *
1234
+	 *	@see        add_product
1235
+	 *
1236
+	 *	Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
1237
+	 *	de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
1238
+	 *	par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
1239
+	 *	et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
1240
+	 */
1241
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise = 0)
1242
+	{
1243
+		global $mysoc, $conf, $langs, $user;
1244
+
1245
+		dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit", LOG_DEBUG);
1246
+
1247
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1248
+
1249
+		// Clean parameters
1250
+		if (empty($remise_percent)) $remise_percent=0;
1251
+		if (empty($qty)) $qty=0;
1252
+		if (empty($info_bits)) $info_bits=0;
1253
+		if (empty($rang)) $rang=0;
1254
+		if (empty($txtva)) $txtva=0;
1255
+		if (empty($txlocaltax1)) $txlocaltax1=0;
1256
+		if (empty($txlocaltax2)) $txlocaltax2=0;
1257
+		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
1258
+		if (empty($this->fk_multicurrency)) $this->fk_multicurrency=0;
1259
+
1260
+		$remise_percent=price2num($remise_percent);
1261
+		$qty=price2num($qty);
1262
+		$pu_ht=price2num($pu_ht);
1263
+		$pu_ttc=price2num($pu_ttc);
1264
+		$pa_ht=price2num($pa_ht);
1265
+		$txtva = price2num($txtva);
1266
+		$txlocaltax1 = price2num($txlocaltax1);
1267
+		$txlocaltax2 = price2num($txlocaltax2);
1268
+		if ($price_base_type=='HT')
1269
+		{
1270
+			$pu=$pu_ht;
1271
+		}
1272
+		else
1273
+		{
1274
+			$pu=$pu_ttc;
1275
+		}
1276
+		$label=trim($label);
1277
+		$desc=trim($desc);
1278
+
1279
+		// Check parameters
1280
+		if ($type < 0) return -1;
1281
+
1282
+		if ($this->statut == self::STATUS_DRAFT)
1283
+		{
1284
+			$this->db->begin();
1285
+
1286
+			$product_type=$type;
1287
+			if (!empty($fk_product))
1288
+			{
1289
+				$product=new Product($this->db);
1290
+				$result=$product->fetch($fk_product);
1291
+				$product_type=$product->type;
1292
+
1293
+				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
1294
+				{
1295
+					$langs->load("errors");
1296
+					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1297
+					dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1298
+					$this->db->rollback();
1299
+					return self::STOCK_NOT_ENOUGH_FOR_ORDER;
1300
+				}
1301
+			}
1302
+			// Calcul du total TTC et de la TVA pour la ligne a partir de
1303
+			// qty, pu, remise_percent et txtva
1304
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1305
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1306
+
1307
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
1308
+
1309
+	   		// Clean vat code
1310
+			$vat_src_code='';
1311
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
1312
+			{
1313
+				$vat_src_code = $reg[1];
1314
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1315
+			}
1316
+
1317
+			$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1318
+
1319
+			$total_ht  = $tabprice[0];
1320
+			$total_tva = $tabprice[1];
1321
+			$total_ttc = $tabprice[2];
1322
+			$total_localtax1 = $tabprice[9];
1323
+			$total_localtax2 = $tabprice[10];
1324
+			$pu_ht = $tabprice[3];
1325
+
1326
+			// MultiCurrency
1327
+			$multicurrency_total_ht  = $tabprice[16];
1328
+			$multicurrency_total_tva = $tabprice[17];
1329
+			$multicurrency_total_ttc = $tabprice[18];
1330
+			$pu_ht_devise = $tabprice[19];
1331
+
1332
+			// Rang to use
1333
+			$rangtouse = $rang;
1334
+			if ($rangtouse == -1)
1335
+			{
1336
+				$rangmax = $this->line_max($fk_parent_line);
1337
+				$rangtouse = $rangmax + 1;
1338
+			}
1339
+
1340
+			// TODO A virer
1341
+			// Anciens indicateurs: $price, $remise (a ne plus utiliser)
1342
+			$price = $pu;
1343
+			$remise = 0;
1344
+			if ($remise_percent > 0)
1345
+			{
1346
+				$remise = round(($pu * $remise_percent / 100), 2);
1347
+				$price = $pu - $remise;
1348
+			}
1349
+
1350
+			// Insert line
1351
+			$this->line=new OrderLine($this->db);
1352
+
1353
+			$this->line->context = $this->context;
1354
+
1355
+			$this->line->fk_commande=$this->id;
1356
+			$this->line->label=$label;
1357
+			$this->line->desc=$desc;
1358
+			$this->line->qty=$qty;
1359
+
1360
+			$this->line->vat_src_code=$vat_src_code;
1361
+			$this->line->tva_tx=$txtva;
1362
+			$this->line->localtax1_tx=$localtaxes_type[1];
1363
+			$this->line->localtax2_tx=$localtaxes_type[3];
1364
+			$this->line->localtax1_type=$localtaxes_type[0];
1365
+			$this->line->localtax2_type=$localtaxes_type[2];
1366
+			$this->line->fk_product=$fk_product;
1367
+			$this->line->product_type=$product_type;
1368
+			$this->line->fk_remise_except=$fk_remise_except;
1369
+			$this->line->remise_percent=$remise_percent;
1370
+			$this->line->subprice=$pu_ht;
1371
+			$this->line->rang=$rangtouse;
1372
+			$this->line->info_bits=$info_bits;
1373
+			$this->line->total_ht=$total_ht;
1374
+			$this->line->total_tva=$total_tva;
1375
+			$this->line->total_localtax1=$total_localtax1;
1376
+			$this->line->total_localtax2=$total_localtax2;
1377
+			$this->line->total_ttc=$total_ttc;
1378
+			$this->line->product_type=$type;
1379
+			$this->line->special_code=$special_code;
1380
+			$this->line->origin=$origin;
1381
+			$this->line->origin_id=$origin_id;
1382
+			$this->line->fk_parent_line=$fk_parent_line;
1383
+			$this->line->fk_unit=$fk_unit;
1384
+
1385
+			$this->line->date_start=$date_start;
1386
+			$this->line->date_end=$date_end;
1387
+
1388
+			$this->line->fk_fournprice = $fk_fournprice;
1389
+			$this->line->pa_ht = $pa_ht;
1390
+
1391
+			// Multicurrency
1392
+			$this->line->fk_multicurrency			= $this->fk_multicurrency;
1393
+			$this->line->multicurrency_code			= $this->multicurrency_code;
1394
+			$this->line->multicurrency_subprice		= $pu_ht_devise;
1395
+			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1396
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1397
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1398
+
1399
+			// TODO Ne plus utiliser
1400
+			$this->line->price=$price;
1401
+			$this->line->remise=$remise;
1402
+
1403
+			if (is_array($array_options) && count($array_options)>0) {
1404
+				$this->line->array_options=$array_options;
1405
+			}
1406
+
1407
+			$result=$this->line->insert($user);
1408
+			if ($result > 0)
1409
+			{
1410
+				// Reorder if child line
1411
+				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1412
+
1413
+				// Mise a jour informations denormalisees au niveau de la commande meme
1414
+				$result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1415
+				if ($result > 0)
1416
+				{
1417
+					$this->db->commit();
1418
+					return $this->line->rowid;
1419
+				}
1420
+				else
1421
+				{
1422
+					$this->db->rollback();
1423
+					return -1;
1424
+				}
1425
+			}
1426
+			else
1427
+			{
1428
+				$this->error=$this->line->error;
1429
+				dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1430
+				$this->db->rollback();
1431
+				return -2;
1432
+			}
1433
+		}
1434
+		else
1435
+		{
1436
+			dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1437
+			return -3;
1438
+		}
1439
+	}
1440
+
1441
+
1442
+	/**
1443
+	 *	Add line into array
1444
+	 *	$this->client must be loaded
1445
+	 *
1446
+	 *	@param		int				$idproduct			Product Id
1447
+	 *	@param		float			$qty				Quantity
1448
+	 *	@param		float			$remise_percent		Product discount relative
1449
+	 * 	@param    	int		$date_start         Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1450
+	 * 	@param    	int		$date_end           End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1451
+	 * 	@return    	void
1452
+	 *
1453
+	 *	TODO	Remplacer les appels a cette fonction par generation objet Ligne
1454
+	 *			insere dans tableau $this->products
1455
+	 */
1456
+	function add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
1457
+	{
1458
+		global $conf, $mysoc;
1459
+
1460
+		if (! $qty) $qty = 1;
1461
+
1462
+		if ($idproduct > 0)
1463
+		{
1464
+			$prod=new Product($this->db);
1465
+			$prod->fetch($idproduct);
1466
+
1467
+			$tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
1468
+			$tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
1469
+			if (empty($tva_tx)) $tva_npr=0;
1470
+			$vat_src_code = '';     // May be defined into tva_tx
1471
+
1472
+			$localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
1473
+			$localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
1474
+
1475
+			// multiprix
1476
+			if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
1477
+			$price = $prod->multiprices[$this->thirdparty->price_level];
1478
+			else
1479
+			$price = $prod->price;
1480
+
1481
+			$line=new OrderLine($this->db);
1482
+
1483
+			$line->context = $this->context;
1484
+
1485
+			$line->fk_product=$idproduct;
1486
+			$line->desc=$prod->description;
1487
+			$line->qty=$qty;
1488
+			$line->subprice=$price;
1489
+			$line->remise_percent=$remise_percent;
1490
+			$line->vat_src_code=$vat_src_code;
1491
+			$line->tva_tx=$tva_tx;
1492
+			$line->localtax1_tx=$localtax1_tx;
1493
+			$line->localtax2_tx=$localtax2_tx;
1494
+			$line->ref=$prod->ref;
1495
+			$line->libelle=$prod->label;
1496
+			$line->product_desc=$prod->description;
1497
+			$line->fk_unit=$prod->fk_unit;
1498
+
1499
+			// Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1500
+			// Save the start and end date of the line in the object
1501
+			if ($date_start) { $line->date_start = $date_start; }
1502
+			if ($date_end)   { $line->date_end = $date_end; }
1503
+
1504
+			$this->lines[] = $line;
1505
+
1506
+			/** POUR AJOUTER AUTOMATIQUEMENT LES SOUSPRODUITS a LA COMMANDE
1507
+             if (! empty($conf->global->PRODUIT_SOUSPRODUITS))
1508
+             {
1509
+             $prod = new Product($this->db);
1510
+             $prod->fetch($idproduct);
1511
+             $prod -> get_sousproduits_arbo ();
1512
+             $prods_arbo = $prod->get_each_prod();
1513
+             if(count($prods_arbo) > 0)
1514
+             {
1515
+             foreach($prods_arbo as $key => $value)
1516
+             {
1517
+             // print "id : ".$value[1].' :qty: '.$value[0].'<br>';
1518
+             if(! in_array($value[1],$this->products))
1519
+             $this->add_product($value[1], $value[0]);
1520
+
1521
+             }
1522
+             }
1523
+
1524
+             }
1525
+			 **/
1526
+		}
1527
+	}
1528
+
1529
+
1530
+	/**
1531
+	 *	Get object and lines from database
1532
+	 *
1533
+	 *	@param      int			$id       		Id of object to load
1534
+	 * 	@param		string		$ref			Ref of object
1535
+	 * 	@param		string		$ref_ext		External reference of object
1536
+	 * 	@param		string		$ref_int		Internal reference of other object
1537
+	 *	@return     int         				>0 if OK, <0 if KO, 0 if not found
1538
+	 */
1539
+	function fetch($id, $ref='', $ref_ext='', $ref_int='')
1540
+	{
1541
+
1542
+		// Check parameters
1543
+		if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1544
+
1545
+		$sql = 'SELECT c.rowid, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
1546
+		$sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1547
+		$sql.= ', c.fk_account';
1548
+		$sql.= ', c.date_commande';
1549
+		$sql.= ', c.date_livraison';
1550
+		$sql.= ', c.fk_shipping_method';
1551
+		$sql.= ', c.fk_warehouse';
1552
+		$sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
1553
+		$sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
1554
+		$sql.= ', c.fk_incoterms, c.location_incoterms';
1555
+		$sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
1556
+		$sql.= ", i.libelle as libelle_incoterms";
1557
+		$sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1558
+		$sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
1559
+		$sql.= ', ca.code as availability_code, ca.label as availability_label';
1560
+		$sql.= ', dr.code as demand_reason_code';
1561
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
1562
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term') . ')';
1563
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement') . ')';
1564
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
1565
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1566
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1567
+		$sql.= " WHERE c.entity IN (".getEntity('commande').")";
1568
+		if ($id)   	  $sql.= " AND c.rowid=".$id;
1569
+		if ($ref)     $sql.= " AND c.ref='".$this->db->escape($ref)."'";
1570
+		if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1571
+		if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1572
+
1573
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1574
+		$result = $this->db->query($sql);
1575
+		if ($result)
1576
+		{
1577
+			$obj = $this->db->fetch_object($result);
1578
+			if ($obj)
1579
+			{
1580
+				$this->id					= $obj->rowid;
1581
+				$this->ref					= $obj->ref;
1582
+				$this->ref_client			= $obj->ref_client;
1583
+				$this->ref_customer			= $obj->ref_client;
1584
+				$this->ref_ext				= $obj->ref_ext;
1585
+				$this->ref_int				= $obj->ref_int;
1586
+				$this->socid				= $obj->fk_soc;
1587
+				$this->statut				= $obj->fk_statut;
1588
+				$this->user_author_id		= $obj->fk_user_author;
1589
+				$this->user_valid           = $obj->fk_user_valid;
1590
+				$this->total_ht				= $obj->total_ht;
1591
+				$this->total_tva			= $obj->total_tva;
1592
+				$this->total_localtax1		= $obj->total_localtax1;
1593
+				$this->total_localtax2		= $obj->total_localtax2;
1594
+				$this->total_ttc			= $obj->total_ttc;
1595
+				$this->date					= $this->db->jdate($obj->date_commande);
1596
+				$this->date_commande		= $this->db->jdate($obj->date_commande);
1597
+				$this->remise				= $obj->remise;
1598
+				$this->remise_percent		= $obj->remise_percent;
1599
+				$this->remise_absolue		= $obj->remise_absolue;
1600
+				$this->source				= $obj->source;
1601
+				$this->facturee				= $obj->billed;			// deprecated
1602
+				$this->billed				= $obj->billed;
1603
+				$this->note					= $obj->note_private;	// deprecated
1604
+				$this->note_private			= $obj->note_private;
1605
+				$this->note_public			= $obj->note_public;
1606
+				$this->fk_project			= $obj->fk_projet;
1607
+				$this->modelpdf				= $obj->model_pdf;
1608
+				$this->mode_reglement_id	= $obj->fk_mode_reglement;
1609
+				$this->mode_reglement_code	= $obj->mode_reglement_code;
1610
+				$this->mode_reglement		= $obj->mode_reglement_libelle;
1611
+				$this->cond_reglement_id	= $obj->fk_cond_reglement;
1612
+				$this->cond_reglement_code	= $obj->cond_reglement_code;
1613
+				$this->cond_reglement		= $obj->cond_reglement_libelle;
1614
+				$this->cond_reglement_doc	= $obj->cond_reglement_libelle_doc;
1615
+				$this->fk_account           = $obj->fk_account;
1616
+				$this->availability_id		= $obj->fk_availability;
1617
+				$this->availability_code	= $obj->availability_code;
1618
+				$this->availability	    	= $obj->availability_label;
1619
+				$this->demand_reason_id		= $obj->fk_input_reason;
1620
+				$this->demand_reason_code	= $obj->demand_reason_code;
1621
+				$this->date_livraison		= $this->db->jdate($obj->date_livraison);
1622
+				$this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1623
+				$this->warehouse_id           = ($obj->fk_warehouse>0)?$obj->fk_warehouse:null;
1624
+				$this->fk_delivery_address	= $obj->fk_delivery_address;
1625
+
1626
+				//Incoterms
1627
+				$this->fk_incoterms = $obj->fk_incoterms;
1628
+				$this->location_incoterms = $obj->location_incoterms;
1629
+				$this->libelle_incoterms = $obj->libelle_incoterms;
1630
+
1631
+				// Multicurrency
1632
+				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1633
+				$this->multicurrency_code 		= $obj->multicurrency_code;
1634
+				$this->multicurrency_tx 		= $obj->multicurrency_tx;
1635
+				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1636
+				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1637
+				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1638
+
1639
+				$this->extraparams			= (array) json_decode($obj->extraparams, true);
1640
+
1641
+				$this->lines				= array();
1642
+
1643
+				if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
1644
+
1645
+				// Retrieve all extrafields for invoice
1646
+				// fetch optionals attributes and labels
1647
+				require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1648
+				$extrafields=new ExtraFields($this->db);
1649
+				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1650
+			   	$this->fetch_optionals($this->id,$extralabels);
1651
+
1652
+				$this->db->free($result);
1653
+
1654
+				/*
1655
+                 * Lines
1656
+                 */
1657
+				$result=$this->fetch_lines();
1658
+				if ($result < 0)
1659
+				{
1660
+					return -3;
1661
+				}
1662
+				return 1;
1663
+			}
1664
+			else
1665
+			{
1666
+				$this->error='Order with id '.$id.' not found sql='.$sql;
1667
+				return 0;
1668
+			}
1669
+		}
1670
+		else
1671
+		{
1672
+			$this->error=$this->db->error();
1673
+			return -1;
1674
+		}
1675
+	}
1676
+
1677
+
1678
+	/**
1679
+	 *	Adding line of fixed discount in the order in DB
1680
+	 *
1681
+	 *	@param     int	$idremise			Id de la remise fixe
1682
+	 *	@return    int          			>0 si ok, <0 si ko
1683
+	 */
1684
+	function insert_discount($idremise)
1685
+	{
1686
+		global $langs;
1687
+
1688
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1689
+		include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1690
+
1691
+		$this->db->begin();
1692
+
1693
+		$remise=new DiscountAbsolute($this->db);
1694
+		$result=$remise->fetch($idremise);
1695
+
1696
+		if ($result > 0)
1697
+		{
1698
+			if ($remise->fk_facture)	// Protection against multiple submission
1699
+			{
1700
+				$this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1701
+				$this->db->rollback();
1702
+				return -5;
1703
+			}
1704
+
1705
+			$line = new OrderLine($this->db);
1706
+
1707
+			$line->fk_commande=$this->id;
1708
+			$line->fk_remise_except=$remise->id;
1709
+			$line->desc=$remise->description;   	// Description ligne
1710
+			$line->vat_src_code=$remise->vat_src_code;
1711
+			$line->tva_tx=$remise->tva_tx;
1712
+			$line->subprice=-$remise->amount_ht;
1713
+			$line->price=-$remise->amount_ht;
1714
+			$line->fk_product=0;					// Id produit predefini
1715
+			$line->qty=1;
1716
+			$line->remise=0;
1717
+			$line->remise_percent=0;
1718
+			$line->rang=-1;
1719
+			$line->info_bits=2;
1720
+
1721
+			$line->total_ht  = -$remise->amount_ht;
1722
+			$line->total_tva = -$remise->amount_tva;
1723
+			$line->total_ttc = -$remise->amount_ttc;
1724
+
1725
+			$result=$line->insert();
1726
+			if ($result > 0)
1727
+			{
1728
+				$result=$this->update_price(1);
1729
+				if ($result > 0)
1730
+				{
1731
+					$this->db->commit();
1732
+					return 1;
1733
+				}
1734
+				else
1735
+				{
1736
+					$this->db->rollback();
1737
+					return -1;
1738
+				}
1739
+			}
1740
+			else
1741
+			{
1742
+				$this->error=$line->error;
1743
+				$this->db->rollback();
1744
+				return -2;
1745
+			}
1746
+		}
1747
+		else
1748
+		{
1749
+			$this->db->rollback();
1750
+			return -2;
1751
+		}
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 *	Load array lines
1757
+	 *
1758
+	 *	@param		int		$only_product	Return only physical products
1759
+	 *	@return		int						<0 if KO, >0 if OK
1760
+	 */
1761
+	function fetch_lines($only_product=0)
1762
+	{
1763
+		$this->lines=array();
1764
+
1765
+		$sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,';
1766
+		$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
1767
+		$sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
1768
+		$sql.= ' l.fk_unit,';
1769
+		$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1770
+		$sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,';
1771
+		$sql.= ' p.weight, p.weight_units, p.volume, p.volume_units';
1772
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1773
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1774
+		$sql.= ' WHERE l.fk_commande = '.$this->id;
1775
+		if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1776
+		$sql .= ' ORDER BY l.rang, l.rowid';
1777
+
1778
+		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1779
+		$result = $this->db->query($sql);
1780
+		if ($result)
1781
+		{
1782
+			$num = $this->db->num_rows($result);
1783
+
1784
+			$i = 0;
1785
+			while ($i < $num)
1786
+			{
1787
+				$objp = $this->db->fetch_object($result);
1788
+
1789
+				$line = new OrderLine($this->db);
1790
+
1791
+				$line->rowid            = $objp->rowid;
1792
+				$line->id               = $objp->rowid;
1793
+				$line->fk_commande      = $objp->fk_commande;
1794
+				$line->commande_id      = $objp->fk_commande;
1795
+				$line->label            = $objp->custom_label;
1796
+				$line->desc             = $objp->description;
1797
+				$line->description      = $objp->description;		// Description line
1798
+				$line->product_type     = $objp->product_type;
1799
+				$line->qty              = $objp->qty;
1800
+
1801
+				$line->vat_src_code     = $objp->vat_src_code;
1802
+				$line->tva_tx           = $objp->tva_tx;
1803
+				$line->localtax1_tx     = $objp->localtax1_tx;
1804
+				$line->localtax2_tx     = $objp->localtax2_tx;
1805
+				$line->localtax1_type	= $objp->localtax1_type;
1806
+				$line->localtax2_type	= $objp->localtax2_type;
1807
+				$line->total_ht         = $objp->total_ht;
1808
+				$line->total_ttc        = $objp->total_ttc;
1809
+				$line->total_tva        = $objp->total_tva;
1810
+				$line->total_localtax1  = $objp->total_localtax1;
1811
+				$line->total_localtax2  = $objp->total_localtax2;
1812
+				$line->subprice         = $objp->subprice;
1813
+				$line->fk_remise_except = $objp->fk_remise_except;
1814
+				$line->remise_percent   = $objp->remise_percent;
1815
+				$line->price            = $objp->price;
1816
+				$line->fk_product       = $objp->fk_product;
1817
+				$line->fk_fournprice 	= $objp->fk_fournprice;
1818
+			  	$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1819
+		   		$line->pa_ht 			= $marginInfos[0];
1820
+				$line->marge_tx			= $marginInfos[1];
1821
+			 	$line->marque_tx		= $marginInfos[2];
1822
+				$line->rang             = $objp->rang;
1823
+				$line->info_bits        = $objp->info_bits;
1824
+				$line->special_code		= $objp->special_code;
1825
+				$line->fk_parent_line	= $objp->fk_parent_line;
1826
+
1827
+				$line->ref				= $objp->product_ref;
1828
+				$line->product_ref		= $objp->product_ref;
1829
+				$line->libelle			= $objp->product_label;
1830
+				$line->product_label	= $objp->product_label;
1831
+				$line->product_desc     = $objp->product_desc;
1832
+				$line->product_tobatch  = $objp->product_tobatch;
1833
+				$line->fk_product_type  = $objp->fk_product_type;	// Produit ou service
1834
+				$line->fk_unit          = $objp->fk_unit;
1835
+
1836
+				$line->weight           = $objp->weight;
1837
+				$line->weight_units     = $objp->weight_units;
1838
+				$line->volume           = $objp->volume;
1839
+				$line->volume_units     = $objp->volume_units;
1840
+
1841
+				$line->date_start       = $this->db->jdate($objp->date_start);
1842
+				$line->date_end         = $this->db->jdate($objp->date_end);
1843
+
1844
+				// Multicurrency
1845
+				$line->fk_multicurrency 		= $objp->fk_multicurrency;
1846
+				$line->multicurrency_code 		= $objp->multicurrency_code;
1847
+				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
1848
+				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
1849
+				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
1850
+				$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
1851
+
1852
+				$this->lines[$i] = $line;
1853
+
1854
+				$i++;
1855
+			}
1856
+
1857
+			$this->db->free($result);
1858
+
1859
+			return 1;
1860
+		}
1861
+		else
1862
+		{
1863
+			$this->error=$this->db->error();
1864
+			return -3;
1865
+		}
1866
+	}
1867
+
1868
+
1869
+	/**
1870
+	 *	Return number of line with type product.
1871
+	 *
1872
+	 *	@return		int		<0 if KO, Nbr of product lines if OK
1873
+	 */
1874
+	function getNbOfProductsLines()
1875
+	{
1876
+		$nb=0;
1877
+		foreach($this->lines as $line)
1878
+		{
1879
+			if ($line->product_type == 0) $nb++;
1880
+		}
1881
+		return $nb;
1882
+	}
1883
+
1884
+	/**
1885
+	 *	Return number of line with type service.
1886
+	 *
1887
+	 *	@return		int		<0 if KO, Nbr of service lines if OK
1888
+	 */
1889
+	function getNbOfServicesLines()
1890
+	{
1891
+		$nb=0;
1892
+		foreach($this->lines as $line)
1893
+		{
1894
+			if ($line->product_type == 1) $nb++;
1895
+		}
1896
+		return $nb;
1897
+	}
1898
+
1899
+	/**
1900
+	 *	Load array this->expeditions of lines of shipments with nb of products sent for each order line
1901
+	 *  Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order
1902
+	 *
1903
+	 *	@param      int		$filtre_statut      Filter on shipment status
1904
+	 * 	@return     int                			<0 if KO, Nb of lines found if OK
1905
+	 */
1906
+	function loadExpeditions($filtre_statut=-1)
1907
+	{
1908
+		$this->expeditions = array();
1909
+
1910
+		$sql = 'SELECT cd.rowid, cd.fk_product,';
1911
+		$sql.= ' sum(ed.qty) as qty';
1912
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
1913
+		if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
1914
+		$sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
1915
+		$sql.= ' WHERE';
1916
+		if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND';
1917
+		$sql.= ' ed.fk_origin_line = cd.rowid';
1918
+		$sql.= ' AND cd.fk_commande =' .$this->id;
1919
+		if ($this->fk_product > 0) $sql.= ' AND cd.fk_product = '.$this->fk_product;
1920
+		if ($filtre_statut >= 0) $sql.=' AND e.fk_statut >= '.$filtre_statut;
1921
+		$sql.= ' GROUP BY cd.rowid, cd.fk_product';
1922
+		//print $sql;
1923
+
1924
+		dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
1925
+		$result = $this->db->query($sql);
1926
+		if ($result)
1927
+		{
1928
+			$num = $this->db->num_rows($result);
1929
+			$i = 0;
1930
+			while ($i < $num)
1931
+			{
1932
+				$obj = $this->db->fetch_object($result);
1933
+				$this->expeditions[$obj->rowid] = $obj->qty;
1934
+				$i++;
1935
+			}
1936
+			$this->db->free();
1937
+			return $num;
1938
+		}
1939
+		else
1940
+		{
1941
+			$this->error=$this->db->lasterror();
1942
+			return -1;
1943
+		}
1944
+
1945
+	}
1946
+
1947
+	/**
1948
+	 * Returns a array with expeditions lines number
1949
+	 *
1950
+	 * @return	int		Nb of shipments
1951
+	 *
1952
+	 * TODO deprecate, move to Shipping class
1953
+	 */
1954
+	function nb_expedition()
1955
+	{
1956
+		$sql = 'SELECT count(*)';
1957
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
1958
+		$sql.= ', '.MAIN_DB_PREFIX.'element_element as el';
1959
+		$sql.= ' WHERE el.fk_source = '.$this->id;
1960
+		$sql.= " AND el.fk_target = e.rowid";
1961
+		$sql.= " AND el.targettype = 'shipping'";
1962
+
1963
+		$resql = $this->db->query($sql);
1964
+		if ($resql)
1965
+		{
1966
+			$row = $this->db->fetch_row($resql);
1967
+			return $row[0];
1968
+		}
1969
+		else dol_print_error($this->db);
1970
+	}
1971
+
1972
+	/**
1973
+	 *	Return a array with the pending stock by product
1974
+	 *
1975
+	 *	@param      int		$filtre_statut      Filtre sur statut
1976
+	 *	@return     int                 		0 si OK, <0 si KO
1977
+	 *
1978
+	 *	TODO		FONCTION NON FINIE A FINIR
1979
+	 */
1980
+	function stock_array($filtre_statut=self::STATUS_CANCELED)
1981
+	{
1982
+		$this->stocks = array();
1983
+
1984
+		// Tableau des id de produit de la commande
1985
+		$array_of_product=array();
1986
+
1987
+		// Recherche total en stock pour chaque produit
1988
+		// TODO $array_of_product est défini vide juste au dessus !!
1989
+		if (count($array_of_product))
1990
+		{
1991
+			$sql = "SELECT fk_product, sum(ps.reel) as total";
1992
+			$sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
1993
+			$sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")";
1994
+			$sql.= ' GROUP BY fk_product ';
1995
+			$result = $this->db->query($sql);
1996
+			if ($result)
1997
+			{
1998
+				$num = $this->db->num_rows($result);
1999
+				$i = 0;
2000
+				while ($i < $num)
2001
+				{
2002
+					$obj = $this->db->fetch_object($result);
2003
+					$this->stocks[$obj->fk_product] = $obj->total;
2004
+					$i++;
2005
+				}
2006
+				$this->db->free();
2007
+			}
2008
+		}
2009
+		return 0;
2010
+	}
2011
+
2012
+	/**
2013
+	 *  Delete an order line
2014
+	 *
2015
+	 *	@param      User	$user		User object
2016
+	 *  @param      int		$lineid		Id of line to delete
2017
+	 *  @return     int        		 	>0 if OK, 0 if nothing to do, <0 if KO
2018
+	 */
2019
+	function deleteline($user=null, $lineid=0)
2020
+	{
2021
+
2022
+		if ($this->statut == self::STATUS_DRAFT)
2023
+		{
2024
+			$this->db->begin();
2025
+
2026
+			$sql = "SELECT fk_product, qty";
2027
+			$sql.= " FROM ".MAIN_DB_PREFIX."commandedet";
2028
+			$sql.= " WHERE rowid = ".$lineid;
2029
+
2030
+			$result = $this->db->query($sql);
2031
+			if ($result)
2032
+			{
2033
+				$obj = $this->db->fetch_object($result);
2034
+
2035
+				if ($obj)
2036
+				{
2037
+					$product = new Product($this->db);
2038
+					$product->id = $obj->fk_product;
2039
+
2040
+					// Delete line
2041
+					$line = new OrderLine($this->db);
2042
+
2043
+					// For triggers
2044
+					$line->fetch($lineid);
2045
+
2046
+					if ($line->delete($user) > 0)
2047
+					{
2048
+						$result=$this->update_price(1);
2049
+
2050
+						if ($result > 0)
2051
+						{
2052
+							$this->db->commit();
2053
+							return 1;
2054
+						}
2055
+						else
2056
+						{
2057
+							$this->db->rollback();
2058
+							$this->error=$this->db->lasterror();
2059
+							return -1;
2060
+						}
2061
+					}
2062
+					else
2063
+					{
2064
+						$this->db->rollback();
2065
+						$this->error=$line->error;
2066
+						return -1;
2067
+					}
2068
+				}
2069
+				else
2070
+				{
2071
+					$this->db->rollback();
2072
+					return 0;
2073
+				}
2074
+			}
2075
+			else
2076
+			{
2077
+				$this->db->rollback();
2078
+				$this->error=$this->db->lasterror();
2079
+				return -1;
2080
+			}
2081
+		}
2082
+		else
2083
+		{
2084
+			return -1;
2085
+		}
2086
+	}
2087
+
2088
+	/**
2089
+	 * 	Applique une remise relative
2090
+	 *
2091
+	 * 	@param     	User		$user		User qui positionne la remise
2092
+	 * 	@param     	float		$remise		Discount (percent)
2093
+	 * 	@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2094
+	 *	@return		int 					<0 if KO, >0 if OK
2095
+	 */
2096
+	function set_remise($user, $remise, $notrigger=0)
2097
+	{
2098
+		$remise=trim($remise)?trim($remise):0;
2099
+
2100
+		if ($user->rights->commande->creer)
2101
+		{
2102
+			$error=0;
2103
+
2104
+			$this->db->begin();
2105
+
2106
+			$remise=price2num($remise);
2107
+
2108
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2109
+			$sql.= ' SET remise_percent = '.$remise;
2110
+			$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2111
+
2112
+			dol_syslog(__METHOD__, LOG_DEBUG);
2113
+			$resql=$this->db->query($sql);
2114
+			if (!$resql)
2115
+			{
2116
+				$this->errors[]=$this->db->error();
2117
+				$error++;
2118
+			}
2119
+
2120
+			if (! $error)
2121
+			{
2122
+				$this->oldcopy= clone $this;
2123
+				$this->remise_percent = $remise;
2124
+				$this->update_price(1);
2125
+			}
2126
+
2127
+			if (! $notrigger && empty($error))
2128
+			{
2129
+				// Call trigger
2130
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2131
+				if ($result < 0) $error++;
2132
+				// End call triggers
2133
+			}
2134
+
2135
+			if (! $error)
2136
+			{
2137
+				$this->db->commit();
2138
+				return 1;
2139
+			}
2140
+			else
2141
+			{
2142
+				foreach($this->errors as $errmsg)
2143
+				{
2144
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2145
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2146
+				}
2147
+				$this->db->rollback();
2148
+				return -1*$error;
2149
+			}
2150
+		}
2151
+	}
2152
+
2153
+
2154
+	/**
2155
+	 * 		Applique une remise absolue
2156
+	 *
2157
+	 * 		@param     	User		$user 		User qui positionne la remise
2158
+	 * 		@param     	float		$remise		Discount
2159
+	 * 		@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2160
+	 *		@return		int 					<0 if KO, >0 if OK
2161
+	 */
2162
+	function set_remise_absolue($user, $remise, $notrigger=0)
2163
+	{
2164
+		$remise=trim($remise)?trim($remise):0;
2165
+
2166
+		if ($user->rights->commande->creer)
2167
+		{
2168
+			$error=0;
2169
+
2170
+			$this->db->begin();
2171
+
2172
+			$remise=price2num($remise);
2173
+
2174
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2175
+			$sql.= ' SET remise_absolue = '.$remise;
2176
+			$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2177
+
2178
+			dol_syslog(__METHOD__, LOG_DEBUG);
2179
+			$resql=$this->db->query($sql);
2180
+			if (!$resql)
2181
+			{
2182
+				$this->errors[]=$this->db->error();
2183
+				$error++;
2184
+			}
2185
+
2186
+			if (! $error)
2187
+			{
2188
+				$this->oldcopy= clone $this;
2189
+				$this->remise_absolue = $remise;
2190
+				$this->update_price(1);
2191
+			}
2192
+
2193
+			if (! $notrigger && empty($error))
2194
+			{
2195
+				// Call trigger
2196
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2197
+				if ($result < 0) $error++;
2198
+				// End call triggers
2199
+			}
2200
+
2201
+			if (! $error)
2202
+			{
2203
+				$this->db->commit();
2204
+				return 1;
2205
+			}
2206
+			else
2207
+			{
2208
+				foreach($this->errors as $errmsg)
2209
+				{
2210
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2211
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2212
+				}
2213
+				$this->db->rollback();
2214
+				return -1*$error;
2215
+			}
2216
+		}
2217
+	}
2218
+
2219
+
2220
+	/**
2221
+	 *	Set the order date
2222
+	 *
2223
+	 *	@param      User	$user       Object user making change
2224
+	 *	@param      int		$date		Date
2225
+	 * 	@param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2226
+	 *	@return     int         		<0 if KO, >0 if OK
2227
+	 */
2228
+	function set_date($user, $date, $notrigger=0)
2229
+	{
2230
+		if ($user->rights->commande->creer)
2231
+		{
2232
+			$error=0;
2233
+
2234
+			$this->db->begin();
2235
+
2236
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2237
+			$sql.= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2238
+			$sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2239
+
2240
+			dol_syslog(__METHOD__, LOG_DEBUG);
2241
+			$resql=$this->db->query($sql);
2242
+			if (!$resql)
2243
+			{
2244
+				$this->errors[]=$this->db->error();
2245
+				$error++;
2246
+			}
2247
+
2248
+			if (! $error)
2249
+			{
2250
+				$this->oldcopy= clone $this;
2251
+				$this->date = $date;
2252
+			}
2253
+
2254
+			if (! $notrigger && empty($error))
2255
+			{
2256
+				// Call trigger
2257
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2258
+				if ($result < 0) $error++;
2259
+				// End call triggers
2260
+			}
2261
+
2262
+			if (! $error)
2263
+			{
2264
+				$this->db->commit();
2265
+				return 1;
2266
+			}
2267
+			else
2268
+			{
2269
+				foreach($this->errors as $errmsg)
2270
+				{
2271
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2272
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2273
+				}
2274
+				$this->db->rollback();
2275
+				return -1*$error;
2276
+			}
2277
+		}
2278
+		else
2279
+		{
2280
+			return -2;
2281
+		}
2282
+	}
2283
+
2284
+	/**
2285
+	 *	Set the planned delivery date
2286
+	 *
2287
+	 *	@param      User	$user        		Objet utilisateur qui modifie
2288
+	 *	@param      int		$date_livraison     Date de livraison
2289
+	 *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2290
+	 *	@return     int         				<0 si ko, >0 si ok
2291
+	 */
2292
+	function set_date_livraison($user, $date_livraison, $notrigger=0)
2293
+	{
2294
+		if ($user->rights->commande->creer)
2295
+		{
2296
+			$error=0;
2297
+
2298
+			$this->db->begin();
2299
+
2300
+			$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2301
+			$sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2302
+			$sql.= " WHERE rowid = ".$this->id;
2303
+
2304
+			dol_syslog(__METHOD__, LOG_DEBUG);
2305
+			$resql=$this->db->query($sql);
2306
+			if (!$resql)
2307
+			{
2308
+				$this->errors[]=$this->db->error();
2309
+				$error++;
2310
+			}
2311
+
2312
+			if (! $error)
2313
+			{
2314
+				$this->oldcopy= clone $this;
2315
+				$this->date_livraison = $date_livraison;
2316
+			}
2317
+
2318
+			if (! $notrigger && empty($error))
2319
+			{
2320
+				// Call trigger
2321
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2322
+				if ($result < 0) $error++;
2323
+				// End call triggers
2324
+			}
2325
+
2326
+			if (! $error)
2327
+			{
2328
+				$this->db->commit();
2329
+				return 1;
2330
+			}
2331
+			else
2332
+			{
2333
+				foreach($this->errors as $errmsg)
2334
+				{
2335
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2336
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2337
+				}
2338
+				$this->db->rollback();
2339
+				return -1*$error;
2340
+			}
2341
+		}
2342
+		else
2343
+		{
2344
+			return -2;
2345
+		}
2346
+	}
2347
+
2348
+	/**
2349
+	 *  Return list of orders (eventuelly filtered on a user) into an array
2350
+	 *
2351
+	 *  @param		int		$shortlist		0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
2352
+	 *  @param      int		$draft      	0=not draft, 1=draft
2353
+	 *  @param      User	$excluser      	Objet user to exclude
2354
+	 *  @param    	int		$socid			Id third pary
2355
+	 *  @param    	int		$limit			For pagination
2356
+	 *  @param    	int		$offset			For pagination
2357
+	 *  @param    	string	$sortfield		Sort criteria
2358
+	 *  @param    	string	$sortorder		Sort order
2359
+	 *  @return     int             		-1 if KO, array with result if OK
2360
+	 */
2361
+	function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
2362
+	{
2363
+		global $user;
2364
+
2365
+		$ga = array();
2366
+
2367
+		$sql = "SELECT s.rowid, s.nom as name, s.client,";
2368
+		$sql.= " c.rowid as cid, c.ref";
2369
+		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2370
+		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2371
+		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2372
+		$sql.= " WHERE c.entity IN (".getEntity('commande').")";
2373
+		$sql.= " AND c.fk_soc = s.rowid";
2374
+		if (! $user->rights->societe->client->voir && ! $socid) //restriction
2375
+		{
2376
+			$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2377
+		}
2378
+		if ($socid) $sql.= " AND s.rowid = ".$socid;
2379
+		if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2380
+		if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id;
2381
+		$sql.= $this->db->order($sortfield,$sortorder);
2382
+		$sql.= $this->db->plimit($limit,$offset);
2383
+
2384
+		$result=$this->db->query($sql);
2385
+		if ($result)
2386
+		{
2387
+			$numc = $this->db->num_rows($result);
2388
+			if ($numc)
2389
+			{
2390
+				$i = 0;
2391
+				while ($i < $numc)
2392
+				{
2393
+					$obj = $this->db->fetch_object($result);
2394
+
2395
+					if ($shortlist == 1)
2396
+					{
2397
+						$ga[$obj->cid] = $obj->ref;
2398
+					}
2399
+					else if ($shortlist == 2)
2400
+					{
2401
+						$ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2402
+					}
2403
+					else
2404
+					{
2405
+						$ga[$i]['id']	= $obj->cid;
2406
+						$ga[$i]['ref'] 	= $obj->ref;
2407
+						$ga[$i]['name'] = $obj->name;
2408
+					}
2409
+					$i++;
2410
+				}
2411
+			}
2412
+			return $ga;
2413
+		}
2414
+		else
2415
+		{
2416
+			dol_print_error($this->db);
2417
+			return -1;
2418
+		}
2419
+	}
2420
+
2421
+	/**
2422
+	 *	Update delivery delay
2423
+	 *
2424
+	 *	@param      int		$availability_id	Id du nouveau mode
2425
+	 *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2426
+	 *	@return     int         				>0 if OK, <0 if KO
2427
+	 */
2428
+	function availability($availability_id, $notrigger=0)
2429
+	{
2430
+		global $user;
2431
+
2432
+		dol_syslog('Commande::availability('.$availability_id.')');
2433
+		if ($this->statut >= self::STATUS_DRAFT)
2434
+		{
2435
+			$error=0;
2436
+
2437
+			$this->db->begin();
2438
+
2439
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2440
+			$sql .= ' SET fk_availability = '.$availability_id;
2441
+			$sql .= ' WHERE rowid='.$this->id;
2442
+
2443
+			dol_syslog(__METHOD__, LOG_DEBUG);
2444
+			$resql=$this->db->query($sql);
2445
+			if (!$resql)
2446
+			{
2447
+				$this->errors[]=$this->db->error();
2448
+				$error++;
2449
+			}
2450
+
2451
+			if (! $error)
2452
+			{
2453
+				$this->oldcopy= clone $this;
2454
+				$this->availability_id = $availability_id;
2455
+			}
2456
+
2457
+			if (! $notrigger && empty($error))
2458
+			{
2459
+				// Call trigger
2460
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2461
+				if ($result < 0) $error++;
2462
+				// End call triggers
2463
+			}
2464
+
2465
+			if (! $error)
2466
+			{
2467
+				$this->db->commit();
2468
+				return 1;
2469
+			}
2470
+			else
2471
+			{
2472
+				foreach($this->errors as $errmsg)
2473
+				{
2474
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2475
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2476
+				}
2477
+				$this->db->rollback();
2478
+				return -1*$error;
2479
+			}
2480
+		}
2481
+		else
2482
+		{
2483
+			$error_str='Command status do not meet requirement '.$this->statut;
2484
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
2485
+			$this->error=$error_str;
2486
+			$this->errors[]= $this->error;
2487
+			return -2;
2488
+		}
2489
+	}
2490
+
2491
+	/**
2492
+	 *	Update order demand_reason
2493
+	 *
2494
+	 *  @param      int		$demand_reason_id	Id of new demand
2495
+	 *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2496
+	 *  @return     int        			 		>0 if ok, <0 if ko
2497
+	 */
2498
+	function demand_reason($demand_reason_id, $notrigger=0)
2499
+	{
2500
+		global $user;
2501
+
2502
+		dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2503
+		if ($this->statut >= self::STATUS_DRAFT)
2504
+		{
2505
+			$error=0;
2506
+
2507
+			$this->db->begin();
2508
+
2509
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2510
+			$sql .= ' SET fk_input_reason = '.$demand_reason_id;
2511
+			$sql .= ' WHERE rowid='.$this->id;
2512
+
2513
+			dol_syslog(__METHOD__, LOG_DEBUG);
2514
+			$resql=$this->db->query($sql);
2515
+			if (!$resql)
2516
+			{
2517
+				$this->errors[]=$this->db->error();
2518
+				$error++;
2519
+			}
2520
+
2521
+			if (! $error)
2522
+			{
2523
+				$this->oldcopy= clone $this;
2524
+				$this->demand_reason_id = $demand_reason_id;
2525
+			}
2526
+
2527
+			if (! $notrigger && empty($error))
2528
+			{
2529
+				// Call trigger
2530
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2531
+				if ($result < 0) $error++;
2532
+				// End call triggers
2533
+			}
2534
+
2535
+			if (! $error)
2536
+			{
2537
+				$this->db->commit();
2538
+				return 1;
2539
+			}
2540
+			else
2541
+			{
2542
+				foreach($this->errors as $errmsg)
2543
+				{
2544
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2545
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2546
+				}
2547
+				$this->db->rollback();
2548
+				return -1*$error;
2549
+			}
2550
+		}
2551
+		else
2552
+		{
2553
+			$error_str='order status do not meet requirement '.$this->statut;
2554
+			dol_syslog(__METHOD__.$error_str, LOG_ERR);
2555
+			$this->error=$error_str;
2556
+			$this->errors[]= $this->error;
2557
+			return -2;
2558
+		}
2559
+	}
2560
+
2561
+	/**
2562
+	 *	Set customer ref
2563
+	 *
2564
+	 *	@param      User	$user           User that make change
2565
+	 *	@param      string	$ref_client     Customer ref
2566
+	 *  @param     	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2567
+	 *	@return     int             		<0 if KO, >0 if OK
2568
+	 */
2569
+	function set_ref_client($user, $ref_client, $notrigger=0)
2570
+	{
2571
+		if ($user->rights->commande->creer)
2572
+		{
2573
+			$error=0;
2574
+
2575
+			$this->db->begin();
2576
+
2577
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET';
2578
+			$sql.= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2579
+			$sql.= ' WHERE rowid = '.$this->id;
2580
+
2581
+			dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2582
+			$resql=$this->db->query($sql);
2583
+			if (!$resql)
2584
+			{
2585
+				$this->errors[]=$this->db->error();
2586
+				$error++;
2587
+			}
2588
+
2589
+			if (! $error)
2590
+			{
2591
+				$this->oldcopy= clone $this;
2592
+				$this->ref_client = $ref_client;
2593
+			}
2594
+
2595
+			if (! $notrigger && empty($error))
2596
+			{
2597
+				// Call trigger
2598
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
2599
+				if ($result < 0) $error++;
2600
+				// End call triggers
2601
+			}
2602
+			if (! $error)
2603
+			{
2604
+				$this->db->commit();
2605
+				return 1;
2606
+			}
2607
+			else
2608
+			{
2609
+				foreach($this->errors as $errmsg)
2610
+				{
2611
+					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2612
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2613
+				}
2614
+				$this->db->rollback();
2615
+				return -1*$error;
2616
+			}
2617
+		}
2618
+		else
2619
+		{
2620
+			return -1;
2621
+		}
2622
+	}
2623
+
2624
+	/**
2625
+	 * Classify the order as invoiced
2626
+	 *
2627
+	 * @param	User    $user       Object user making the change
2628
+	 * @param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2629
+	 * @return	int                 <0 if KO, >0 if OK
2630
+	 */
2631
+	function classifyBilled(User $user, $notrigger=0)
2632
+	{
2633
+		$error = 0;
2634
+
2635
+		$this->db->begin();
2636
+
2637
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
2638
+		$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2639
+
2640
+		dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
2641
+		if ($this->db->query($sql))
2642
+		{
2643
+
2644
+			if (! $error)
2645
+			{
2646
+				$this->oldcopy= clone $this;
2647
+				$this->facturee=1; // deprecated
2648
+				$this->billed=1;
2649
+			}
2650
+
2651
+			if (! $notrigger && empty($error))
2652
+			{
2653
+				// Call trigger
2654
+				$result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user);
2655
+				if ($result < 0) $error++;
2656
+				// End call triggers
2657
+			}
2658
+
2659
+			if (! $error)
2660
+			{
2661
+				$this->db->commit();
2662
+				return 1;
2663
+			}
2664
+			else
2665
+			{
2666
+				foreach($this->errors as $errmsg)
2667
+				{
2668
+					dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
2669
+					$this->error.=($this->error?', '.$errmsg:$errmsg);
2670
+				}
2671
+				$this->db->rollback();
2672
+				return -1*$error;
2673
+			}
2674
+		}
2675
+		else
2676
+		{
2677
+			$this->error=$this->db->error();
2678
+			$this->db->rollback();
2679
+			return -1;
2680
+		}
2681
+	}
2682
+
2683
+	/**
2684
+	 * Classify the order as invoiced
2685
+	 *
2686
+	 * @return     int     <0 if ko, >0 if ok
2687
+	 * @deprecated
2688
+	 * @see classifyBilled()
2689
+	 */
2690
+	function classer_facturee()
2691
+	{
2692
+		global $user;
2693
+		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
2694
+
2695
+		return $this->classifyBilled($user);
2696
+	}
2623 2697
 
2624 2698
 	/**
2625
-	 * Classify the order as invoiced
2699
+	 * Classify the order as not invoiced
2626 2700
 	 *
2627
-	 * @param	User    $user       Object user making the change
2628
-	 * @param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2629
-	 * @return	int                 <0 if KO, >0 if OK
2701
+	 * @return     int     <0 if ko, >0 if ok
2630 2702
 	 */
2631
-	function classifyBilled(User $user, $notrigger=0)
2703
+	function classifyUnBilled()
2632 2704
 	{
2633
-        $error = 0;
2705
+		global $conf, $user, $langs;
2706
+		$error = 0;
2634 2707
 
2635 2708
 		$this->db->begin();
2636 2709
 
2637
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
2710
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0';
2638 2711
 		$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2639 2712
 
2640
-		dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
2713
+		dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
2641 2714
 		if ($this->db->query($sql))
2642 2715
 		{
2643
-
2644 2716
 			if (! $error)
2645 2717
 			{
2646 2718
 				$this->oldcopy= clone $this;
@@ -2648,16 +2720,16 @@  discard block
 block discarded – undo
2648 2720
 				$this->billed=1;
2649 2721
 			}
2650 2722
 
2651
-			if (! $notrigger && empty($error))
2652
-			{
2653
-            	// Call trigger
2654
-            	$result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user);
2655
-            	if ($result < 0) $error++;
2656
-            	// End call triggers
2657
-			}
2723
+			// Call trigger
2724
+			$result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED',$user);
2725
+			if ($result < 0) $error++;
2726
+			// End call triggers
2658 2727
 
2659 2728
 			if (! $error)
2660 2729
 			{
2730
+				$this->facturee=0; // deprecated
2731
+				$this->billed=0;
2732
+
2661 2733
 				$this->db->commit();
2662 2734
 				return 1;
2663 2735
 			}
@@ -2665,7 +2737,7 @@  discard block
 block discarded – undo
2665 2737
 			{
2666 2738
 				foreach($this->errors as $errmsg)
2667 2739
 				{
2668
-					dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
2740
+					dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
2669 2741
 					$this->error.=($this->error?', '.$errmsg:$errmsg);
2670 2742
 				}
2671 2743
 				$this->db->rollback();
@@ -2675,175 +2747,103 @@  discard block
 block discarded – undo
2675 2747
 		else
2676 2748
 		{
2677 2749
 			$this->error=$this->db->error();
2678
-            $this->db->rollback();
2750
+			$this->db->rollback();
2679 2751
 			return -1;
2680 2752
 		}
2681 2753
 	}
2682 2754
 
2755
+
2683 2756
 	/**
2684
-	 * Classify the order as invoiced
2757
+	 *  Update a line in database
2685 2758
 	 *
2686
-	 * @return     int     <0 if ko, >0 if ok
2687
-	 * @deprecated
2688
-	 * @see classifyBilled()
2759
+	 *  @param    	int				$rowid            	Id of line to update
2760
+	 *  @param    	string			$desc             	Description of line
2761
+	 *  @param    	float			$pu               	Unit price
2762
+	 *  @param    	float			$qty              	Quantity
2763
+	 *  @param    	float			$remise_percent   	Percent of discount
2764
+	 *  @param    	float			$txtva           	Taux TVA
2765
+	 * 	@param		float			$txlocaltax1		Local tax 1 rate
2766
+	 *  @param		float			$txlocaltax2		Local tax 2 rate
2767
+	 *  @param    	string			$price_base_type	HT or TTC
2768
+	 *  @param    	int				$info_bits        	Miscellaneous informations on line
2769
+	 *  @param    	int				$date_start        	Start date of the line
2770
+	 *  @param    	int				$date_end          	End date of the line
2771
+	 * 	@param		int				$type				Type of line (0=product, 1=service)
2772
+	 * 	@param		int				$fk_parent_line		Id of parent line (0 in most cases, used by modules adding sublevels into lines).
2773
+	 * 	@param		int				$skip_update_total	Keep fields total_xxx to 0 (used for special lines by some modules)
2774
+	 *  @param		int				$fk_fournprice		Id of origin supplier price
2775
+	 *  @param		int				$pa_ht				Price (without tax) of product when it was bought
2776
+	 *  @param		string			$label				Label
2777
+	 *  @param		int				$special_code		Special code (also used by externals modules!)
2778
+	 *  @param		array			$array_options		extrafields array
2779
+	 * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
2780
+	 *  @param		double			$pu_ht_devise		Amount in currency
2781
+	 * 	@param		int				$notrigger			disable line update trigger
2782
+	 *  @return   	int              					< 0 if KO, > 0 if OK
2689 2783
 	 */
2690
-	function classer_facturee()
2784
+	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0,$txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
2691 2785
 	{
2692
-	    global $user;
2693
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
2786
+		global $conf, $mysoc, $langs, $user;
2694 2787
 
2695
-		return $this->classifyBilled($user);
2696
-	}
2788
+		dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code");
2789
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2697 2790
 
2698
-	/**
2699
-	 * Classify the order as not invoiced
2700
-	 *
2701
-	 * @return     int     <0 if ko, >0 if ok
2702
-	 */
2703
-	function classifyUnBilled()
2704
-	{
2705
-	    global $conf, $user, $langs;
2706
-	    $error = 0;
2707
-
2708
-	    $this->db->begin();
2709
-
2710
-	    $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0';
2711
-	    $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2712
-
2713
-	    dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
2714
-	    if ($this->db->query($sql))
2715
-	    {
2716
-	    	if (! $error)
2717
-	    	{
2718
-	    		$this->oldcopy= clone $this;
2719
-	    		$this->facturee=1; // deprecated
2720
-	    		$this->billed=1;
2721
-	    	}
2722
-
2723
-	        // Call trigger
2724
-	        $result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED',$user);
2725
-	        if ($result < 0) $error++;
2726
-	        // End call triggers
2727
-
2728
-	        if (! $error)
2729
-	        {
2730
-	            $this->facturee=0; // deprecated
2731
-	            $this->billed=0;
2732
-
2733
-	            $this->db->commit();
2734
-	            return 1;
2735
-	        }
2736
-	        else
2737
-	        {
2738
-	            foreach($this->errors as $errmsg)
2739
-	            {
2740
-	                dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
2741
-	                $this->error.=($this->error?', '.$errmsg:$errmsg);
2742
-	            }
2743
-	            $this->db->rollback();
2744
-	            return -1*$error;
2745
-	        }
2746
-	    }
2747
-	    else
2748
-	    {
2749
-	        $this->error=$this->db->error();
2750
-	        $this->db->rollback();
2751
-	        return -1;
2752
-	    }
2753
-	}
2791
+		if (! empty($this->brouillon))
2792
+		{
2793
+			$this->db->begin();
2794
+
2795
+			// Clean parameters
2796
+			if (empty($qty)) $qty=0;
2797
+			if (empty($info_bits)) $info_bits=0;
2798
+			if (empty($txtva)) $txtva=0;
2799
+			if (empty($txlocaltax1)) $txlocaltax1=0;
2800
+			if (empty($txlocaltax2)) $txlocaltax2=0;
2801
+			if (empty($remise)) $remise=0;
2802
+			if (empty($remise_percent)) $remise_percent=0;
2803
+			if (empty($special_code) || $special_code == 3) $special_code=0;
2804
+
2805
+			$remise_percent=price2num($remise_percent);
2806
+			$qty=price2num($qty);
2807
+			$pu = price2num($pu);
2808
+	  		$pa_ht=price2num($pa_ht);
2809
+			$txtva=price2num($txtva);
2810
+			$txlocaltax1=price2num($txlocaltax1);
2811
+			$txlocaltax2=price2num($txlocaltax2);
2754 2812
 
2813
+			// Calcul du total TTC et de la TVA pour la ligne a partir de
2814
+			// qty, pu, remise_percent et txtva
2815
+			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2816
+			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2755 2817
 
2756
-    /**
2757
-     *  Update a line in database
2758
-     *
2759
-     *  @param    	int				$rowid            	Id of line to update
2760
-     *  @param    	string			$desc             	Description of line
2761
-     *  @param    	float			$pu               	Unit price
2762
-     *  @param    	float			$qty              	Quantity
2763
-     *  @param    	float			$remise_percent   	Percent of discount
2764
-     *  @param    	float			$txtva           	Taux TVA
2765
-     * 	@param		float			$txlocaltax1		Local tax 1 rate
2766
-     *  @param		float			$txlocaltax2		Local tax 2 rate
2767
-     *  @param    	string			$price_base_type	HT or TTC
2768
-     *  @param    	int				$info_bits        	Miscellaneous informations on line
2769
-     *  @param    	int				$date_start        	Start date of the line
2770
-     *  @param    	int				$date_end          	End date of the line
2771
-     * 	@param		int				$type				Type of line (0=product, 1=service)
2772
-     * 	@param		int				$fk_parent_line		Id of parent line (0 in most cases, used by modules adding sublevels into lines).
2773
-     * 	@param		int				$skip_update_total	Keep fields total_xxx to 0 (used for special lines by some modules)
2774
-     *  @param		int				$fk_fournprice		Id of origin supplier price
2775
-     *  @param		int				$pa_ht				Price (without tax) of product when it was bought
2776
-     *  @param		string			$label				Label
2777
-     *  @param		int				$special_code		Special code (also used by externals modules!)
2778
-	 *  @param		array			$array_options		extrafields array
2779
-     * 	@param 		string			$fk_unit 			Code of the unit to use. Null to use the default one
2780
-	 *  @param		double			$pu_ht_devise		Amount in currency
2781
-     * 	@param		int				$notrigger			disable line update trigger
2782
-     *  @return   	int              					< 0 if KO, > 0 if OK
2783
-     */
2784
-	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0,$txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
2785
-    {
2786
-        global $conf, $mysoc, $langs, $user;
2787
-
2788
-        dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code");
2789
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2790
-
2791
-        if (! empty($this->brouillon))
2792
-        {
2793
-            $this->db->begin();
2794
-
2795
-            // Clean parameters
2796
-            if (empty($qty)) $qty=0;
2797
-            if (empty($info_bits)) $info_bits=0;
2798
-            if (empty($txtva)) $txtva=0;
2799
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2800
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2801
-            if (empty($remise)) $remise=0;
2802
-            if (empty($remise_percent)) $remise_percent=0;
2803
-            if (empty($special_code) || $special_code == 3) $special_code=0;
2804
-
2805
-            $remise_percent=price2num($remise_percent);
2806
-            $qty=price2num($qty);
2807
-            $pu = price2num($pu);
2808
-      		$pa_ht=price2num($pa_ht);
2809
-            $txtva=price2num($txtva);
2810
-            $txlocaltax1=price2num($txlocaltax1);
2811
-            $txlocaltax2=price2num($txlocaltax2);
2812
-
2813
-            // Calcul du total TTC et de la TVA pour la ligne a partir de
2814
-            // qty, pu, remise_percent et txtva
2815
-            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2816
-            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2817
-
2818
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
2819
-
2820
-       		// Clean vat code
2821
-    		$vat_src_code='';
2822
-    		if (preg_match('/\((.*)\)/', $txtva, $reg))
2823
-    		{
2824
-    		    $vat_src_code = $reg[1];
2825
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2826
-    		}
2827
-
2828
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2829
-
2830
-            $total_ht  = $tabprice[0];
2831
-            $total_tva = $tabprice[1];
2832
-            $total_ttc = $tabprice[2];
2833
-            $total_localtax1 = $tabprice[9];
2834
-            $total_localtax2 = $tabprice[10];
2818
+			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
2819
+
2820
+	   		// Clean vat code
2821
+			$vat_src_code='';
2822
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
2823
+			{
2824
+				$vat_src_code = $reg[1];
2825
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2826
+			}
2827
+
2828
+			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2829
+
2830
+			$total_ht  = $tabprice[0];
2831
+			$total_tva = $tabprice[1];
2832
+			$total_ttc = $tabprice[2];
2833
+			$total_localtax1 = $tabprice[9];
2834
+			$total_localtax2 = $tabprice[10];
2835 2835
 			$pu_ht  = $tabprice[3];
2836 2836
 			$pu_tva = $tabprice[4];
2837 2837
 			$pu_ttc = $tabprice[5];
2838 2838
 
2839 2839
 			// MultiCurrency
2840 2840
 			$multicurrency_total_ht  = $tabprice[16];
2841
-            $multicurrency_total_tva = $tabprice[17];
2842
-            $multicurrency_total_ttc = $tabprice[18];
2841
+			$multicurrency_total_tva = $tabprice[17];
2842
+			$multicurrency_total_ttc = $tabprice[18];
2843 2843
 			$pu_ht_devise = $tabprice[19];
2844 2844
 
2845
-            // Anciens indicateurs: $price, $subprice, $remise (a ne plus utiliser)
2846
-            $price = $pu_ht;
2845
+			// Anciens indicateurs: $price, $subprice, $remise (a ne plus utiliser)
2846
+			$price = $pu_ht;
2847 2847
 			if ($price_base_type == 'TTC')
2848 2848
 			{
2849 2849
 				$subprice = $pu_ttc;
@@ -2852,72 +2852,72 @@  discard block
 block discarded – undo
2852 2852
 			{
2853 2853
 				$subprice = $pu_ht;
2854 2854
 			}
2855
-            $remise = 0;
2856
-            if ($remise_percent > 0)
2857
-            {
2858
-                $remise = round(($pu * $remise_percent / 100),2);
2859
-                $price = ($pu - $remise);
2860
-            }
2861
-
2862
-            //Fetch current line from the database and then clone the object and set it in $oldline property
2863
-            $line = new OrderLine($this->db);
2864
-            $line->fetch($rowid);
2865
-
2866
-            if (!empty($line->fk_product))
2867
-            {
2868
-                $product=new Product($this->db);
2869
-                $result=$product->fetch($line->fk_product);
2870
-                $product_type=$product->type;
2871
-
2872
-                if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
2873
-                {
2874
-                    $langs->load("errors");
2875
-                    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
2876
-                    dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
2877
-                    $this->db->rollback();
2878
-                    return self::STOCK_NOT_ENOUGH_FOR_ORDER;
2879
-                }
2880
-            }
2881
-
2882
-            $staticline = clone $line;
2883
-
2884
-            $line->oldline = $staticline;
2885
-            $this->line = $line;
2886
-            $this->line->context = $this->context;
2887
-
2888
-            // Reorder if fk_parent_line change
2889
-            if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2890
-            {
2891
-            	$rangmax = $this->line_max($fk_parent_line);
2892
-            	$this->line->rang = $rangmax + 1;
2893
-            }
2894
-
2895
-            $this->line->rowid=$rowid;
2896
-            $this->line->label=$label;
2897
-            $this->line->desc=$desc;
2898
-            $this->line->qty=$qty;
2899
-
2900
-            $this->line->vat_src_code	= $vat_src_code;
2901
-            $this->line->tva_tx         = $txtva;
2902
-            $this->line->localtax1_tx   = $txlocaltax1;
2903
-            $this->line->localtax2_tx   = $txlocaltax2;
2855
+			$remise = 0;
2856
+			if ($remise_percent > 0)
2857
+			{
2858
+				$remise = round(($pu * $remise_percent / 100),2);
2859
+				$price = ($pu - $remise);
2860
+			}
2861
+
2862
+			//Fetch current line from the database and then clone the object and set it in $oldline property
2863
+			$line = new OrderLine($this->db);
2864
+			$line->fetch($rowid);
2865
+
2866
+			if (!empty($line->fk_product))
2867
+			{
2868
+				$product=new Product($this->db);
2869
+				$result=$product->fetch($line->fk_product);
2870
+				$product_type=$product->type;
2871
+
2872
+				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
2873
+				{
2874
+					$langs->load("errors");
2875
+					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
2876
+					dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
2877
+					$this->db->rollback();
2878
+					return self::STOCK_NOT_ENOUGH_FOR_ORDER;
2879
+				}
2880
+			}
2881
+
2882
+			$staticline = clone $line;
2883
+
2884
+			$line->oldline = $staticline;
2885
+			$this->line = $line;
2886
+			$this->line->context = $this->context;
2887
+
2888
+			// Reorder if fk_parent_line change
2889
+			if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2890
+			{
2891
+				$rangmax = $this->line_max($fk_parent_line);
2892
+				$this->line->rang = $rangmax + 1;
2893
+			}
2894
+
2895
+			$this->line->rowid=$rowid;
2896
+			$this->line->label=$label;
2897
+			$this->line->desc=$desc;
2898
+			$this->line->qty=$qty;
2899
+
2900
+			$this->line->vat_src_code	= $vat_src_code;
2901
+			$this->line->tva_tx         = $txtva;
2902
+			$this->line->localtax1_tx   = $txlocaltax1;
2903
+			$this->line->localtax2_tx   = $txlocaltax2;
2904 2904
 			$this->line->localtax1_type = $localtaxes_type[0];
2905 2905
 			$this->line->localtax2_type = $localtaxes_type[2];
2906
-            $this->line->remise_percent = $remise_percent;
2907
-            $this->line->subprice       = $subprice;
2908
-            $this->line->info_bits      = $info_bits;
2909
-            $this->line->special_code   = $special_code;
2910
-            $this->line->total_ht       = $total_ht;
2911
-            $this->line->total_tva      = $total_tva;
2912
-            $this->line->total_localtax1= $total_localtax1;
2913
-            $this->line->total_localtax2= $total_localtax2;
2914
-            $this->line->total_ttc      = $total_ttc;
2915
-            $this->line->date_start     = $date_start;
2916
-            $this->line->date_end       = $date_end;
2917
-            $this->line->product_type   = $type;
2918
-            $this->line->fk_parent_line = $fk_parent_line;
2919
-            $this->line->skip_update_total=$skip_update_total;
2920
-	        $this->line->fk_unit        = $fk_unit;
2906
+			$this->line->remise_percent = $remise_percent;
2907
+			$this->line->subprice       = $subprice;
2908
+			$this->line->info_bits      = $info_bits;
2909
+			$this->line->special_code   = $special_code;
2910
+			$this->line->total_ht       = $total_ht;
2911
+			$this->line->total_tva      = $total_tva;
2912
+			$this->line->total_localtax1= $total_localtax1;
2913
+			$this->line->total_localtax2= $total_localtax2;
2914
+			$this->line->total_ttc      = $total_ttc;
2915
+			$this->line->date_start     = $date_start;
2916
+			$this->line->date_end       = $date_end;
2917
+			$this->line->product_type   = $type;
2918
+			$this->line->fk_parent_line = $fk_parent_line;
2919
+			$this->line->skip_update_total=$skip_update_total;
2920
+			$this->line->fk_unit        = $fk_unit;
2921 2921
 
2922 2922
 			$this->line->fk_fournprice = $fk_fournprice;
2923 2923
 			$this->line->pa_ht = $pa_ht;
@@ -2925,44 +2925,44 @@  discard block
 block discarded – undo
2925 2925
 			// Multicurrency
2926 2926
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
2927 2927
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2928
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2929
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2928
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2929
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2930 2930
 
2931
-            // TODO deprecated
2932
-            $this->line->price=$price;
2933
-            $this->line->remise=$remise;
2931
+			// TODO deprecated
2932
+			$this->line->price=$price;
2933
+			$this->line->remise=$remise;
2934 2934
 
2935 2935
 			if (is_array($array_options) && count($array_options)>0) {
2936 2936
 				$this->line->array_options=$array_options;
2937 2937
 			}
2938 2938
 
2939
-            $result=$this->line->update($user, $notrigger);
2940
-            if ($result > 0)
2941
-            {
2942
-            	// Reorder if child line
2943
-            	if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2944
-
2945
-                // Mise a jour info denormalisees
2946
-                $this->update_price(1);
2947
-
2948
-                $this->db->commit();
2949
-                return $result;
2950
-            }
2951
-            else
2952
-            {
2953
-	            $this->error=$this->line->error;
2954
-
2955
-	            $this->db->rollback();
2956
-	            return -1;
2957
-            }
2958
-        }
2959
-        else
2960
-        {
2961
-            $this->error=get_class($this)."::updateline Order status makes operation forbidden";
2962
-        	$this->errors=array('OrderStatusMakeOperationForbidden');
2963
-            return -2;
2964
-        }
2965
-    }
2939
+			$result=$this->line->update($user, $notrigger);
2940
+			if ($result > 0)
2941
+			{
2942
+				// Reorder if child line
2943
+				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2944
+
2945
+				// Mise a jour info denormalisees
2946
+				$this->update_price(1);
2947
+
2948
+				$this->db->commit();
2949
+				return $result;
2950
+			}
2951
+			else
2952
+			{
2953
+				$this->error=$this->line->error;
2954
+
2955
+				$this->db->rollback();
2956
+				return -1;
2957
+			}
2958
+		}
2959
+		else
2960
+		{
2961
+			$this->error=get_class($this)."::updateline Order status makes operation forbidden";
2962
+			$this->errors=array('OrderStatusMakeOperationForbidden');
2963
+			return -2;
2964
+		}
2965
+	}
2966 2966
 
2967 2967
 	/**
2968 2968
 	 *      Update database
@@ -3025,383 +3025,383 @@  discard block
 block discarded – undo
3025 3025
 		{
3026 3026
 			if (! $notrigger)
3027 3027
 			{
3028
-	            // Call trigger
3029
-	            $result=$this->call_trigger('ORDER_MODIFY',$user);
3030
-	            if ($result < 0) $error++;
3031
-	            // End call triggers
3028
+				// Call trigger
3029
+				$result=$this->call_trigger('ORDER_MODIFY',$user);
3030
+				if ($result < 0) $error++;
3031
+				// End call triggers
3032
+			}
3033
+		}
3034
+
3035
+		// Commit or rollback
3036
+		if ($error)
3037
+		{
3038
+			foreach($this->errors as $errmsg)
3039
+			{
3040
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3041
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
3042
+			}
3043
+			$this->db->rollback();
3044
+			return -1*$error;
3045
+		}
3046
+		else
3047
+		{
3048
+			$this->db->commit();
3049
+			return 1;
3050
+		}
3051
+	}
3052
+
3053
+	/**
3054
+	 *	Update value of extrafields on order
3055
+	 *
3056
+	 *	@param      User	$user       Object user that modify
3057
+	 *	@return     int         		<0 if ko, >0 if ok
3058
+	 */
3059
+	function update_extrafields($user)
3060
+	{
3061
+		global $hookmanager, $conf;
3062
+
3063
+		$action='create';
3064
+		$error = 0;
3065
+
3066
+		// Actions on extra fields (by external module or standard code)
3067
+		// TODO le hook fait double emploi avec le trigger !!
3068
+		$hookmanager->initHooks(array('orderdao'));
3069
+		$parameters=array('id'=>$this->id);
3070
+		$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3071
+		if (empty($reshook))
3072
+		{
3073
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3074
+			{
3075
+				$result=$this->insertExtraFields();
3076
+				if ($result < 0)
3077
+				{
3078
+					$error++;
3079
+				}
3080
+			}
3081
+		}
3082
+		else if ($reshook < 0) $error++;
3083
+
3084
+		if (!$error)
3085
+		{
3086
+			return 1;
3087
+		}
3088
+		else
3089
+		{
3090
+			return -1;
3091
+		}
3092
+
3093
+	}
3094
+
3095
+	/**
3096
+	 *	Delete the customer order
3097
+	 *
3098
+	 *	@param	User	$user		User object
3099
+	 *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3100
+	 * 	@return	int					<=0 if KO, >0 if OK
3101
+	 */
3102
+	function delete($user, $notrigger=0)
3103
+	{
3104
+		global $conf, $langs;
3105
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3106
+
3107
+		$error = 0;
3108
+
3109
+		dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG);
3110
+
3111
+		$this->db->begin();
3112
+
3113
+		if (! $error && ! $notrigger)
3114
+		{
3115
+			// Call trigger
3116
+			$result=$this->call_trigger('ORDER_DELETE',$user);
3117
+			if ($result < 0) $error++;
3118
+			// End call triggers
3119
+		}
3120
+
3121
+		//TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail
3122
+		if (! $error)
3123
+		{
3124
+			// Delete order details
3125
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id;
3126
+			if (! $this->db->query($sql) )
3127
+			{
3128
+				$error++;
3129
+				$this->errors[]=$this->db->lasterror();
3130
+			}
3131
+
3132
+			// Delete order
3133
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id;
3134
+			if (! $this->db->query($sql) )
3135
+			{
3136
+				$error++;
3137
+				$this->errors[]=$this->db->lasterror();
3138
+			}
3139
+
3140
+			// Delete linked object
3141
+			$res = $this->deleteObjectLinked();
3142
+			if ($res < 0) $error++;
3143
+
3144
+			// Delete linked contacts
3145
+			$res = $this->delete_linked_contact();
3146
+			if ($res < 0) $error++;
3147
+
3148
+			// Remove extrafields
3149
+			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3150
+			{
3151
+				$result=$this->deleteExtraFields();
3152
+				if ($result < 0)
3153
+				{
3154
+					$error++;
3155
+					dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3156
+				}
3157
+			}
3158
+
3159
+			// On efface le repertoire de pdf provisoire
3160
+			$comref = dol_sanitizeFileName($this->ref);
3161
+			if ($conf->commande->dir_output && !empty($this->ref))
3162
+			{
3163
+				$dir = $conf->commande->dir_output . "/" . $comref ;
3164
+				$file = $conf->commande->dir_output . "/" . $comref . "/" . $comref . ".pdf";
3165
+				if (file_exists($file))	// We must delete all files before deleting directory
3166
+				{
3167
+					dol_delete_preview($this);
3168
+
3169
+					if (! dol_delete_file($file,0,0,0,$this)) // For triggers
3170
+					{
3171
+						$this->db->rollback();
3172
+						return 0;
3173
+					}
3174
+				}
3175
+				if (file_exists($dir))
3176
+				{
3177
+					if (! dol_delete_dir_recursive($dir))
3178
+					{
3179
+						$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
3180
+						$this->db->rollback();
3181
+						return 0;
3182
+					}
3183
+				}
3184
+			}
3185
+
3186
+
3187
+		}
3188
+
3189
+		if (! $error)
3190
+		{
3191
+			$this->db->commit();
3192
+			return 1;
3193
+		}
3194
+		else
3195
+		{
3196
+			foreach($this->errors as $errmsg)
3197
+			{
3198
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
3199
+			}
3200
+			$this->db->rollback();
3201
+			return -1*$error;
3202
+		}
3203
+	}
3204
+
3205
+
3206
+	/**
3207
+	 *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
3208
+	 *
3209
+	 *	@param		User	$user   Object user
3210
+	 *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
3211
+	 */
3212
+	function load_board($user)
3213
+	{
3214
+		global $conf, $langs;
3215
+
3216
+		$clause = " WHERE";
3217
+
3218
+		$sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut";
3219
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
3220
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
3221
+		{
3222
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3223
+			$sql.= " WHERE sc.fk_user = " .$user->id;
3224
+			$clause = " AND";
3225
+		}
3226
+		$sql.= $clause." c.entity IN (".getEntity('commande').")";
3227
+		//$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3228
+		$sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))";    // If status is 2 and facture=1, it must be selected
3229
+		if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
3230
+
3231
+		$resql=$this->db->query($sql);
3232
+		if ($resql)
3233
+		{
3234
+			$response = new WorkboardResponse();
3235
+			$response->warning_delay=$conf->commande->client->warning_delay/60/60/24;
3236
+			$response->label=$langs->trans("OrdersToProcess");
3237
+			$response->url=DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
3238
+			$response->img=img_object('',"order");
3239
+
3240
+			$generic_commande = new Commande($this->db);
3241
+
3242
+			while ($obj=$this->db->fetch_object($resql))
3243
+			{
3244
+				$response->nbtodo++;
3245
+
3246
+				$generic_commande->statut = $obj->fk_statut;
3247
+				$generic_commande->date_commande = $this->db->jdate($obj->date_commande);
3248
+				$generic_commande->date_livraison = $this->db->jdate($obj->delivery_date);
3249
+
3250
+				if ($generic_commande->hasDelay()) {
3251
+					$response->nbtodolate++;
3252
+				}
3032 3253
 			}
3254
+
3255
+			return $response;
3256
+		}
3257
+		else
3258
+		{
3259
+			$this->error=$this->db->error();
3260
+			return -1;
3261
+		}
3262
+	}
3263
+
3264
+	/**
3265
+	 *	Return source label of order
3266
+	 *
3267
+	 *	@return     string      Label
3268
+	 */
3269
+	function getLabelSource()
3270
+	{
3271
+		global $langs;
3272
+
3273
+		$label=$langs->trans('OrderSource'.$this->source);
3274
+
3275
+		if ($label == 'OrderSource') return '';
3276
+		return $label;
3277
+	}
3278
+
3279
+	/**
3280
+	 *	Return status label of Order
3281
+	 *
3282
+	 *	@param      int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
3283
+	 *	@return     string      		Libelle
3284
+	 */
3285
+	function getLibStatut($mode)
3286
+	{
3287
+		if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility
3288
+		return $this->LibStatut($this->statut,$this->billed,$mode);
3289
+	}
3290
+
3291
+	/**
3292
+	 *	Return label of status
3293
+	 *
3294
+	 *	@param		int		$statut      	  Id statut
3295
+	 *  @param      int		$billed    		  If invoiced
3296
+	 *	@param      int		$mode        	  0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
3297
+	 *  @param      int     $donotshowbilled  Do not show billed status after order status
3298
+	 *  @return     string					  Label of status
3299
+	 */
3300
+	function LibStatut($statut,$billed,$mode,$donotshowbilled=0)
3301
+	{
3302
+		global $langs, $conf;
3303
+
3304
+		$billedtext = '';
3305
+		if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3306
+
3307
+		//print 'x'.$statut.'-'.$billed;
3308
+		if ($mode == 0)
3309
+		{
3310
+			if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3311
+			if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3312
+			if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3313
+			if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3314
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3315
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3316
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3317
+		}
3318
+		elseif ($mode == 1)
3319
+		{
3320
+			if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3321
+			if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3322
+			if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3323
+			if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3324
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3325
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3326
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3327
+		}
3328
+		elseif ($mode == 2)
3329
+		{
3330
+			if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3331
+			if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3332
+			if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3333
+			if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3334
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3335
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3336
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3337
+		}
3338
+		elseif ($mode == 3)
3339
+		{
3340
+			if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3341
+			if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3342
+			if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3343
+			if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3344
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3345
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3346
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3033 3347
 		}
3034
-
3035
-		// Commit or rollback
3036
-		if ($error)
3348
+		elseif ($mode == 4)
3037 3349
 		{
3038
-			foreach($this->errors as $errmsg)
3039
-			{
3040
-				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3041
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
3042
-			}
3043
-			$this->db->rollback();
3044
-			return -1*$error;
3350
+			if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3351
+			if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3352
+			if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3353
+			if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3354
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3355
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3356
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3045 3357
 		}
3046
-		else
3358
+		elseif ($mode == 5)
3047 3359
 		{
3048
-			$this->db->commit();
3049
-			return 1;
3360
+			if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3361
+			if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3362
+			if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3363
+			if ($statut==self::STATUS_ACCEPTED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3364
+			if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3365
+			if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3366
+			if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3050 3367
 		}
3051 3368
 	}
3052 3369
 
3053
-    /**
3054
-     *	Update value of extrafields on order
3055
-     *
3056
-     *	@param      User	$user       Object user that modify
3057
-     *	@return     int         		<0 if ko, >0 if ok
3058
-     */
3059
-    function update_extrafields($user)
3060
-    {
3061
-        global $hookmanager, $conf;
3062
-
3063
-    	$action='create';
3064
-        $error = 0;
3065
-
3066
-    	// Actions on extra fields (by external module or standard code)
3067
-    	// TODO le hook fait double emploi avec le trigger !!
3068
-    	$hookmanager->initHooks(array('orderdao'));
3069
-    	$parameters=array('id'=>$this->id);
3070
-    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3071
-    	if (empty($reshook))
3072
-    	{
3073
-    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3074
-    		{
3075
-    			$result=$this->insertExtraFields();
3076
-    			if ($result < 0)
3077
-    			{
3078
-    				$error++;
3079
-    			}
3080
-    		}
3081
-    	}
3082
-    	else if ($reshook < 0) $error++;
3083
-
3084
-    	if (!$error)
3085
-    	{
3086
-    		return 1;
3087
-    	}
3088
-    	else
3089
-    	{
3090
-    		return -1;
3091
-    	}
3092
-
3093
-    }
3094
-
3095
-    /**
3096
-     *	Delete the customer order
3097
-     *
3098
-     *	@param	User	$user		User object
3099
-     *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3100
-     * 	@return	int					<=0 if KO, >0 if OK
3101
-     */
3102
-    function delete($user, $notrigger=0)
3103
-    {
3104
-        global $conf, $langs;
3105
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3106
-
3107
-        $error = 0;
3108
-
3109
-        dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG);
3110
-
3111
-        $this->db->begin();
3112
-
3113
-        if (! $error && ! $notrigger)
3114
-        {
3115
-            // Call trigger
3116
-            $result=$this->call_trigger('ORDER_DELETE',$user);
3117
-            if ($result < 0) $error++;
3118
-            // End call triggers
3119
-        }
3120
-
3121
-        //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail
3122
-        if (! $error)
3123
-        {
3124
-        	// Delete order details
3125
-        	$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id;
3126
-        	if (! $this->db->query($sql) )
3127
-        	{
3128
-        		$error++;
3129
-        		$this->errors[]=$this->db->lasterror();
3130
-        	}
3131
-
3132
-        	// Delete order
3133
-        	$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id;
3134
-        	if (! $this->db->query($sql) )
3135
-        	{
3136
-        		$error++;
3137
-        		$this->errors[]=$this->db->lasterror();
3138
-        	}
3139
-
3140
-        	// Delete linked object
3141
-        	$res = $this->deleteObjectLinked();
3142
-        	if ($res < 0) $error++;
3143
-
3144
-        	// Delete linked contacts
3145
-        	$res = $this->delete_linked_contact();
3146
-        	if ($res < 0) $error++;
3147
-
3148
-        	// Remove extrafields
3149
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3150
-        	{
3151
-        		$result=$this->deleteExtraFields();
3152
-        		if ($result < 0)
3153
-        		{
3154
-        			$error++;
3155
-        			dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3156
-        		}
3157
-        	}
3158
-
3159
-        	// On efface le repertoire de pdf provisoire
3160
-        	$comref = dol_sanitizeFileName($this->ref);
3161
-        	if ($conf->commande->dir_output && !empty($this->ref))
3162
-        	{
3163
-        		$dir = $conf->commande->dir_output . "/" . $comref ;
3164
-        		$file = $conf->commande->dir_output . "/" . $comref . "/" . $comref . ".pdf";
3165
-        		if (file_exists($file))	// We must delete all files before deleting directory
3166
-        		{
3167
-        			dol_delete_preview($this);
3168
-
3169
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
3170
-        			{
3171
-        				$this->db->rollback();
3172
-        				return 0;
3173
-        			}
3174
-        		}
3175
-        		if (file_exists($dir))
3176
-        		{
3177
-        			if (! dol_delete_dir_recursive($dir))
3178
-        			{
3179
-        				$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
3180
-        				$this->db->rollback();
3181
-        				return 0;
3182
-        			}
3183
-        		}
3184
-        	}
3185
-
3186
-
3187
-        }
3188
-
3189
-        if (! $error)
3190
-        {
3191
-        	$this->db->commit();
3192
-        	return 1;
3193
-        }
3194
-        else
3195
-        {
3196
-	        foreach($this->errors as $errmsg)
3197
-	        {
3198
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
3199
-	        }
3200
-	        $this->db->rollback();
3201
-	        return -1*$error;
3202
-        }
3203
-    }
3204
-
3205
-
3206
-    /**
3207
-     *	Load indicators for dashboard (this->nbtodo and this->nbtodolate)
3208
-     *
3209
-     *	@param		User	$user   Object user
3210
-     *	@return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
3211
-     */
3212
-    function load_board($user)
3213
-    {
3214
-        global $conf, $langs;
3215
-
3216
-        $clause = " WHERE";
3217
-
3218
-        $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut";
3219
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
3220
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
3221
-        {
3222
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3223
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3224
-            $clause = " AND";
3225
-        }
3226
-        $sql.= $clause." c.entity IN (".getEntity('commande').")";
3227
-        //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3228
-        $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))";    // If status is 2 and facture=1, it must be selected
3229
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
3230
-
3231
-        $resql=$this->db->query($sql);
3232
-        if ($resql)
3233
-        {
3234
-	        $response = new WorkboardResponse();
3235
-	        $response->warning_delay=$conf->commande->client->warning_delay/60/60/24;
3236
-	        $response->label=$langs->trans("OrdersToProcess");
3237
-	        $response->url=DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
3238
-	        $response->img=img_object('',"order");
3239
-
3240
-            $generic_commande = new Commande($this->db);
3241
-
3242
-            while ($obj=$this->db->fetch_object($resql))
3243
-            {
3244
-                $response->nbtodo++;
3245
-
3246
-                $generic_commande->statut = $obj->fk_statut;
3247
-                $generic_commande->date_commande = $this->db->jdate($obj->date_commande);
3248
-                $generic_commande->date_livraison = $this->db->jdate($obj->delivery_date);
3249
-
3250
-                if ($generic_commande->hasDelay()) {
3251
-		            $response->nbtodolate++;
3252
-	            }
3253
-            }
3254
-
3255
-            return $response;
3256
-        }
3257
-        else
3258
-        {
3259
-            $this->error=$this->db->error();
3260
-            return -1;
3261
-        }
3262
-    }
3263
-
3264
-    /**
3265
-     *	Return source label of order
3266
-     *
3267
-     *	@return     string      Label
3268
-     */
3269
-    function getLabelSource()
3270
-    {
3271
-        global $langs;
3272
-
3273
-        $label=$langs->trans('OrderSource'.$this->source);
3274
-
3275
-        if ($label == 'OrderSource') return '';
3276
-        return $label;
3277
-    }
3278
-
3279
-    /**
3280
-     *	Return status label of Order
3281
-     *
3282
-     *	@param      int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
3283
-     *	@return     string      		Libelle
3284
-     */
3285
-    function getLibStatut($mode)
3286
-    {
3287
-        if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility
3288
-        return $this->LibStatut($this->statut,$this->billed,$mode);
3289
-    }
3290
-
3291
-    /**
3292
-     *	Return label of status
3293
-     *
3294
-     *	@param		int		$statut      	  Id statut
3295
-     *  @param      int		$billed    		  If invoiced
3296
-     *	@param      int		$mode        	  0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
3297
-     *  @param      int     $donotshowbilled  Do not show billed status after order status
3298
-     *  @return     string					  Label of status
3299
-     */
3300
-    function LibStatut($statut,$billed,$mode,$donotshowbilled=0)
3301
-    {
3302
-        global $langs, $conf;
3303
-
3304
-        $billedtext = '';
3305
-        if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3306
-
3307
-        //print 'x'.$statut.'-'.$billed;
3308
-        if ($mode == 0)
3309
-        {
3310
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3311
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3312
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3313
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3314
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3315
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3316
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3317
-        }
3318
-        elseif ($mode == 1)
3319
-        {
3320
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3321
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3322
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3323
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3324
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3325
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3326
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3327
-        }
3328
-        elseif ($mode == 2)
3329
-        {
3330
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3331
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3332
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3333
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3334
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3335
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3336
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3337
-        }
3338
-        elseif ($mode == 3)
3339
-        {
3340
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3341
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3342
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3343
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3344
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3345
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3346
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3347
-        }
3348
-        elseif ($mode == 4)
3349
-        {
3350
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3351
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3352
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3353
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3354
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3355
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3356
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3357
-        }
3358
-        elseif ($mode == 5)
3359
-        {
3360
-            if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3361
-            if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3362
-            if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3363
-            if ($statut==self::STATUS_ACCEPTED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3364
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3365
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3366
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3367
-        }
3368
-    }
3369
-
3370
-
3371
-    /**
3372
-     *	Return clicable link of object (with eventually picto)
3373
-     *
3374
-     *	@param      int			$withpicto                Add picto into link
3375
-     *	@param      string	    $option                   Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
3376
-     *	@param      int			$max          	          Max length to show
3377
-     *	@param      int			$short			          ???
3378
-     *  @param	    int   	    $notooltip		          1=Disable tooltip
3379
-     *  @param      int         $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3380
-     *	@return     string          			          String with URL
3381
-     */
3382
-    function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
3383
-    {
3384
-        global $conf, $langs, $user;
3385
-
3386
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3387
-
3388
-        $result='';
3389
-
3390
-        if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3391
-        else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3392
-
3393
-        if ($option !== 'nolink')
3394
-        {
3395
-            // Add param to save lastsearch_values or not
3396
-            $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3397
-            if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3398
-            if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3399
-        }
3400
-
3401
-        if ($short) return $url;
3402
-
3403
-        $picto = 'order';
3404
-        $label = '';
3370
+
3371
+	/**
3372
+	 *	Return clicable link of object (with eventually picto)
3373
+	 *
3374
+	 *	@param      int			$withpicto                Add picto into link
3375
+	 *	@param      string	    $option                   Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
3376
+	 *	@param      int			$max          	          Max length to show
3377
+	 *	@param      int			$short			          ???
3378
+	 *  @param	    int   	    $notooltip		          1=Disable tooltip
3379
+	 *  @param      int         $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3380
+	 *	@return     string          			          String with URL
3381
+	 */
3382
+	function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
3383
+	{
3384
+		global $conf, $langs, $user;
3385
+
3386
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3387
+
3388
+		$result='';
3389
+
3390
+		if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3391
+		else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3392
+
3393
+		if ($option !== 'nolink')
3394
+		{
3395
+			// Add param to save lastsearch_values or not
3396
+			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3397
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3398
+			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3399
+		}
3400
+
3401
+		if ($short) return $url;
3402
+
3403
+		$picto = 'order';
3404
+		$label = '';
3405 3405
 
3406 3406
 		if ($user->rights->commande->lire) {
3407 3407
 			$label = '<u>'.$langs->trans("ShowOrder").'</u>';
@@ -3421,223 +3421,223 @@  discard block
 block discarded – undo
3421 3421
 		$linkclose='';
3422 3422
 		if (empty($notooltip) && $user->rights->commande->lire)
3423 3423
 		{
3424
-		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3425
-		    {
3426
-		        $label=$langs->trans("ShowOrder");
3427
-		        $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3428
-		    }
3429
-		    $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3430
-		    $linkclose.=' class="classfortooltip"';
3424
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3425
+			{
3426
+				$label=$langs->trans("ShowOrder");
3427
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3428
+			}
3429
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3430
+			$linkclose.=' class="classfortooltip"';
3431
+		}
3432
+
3433
+		$linkstart = '<a href="'.$url.'"';
3434
+		$linkstart.=$linkclose.'>';
3435
+		$linkend='</a>';
3436
+
3437
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3438
+		if ($withpicto && $withpicto != 2) $result.=' ';
3439
+		$result.=$linkstart.$this->ref.$linkend;
3440
+		return $result;
3441
+	}
3442
+
3443
+
3444
+	/**
3445
+	 *	Charge les informations d'ordre info dans l'objet commande
3446
+	 *
3447
+	 *	@param  int		$id       Id of order
3448
+	 *	@return	void
3449
+	 */
3450
+	function info($id)
3451
+	{
3452
+		$sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
3453
+		$sql.= ' date_valid as datev,';
3454
+		$sql.= ' date_cloture as datecloture,';
3455
+		$sql.= ' fk_user_author, fk_user_valid, fk_user_cloture';
3456
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
3457
+		$sql.= ' WHERE c.rowid = '.$id;
3458
+		$result=$this->db->query($sql);
3459
+		if ($result)
3460
+		{
3461
+			if ($this->db->num_rows($result))
3462
+			{
3463
+				$obj = $this->db->fetch_object($result);
3464
+				$this->id = $obj->rowid;
3465
+				if ($obj->fk_user_author)
3466
+				{
3467
+					$cuser = new User($this->db);
3468
+					$cuser->fetch($obj->fk_user_author);
3469
+					$this->user_creation   = $cuser;
3470
+				}
3471
+
3472
+				if ($obj->fk_user_valid)
3473
+				{
3474
+					$vuser = new User($this->db);
3475
+					$vuser->fetch($obj->fk_user_valid);
3476
+					$this->user_validation = $vuser;
3477
+				}
3478
+
3479
+				if ($obj->fk_user_cloture)
3480
+				{
3481
+					$cluser = new User($this->db);
3482
+					$cluser->fetch($obj->fk_user_cloture);
3483
+					$this->user_cloture   = $cluser;
3484
+				}
3485
+
3486
+				$this->date_creation     = $this->db->jdate($obj->datec);
3487
+				$this->date_modification = $this->db->jdate($obj->datem);
3488
+				$this->date_validation   = $this->db->jdate($obj->datev);
3489
+				$this->date_cloture      = $this->db->jdate($obj->datecloture);
3490
+			}
3491
+
3492
+			$this->db->free($result);
3493
+
3494
+		}
3495
+		else
3496
+		{
3497
+			dol_print_error($this->db);
3498
+		}
3499
+	}
3500
+
3501
+
3502
+	/**
3503
+	 *  Initialise an instance with random values.
3504
+	 *  Used to build previews or test instances.
3505
+	 *	id must be 0 if object instance is a specimen.
3506
+	 *
3507
+	 *  @return	void
3508
+	 */
3509
+	function initAsSpecimen()
3510
+	{
3511
+		global $langs;
3512
+
3513
+		dol_syslog(get_class($this)."::initAsSpecimen");
3514
+
3515
+		// Load array of products prodids
3516
+		$num_prods = 0;
3517
+		$prodids = array();
3518
+		$sql = "SELECT rowid";
3519
+		$sql.= " FROM ".MAIN_DB_PREFIX."product";
3520
+		$sql.= " WHERE entity IN (".getEntity('product').")";
3521
+		$resql = $this->db->query($sql);
3522
+		if ($resql)
3523
+		{
3524
+			$num_prods = $this->db->num_rows($resql);
3525
+			$i = 0;
3526
+			while ($i < $num_prods)
3527
+			{
3528
+				$i++;
3529
+				$row = $this->db->fetch_row($resql);
3530
+				$prodids[$i] = $row[0];
3531
+			}
3431 3532
 		}
3432 3533
 
3433
-        $linkstart = '<a href="'.$url.'"';
3434
-        $linkstart.=$linkclose.'>';
3435
-        $linkend='</a>';
3436
-
3437
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3438
-        if ($withpicto && $withpicto != 2) $result.=' ';
3439
-        $result.=$linkstart.$this->ref.$linkend;
3440
-        return $result;
3441
-    }
3442
-
3443
-
3444
-    /**
3445
-     *	Charge les informations d'ordre info dans l'objet commande
3446
-     *
3447
-     *	@param  int		$id       Id of order
3448
-     *	@return	void
3449
-     */
3450
-    function info($id)
3451
-    {
3452
-        $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
3453
-        $sql.= ' date_valid as datev,';
3454
-        $sql.= ' date_cloture as datecloture,';
3455
-        $sql.= ' fk_user_author, fk_user_valid, fk_user_cloture';
3456
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
3457
-        $sql.= ' WHERE c.rowid = '.$id;
3458
-        $result=$this->db->query($sql);
3459
-        if ($result)
3460
-        {
3461
-            if ($this->db->num_rows($result))
3462
-            {
3463
-                $obj = $this->db->fetch_object($result);
3464
-                $this->id = $obj->rowid;
3465
-                if ($obj->fk_user_author)
3466
-                {
3467
-                    $cuser = new User($this->db);
3468
-                    $cuser->fetch($obj->fk_user_author);
3469
-                    $this->user_creation   = $cuser;
3470
-                }
3471
-
3472
-                if ($obj->fk_user_valid)
3473
-                {
3474
-                    $vuser = new User($this->db);
3475
-                    $vuser->fetch($obj->fk_user_valid);
3476
-                    $this->user_validation = $vuser;
3477
-                }
3478
-
3479
-                if ($obj->fk_user_cloture)
3480
-                {
3481
-                    $cluser = new User($this->db);
3482
-                    $cluser->fetch($obj->fk_user_cloture);
3483
-                    $this->user_cloture   = $cluser;
3484
-                }
3485
-
3486
-                $this->date_creation     = $this->db->jdate($obj->datec);
3487
-                $this->date_modification = $this->db->jdate($obj->datem);
3488
-                $this->date_validation   = $this->db->jdate($obj->datev);
3489
-                $this->date_cloture      = $this->db->jdate($obj->datecloture);
3490
-            }
3491
-
3492
-            $this->db->free($result);
3493
-
3494
-        }
3495
-        else
3496
-        {
3497
-            dol_print_error($this->db);
3498
-        }
3499
-    }
3500
-
3501
-
3502
-    /**
3503
-     *  Initialise an instance with random values.
3504
-     *  Used to build previews or test instances.
3505
-     *	id must be 0 if object instance is a specimen.
3506
-     *
3507
-     *  @return	void
3508
-     */
3509
-    function initAsSpecimen()
3510
-    {
3511
-        global $langs;
3512
-
3513
-        dol_syslog(get_class($this)."::initAsSpecimen");
3514
-
3515
-        // Load array of products prodids
3516
-        $num_prods = 0;
3517
-        $prodids = array();
3518
-        $sql = "SELECT rowid";
3519
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
3520
-        $sql.= " WHERE entity IN (".getEntity('product').")";
3521
-        $resql = $this->db->query($sql);
3522
-        if ($resql)
3523
-        {
3524
-            $num_prods = $this->db->num_rows($resql);
3525
-            $i = 0;
3526
-            while ($i < $num_prods)
3527
-            {
3528
-                $i++;
3529
-                $row = $this->db->fetch_row($resql);
3530
-                $prodids[$i] = $row[0];
3531
-            }
3532
-        }
3533
-
3534
-        // Initialise parametres
3535
-        $this->id=0;
3536
-        $this->ref = 'SPECIMEN';
3537
-        $this->specimen=1;
3538
-        $this->socid = 1;
3539
-        $this->date = time();
3540
-        $this->date_lim_reglement=$this->date+3600*24*30;
3541
-        $this->cond_reglement_code = 'RECEP';
3542
-        $this->mode_reglement_code = 'CHQ';
3543
-        $this->availability_code   = 'DSP';
3544
-        $this->demand_reason_code  = 'SRC_00';
3545
-        $this->note_public='This is a comment (public)';
3546
-        $this->note_private='This is a comment (private)';
3547
-        // Lines
3548
-        $nbp = 5;
3549
-        $xnbp = 0;
3550
-        while ($xnbp < $nbp)
3551
-        {
3552
-            $line=new OrderLine($this->db);
3553
-
3554
-            $line->desc=$langs->trans("Description")." ".$xnbp;
3555
-            $line->qty=1;
3556
-            $line->subprice=100;
3557
-            $line->price=100;
3558
-            $line->tva_tx=20;
3559
-            if ($xnbp == 2)
3560
-            {
3561
-                $line->total_ht=50;
3562
-                $line->total_ttc=60;
3563
-                $line->total_tva=10;
3564
-                $line->remise_percent=50;
3565
-            }
3566
-            else
3567
-            {
3568
-                $line->total_ht=100;
3569
-                $line->total_ttc=120;
3570
-                $line->total_tva=20;
3571
-                $line->remise_percent=0;
3572
-            }
3573
-            if ($num_prods > 0)
3574
-            {
3575
-            	$prodid = mt_rand(1, $num_prods);
3576
-            	$line->fk_product=$prodids[$prodid];
3534
+		// Initialise parametres
3535
+		$this->id=0;
3536
+		$this->ref = 'SPECIMEN';
3537
+		$this->specimen=1;
3538
+		$this->socid = 1;
3539
+		$this->date = time();
3540
+		$this->date_lim_reglement=$this->date+3600*24*30;
3541
+		$this->cond_reglement_code = 'RECEP';
3542
+		$this->mode_reglement_code = 'CHQ';
3543
+		$this->availability_code   = 'DSP';
3544
+		$this->demand_reason_code  = 'SRC_00';
3545
+		$this->note_public='This is a comment (public)';
3546
+		$this->note_private='This is a comment (private)';
3547
+		// Lines
3548
+		$nbp = 5;
3549
+		$xnbp = 0;
3550
+		while ($xnbp < $nbp)
3551
+		{
3552
+			$line=new OrderLine($this->db);
3553
+
3554
+			$line->desc=$langs->trans("Description")." ".$xnbp;
3555
+			$line->qty=1;
3556
+			$line->subprice=100;
3557
+			$line->price=100;
3558
+			$line->tva_tx=20;
3559
+			if ($xnbp == 2)
3560
+			{
3561
+				$line->total_ht=50;
3562
+				$line->total_ttc=60;
3563
+				$line->total_tva=10;
3564
+				$line->remise_percent=50;
3565
+			}
3566
+			else
3567
+			{
3568
+				$line->total_ht=100;
3569
+				$line->total_ttc=120;
3570
+				$line->total_tva=20;
3571
+				$line->remise_percent=0;
3572
+			}
3573
+			if ($num_prods > 0)
3574
+			{
3575
+				$prodid = mt_rand(1, $num_prods);
3576
+				$line->fk_product=$prodids[$prodid];
3577 3577
 				$line->product_ref='SPECIMEN';
3578
-            }
3579
-
3580
-            $this->lines[$xnbp]=$line;
3581
-
3582
-            $this->total_ht       += $line->total_ht;
3583
-            $this->total_tva      += $line->total_tva;
3584
-            $this->total_ttc      += $line->total_ttc;
3585
-
3586
-            $xnbp++;
3587
-        }
3588
-    }
3589
-
3590
-
3591
-    /**
3592
-     *	Charge indicateurs this->nb de tableau de bord
3593
-     *
3594
-     *	@return     int         <0 si ko, >0 si ok
3595
-     */
3596
-    function load_state_board()
3597
-    {
3598
-        global $user;
3599
-
3600
-        $this->nb=array();
3601
-        $clause = "WHERE";
3602
-
3603
-        $sql = "SELECT count(co.rowid) as nb";
3604
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande as co";
3605
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3606
-        if (!$user->rights->societe->client->voir && !$user->societe_id)
3607
-        {
3608
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3609
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3610
-            $clause = "AND";
3611
-        }
3612
-        $sql.= " ".$clause." co.entity IN (".getEntity('commande').")";
3613
-
3614
-        $resql=$this->db->query($sql);
3615
-        if ($resql)
3616
-        {
3617
-            while ($obj=$this->db->fetch_object($resql))
3618
-            {
3619
-                $this->nb["orders"]=$obj->nb;
3620
-            }
3621
-            $this->db->free($resql);
3622
-            return 1;
3623
-        }
3624
-        else
3625
-        {
3626
-            dol_print_error($this->db);
3627
-            $this->error=$this->db->error();
3628
-            return -1;
3629
-        }
3630
-    }
3631
-
3632
-    /**
3578
+			}
3579
+
3580
+			$this->lines[$xnbp]=$line;
3581
+
3582
+			$this->total_ht       += $line->total_ht;
3583
+			$this->total_tva      += $line->total_tva;
3584
+			$this->total_ttc      += $line->total_ttc;
3585
+
3586
+			$xnbp++;
3587
+		}
3588
+	}
3589
+
3590
+
3591
+	/**
3592
+	 *	Charge indicateurs this->nb de tableau de bord
3593
+	 *
3594
+	 *	@return     int         <0 si ko, >0 si ok
3595
+	 */
3596
+	function load_state_board()
3597
+	{
3598
+		global $user;
3599
+
3600
+		$this->nb=array();
3601
+		$clause = "WHERE";
3602
+
3603
+		$sql = "SELECT count(co.rowid) as nb";
3604
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande as co";
3605
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3606
+		if (!$user->rights->societe->client->voir && !$user->societe_id)
3607
+		{
3608
+			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3609
+			$sql.= " WHERE sc.fk_user = " .$user->id;
3610
+			$clause = "AND";
3611
+		}
3612
+		$sql.= " ".$clause." co.entity IN (".getEntity('commande').")";
3613
+
3614
+		$resql=$this->db->query($sql);
3615
+		if ($resql)
3616
+		{
3617
+			while ($obj=$this->db->fetch_object($resql))
3618
+			{
3619
+				$this->nb["orders"]=$obj->nb;
3620
+			}
3621
+			$this->db->free($resql);
3622
+			return 1;
3623
+		}
3624
+		else
3625
+		{
3626
+			dol_print_error($this->db);
3627
+			$this->error=$this->db->error();
3628
+			return -1;
3629
+		}
3630
+	}
3631
+
3632
+	/**
3633 3633
 	 * 	Create an array of order lines
3634 3634
 	 *
3635 3635
 	 * 	@return int		>0 if OK, <0 if KO
3636
-     */
3637
-    function getLinesArray()
3638
-    {
3639
-        return $this->fetch_lines();
3640
-    }
3636
+	 */
3637
+	function getLinesArray()
3638
+	{
3639
+		return $this->fetch_lines();
3640
+	}
3641 3641
 
3642 3642
 	/**
3643 3643
 	 *  Create a document onto disk according to template module.
@@ -3689,39 +3689,39 @@  discard block
 block discarded – undo
3689 3689
 		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3690 3690
 	}
3691 3691
 
3692
-    /**
3693
-     * Is the customer order delayed?
3694
-     *
3695
-     * @return bool     true if late, false if not
3696
-     */
3697
-    public function hasDelay()
3698
-    {
3699
-        global $conf;
3700
-
3701
-        if (! ($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
3702
-            return false;   // Never late if not inside this status range
3703
-        }
3704
-
3705
-        $now = dol_now();
3706
-
3707
-        return max($this->date_commande, $this->date_livraison) < ($now - $conf->commande->client->warning_delay);
3708
-    }
3709
-
3710
-    /**
3711
-     * Show the customer delayed info
3712
-     *
3713
-     * @return string       Show delayed information
3714
-     */
3715
-    public function showDelay()
3716
-    {
3717
-        global $conf, $langs;
3718
-
3719
-        if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3720
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3721
-        $text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3722
-
3723
-        return $text;
3724
-    }
3692
+	/**
3693
+	 * Is the customer order delayed?
3694
+	 *
3695
+	 * @return bool     true if late, false if not
3696
+	 */
3697
+	public function hasDelay()
3698
+	{
3699
+		global $conf;
3700
+
3701
+		if (! ($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
3702
+			return false;   // Never late if not inside this status range
3703
+		}
3704
+
3705
+		$now = dol_now();
3706
+
3707
+		return max($this->date_commande, $this->date_livraison) < ($now - $conf->commande->client->warning_delay);
3708
+	}
3709
+
3710
+	/**
3711
+	 * Show the customer delayed info
3712
+	 *
3713
+	 * @return string       Show delayed information
3714
+	 */
3715
+	public function showDelay()
3716
+	{
3717
+		global $conf, $langs;
3718
+
3719
+		if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3720
+		else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3721
+		$text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3722
+
3723
+		return $text;
3724
+	}
3725 3725
 }
3726 3726
 
3727 3727
 
@@ -3733,7 +3733,7 @@  discard block
 block discarded – undo
3733 3733
 	public $element='commandedet';
3734 3734
 	public $table_element='commandedet';
3735 3735
 
3736
-    var $oldline;
3736
+	var $oldline;
3737 3737
 
3738 3738
 	/**
3739 3739
 	 * Id of parent order
@@ -3749,12 +3749,12 @@  discard block
 block discarded – undo
3749 3749
 	 */
3750 3750
 	public $commande_id;
3751 3751
 
3752
-    // From llx_commandedet
3753
-    var $fk_parent_line;
3754
-    var $fk_facture;
3755
-    var $label;
3756
-    var $fk_remise_except;
3757
-    var $rang = 0;
3752
+	// From llx_commandedet
3753
+	var $fk_parent_line;
3754
+	var $fk_facture;
3755
+	var $label;
3756
+	var $fk_remise_except;
3757
+	var $rang = 0;
3758 3758
 	var $fk_fournprice;
3759 3759
 
3760 3760
 	/**
@@ -3762,8 +3762,8 @@  discard block
 block discarded – undo
3762 3762
 	 * @var float
3763 3763
 	 */
3764 3764
 	var $pa_ht;
3765
-    var $marge_tx;
3766
-    var $marque_tx;
3765
+	var $marge_tx;
3766
+	var $marque_tx;
3767 3767
 
3768 3768
 	/**
3769 3769
 	 * @deprecated
@@ -3771,88 +3771,88 @@  discard block
 block discarded – undo
3771 3771
 	 */
3772 3772
 	var $remise;
3773 3773
 
3774
-    // Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
3775
-    // Start and end date of the line
3776
-    var $date_start;
3777
-    var $date_end;
3778
-
3779
-    var $skip_update_total; // Skip update price total for special lines
3780
-
3781
-
3782
-    /**
3783
-     *      Constructor
3784
-     *
3785
-     *      @param     DoliDB	$db      handler d'acces base de donnee
3786
-     */
3787
-    function __construct($db)
3788
-    {
3789
-        $this->db= $db;
3790
-    }
3791
-
3792
-    /**
3793
-     *  Load line order
3794
-     *
3795
-     *  @param  int		$rowid          Id line order
3796
-     *  @return	int						<0 if KO, >0 if OK
3797
-     */
3798
-    function fetch($rowid)
3799
-    {
3800
-        $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,';
3801
-        $sql.= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,';
3802
-        $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
3803
-	    $sql.= ' cd.fk_unit,';
3774
+	// Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
3775
+	// Start and end date of the line
3776
+	var $date_start;
3777
+	var $date_end;
3778
+
3779
+	var $skip_update_total; // Skip update price total for special lines
3780
+
3781
+
3782
+	/**
3783
+	 *      Constructor
3784
+	 *
3785
+	 *      @param     DoliDB	$db      handler d'acces base de donnee
3786
+	 */
3787
+	function __construct($db)
3788
+	{
3789
+		$this->db= $db;
3790
+	}
3791
+
3792
+	/**
3793
+	 *  Load line order
3794
+	 *
3795
+	 *  @param  int		$rowid          Id line order
3796
+	 *  @return	int						<0 if KO, >0 if OK
3797
+	 */
3798
+	function fetch($rowid)
3799
+	{
3800
+		$sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,';
3801
+		$sql.= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,';
3802
+		$sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
3803
+		$sql.= ' cd.fk_unit,';
3804 3804
 		$sql.= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
3805
-        $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,';
3806
-        $sql.= ' cd.date_start, cd.date_end';
3807
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
3808
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3809
-        $sql.= ' WHERE cd.rowid = '.$rowid;
3810
-        $result = $this->db->query($sql);
3811
-        if ($result)
3812
-        {
3813
-            $objp = $this->db->fetch_object($result);
3814
-            $this->rowid            = $objp->rowid;
3815
-            $this->fk_commande      = $objp->fk_commande;
3816
-            $this->fk_parent_line   = $objp->fk_parent_line;
3817
-            $this->label            = $objp->custom_label;
3818
-            $this->desc             = $objp->description;
3819
-            $this->qty              = $objp->qty;
3820
-            $this->price            = $objp->price;
3821
-            $this->subprice         = $objp->subprice;
3822
-            $this->vat_src_code     = $objp->vat_src_code;
3823
-            $this->tva_tx           = $objp->tva_tx;
3824
-            $this->localtax1_tx		= $objp->localtax1_tx;
3825
-            $this->localtax2_tx		= $objp->localtax2_tx;
3826
-            $this->remise           = $objp->remise;
3827
-            $this->remise_percent   = $objp->remise_percent;
3828
-            $this->fk_remise_except = $objp->fk_remise_except;
3829
-            $this->fk_product       = $objp->fk_product;
3830
-            $this->product_type     = $objp->product_type;
3831
-            $this->info_bits        = $objp->info_bits;
3805
+		$sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,';
3806
+		$sql.= ' cd.date_start, cd.date_end';
3807
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
3808
+		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3809
+		$sql.= ' WHERE cd.rowid = '.$rowid;
3810
+		$result = $this->db->query($sql);
3811
+		if ($result)
3812
+		{
3813
+			$objp = $this->db->fetch_object($result);
3814
+			$this->rowid            = $objp->rowid;
3815
+			$this->fk_commande      = $objp->fk_commande;
3816
+			$this->fk_parent_line   = $objp->fk_parent_line;
3817
+			$this->label            = $objp->custom_label;
3818
+			$this->desc             = $objp->description;
3819
+			$this->qty              = $objp->qty;
3820
+			$this->price            = $objp->price;
3821
+			$this->subprice         = $objp->subprice;
3822
+			$this->vat_src_code     = $objp->vat_src_code;
3823
+			$this->tva_tx           = $objp->tva_tx;
3824
+			$this->localtax1_tx		= $objp->localtax1_tx;
3825
+			$this->localtax2_tx		= $objp->localtax2_tx;
3826
+			$this->remise           = $objp->remise;
3827
+			$this->remise_percent   = $objp->remise_percent;
3828
+			$this->fk_remise_except = $objp->fk_remise_except;
3829
+			$this->fk_product       = $objp->fk_product;
3830
+			$this->product_type     = $objp->product_type;
3831
+			$this->info_bits        = $objp->info_bits;
3832 3832
 			$this->special_code		= $objp->special_code;
3833
-            $this->total_ht         = $objp->total_ht;
3834
-            $this->total_tva        = $objp->total_tva;
3835
-            $this->total_localtax1  = $objp->total_localtax1;
3836
-            $this->total_localtax2  = $objp->total_localtax2;
3837
-            $this->total_ttc        = $objp->total_ttc;
3833
+			$this->total_ht         = $objp->total_ht;
3834
+			$this->total_tva        = $objp->total_tva;
3835
+			$this->total_localtax1  = $objp->total_localtax1;
3836
+			$this->total_localtax2  = $objp->total_localtax2;
3837
+			$this->total_ttc        = $objp->total_ttc;
3838 3838
 			$this->fk_fournprice	= $objp->fk_fournprice;
3839 3839
 			$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
3840 3840
 			$this->pa_ht			= $marginInfos[0];
3841 3841
 			$this->marge_tx			= $marginInfos[1];
3842 3842
 			$this->marque_tx		= $marginInfos[2];
3843
-            $this->special_code		= $objp->special_code;
3844
-            $this->rang             = $objp->rang;
3843
+			$this->special_code		= $objp->special_code;
3844
+			$this->rang             = $objp->rang;
3845 3845
 
3846
-            $this->ref				= $objp->product_ref;      // deprecated
3847
-            $this->product_ref		= $objp->product_ref;
3848
-            $this->libelle			= $objp->product_libelle;  // deprecated
3849
-            $this->product_label	= $objp->product_libelle;
3850
-            $this->product_desc     = $objp->product_desc;
3851
-            $this->product_tobatch  = $objp->product_tobatch;
3852
-            $this->fk_unit          = $objp->fk_unit;
3846
+			$this->ref				= $objp->product_ref;      // deprecated
3847
+			$this->product_ref		= $objp->product_ref;
3848
+			$this->libelle			= $objp->product_libelle;  // deprecated
3849
+			$this->product_label	= $objp->product_libelle;
3850
+			$this->product_desc     = $objp->product_desc;
3851
+			$this->product_tobatch  = $objp->product_tobatch;
3852
+			$this->fk_unit          = $objp->fk_unit;
3853 3853
 
3854
-            $this->date_start       = $this->db->jdate($objp->date_start);
3855
-            $this->date_end         = $this->db->jdate($objp->date_end);
3854
+			$this->date_start       = $this->db->jdate($objp->date_start);
3855
+			$this->date_end         = $this->db->jdate($objp->date_end);
3856 3856
 
3857 3857
 			$this->fk_multicurrency			= $objp->fk_multicurrency;
3858 3858
 			$this->multicurrency_code		= $objp->multicurrency_code;
@@ -3861,38 +3861,38 @@  discard block
 block discarded – undo
3861 3861
 			$this->multicurrency_total_tva	= $objp->multicurrency_total_tva;
3862 3862
 			$this->multicurrency_total_ttc	= $objp->multicurrency_total_ttc;
3863 3863
 
3864
-            $this->db->free($result);
3865
-
3866
-            return 1;
3867
-        }
3868
-        else
3869
-        {
3870
-            $this->error = $this->db->lasterror();
3871
-            return -1;
3872
-        }
3873
-    }
3874
-
3875
-    /**
3876
-     * 	Delete line in database
3877
-     *
3878
-     *	@param      User	$user        	User that modify
3864
+			$this->db->free($result);
3865
+
3866
+			return 1;
3867
+		}
3868
+		else
3869
+		{
3870
+			$this->error = $this->db->lasterror();
3871
+			return -1;
3872
+		}
3873
+	}
3874
+
3875
+	/**
3876
+	 * 	Delete line in database
3877
+	 *
3878
+	 *	@param      User	$user        	User that modify
3879 3879
 	 *  @param      int		$notrigger	    0=launch triggers after, 1=disable triggers
3880
-     *	@return	 int  <0 si ko, >0 si ok
3881
-     */
3882
-    function delete($user=null, $notrigger=0)
3883
-    {
3884
-        global $conf, $user, $langs;
3880
+	 *	@return	 int  <0 si ko, >0 si ok
3881
+	 */
3882
+	function delete($user=null, $notrigger=0)
3883
+	{
3884
+		global $conf, $user, $langs;
3885 3885
 
3886 3886
 		$error=0;
3887 3887
 
3888
-	    $this->db->begin();
3888
+		$this->db->begin();
3889 3889
 
3890
-        $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid=".$this->rowid;
3890
+		$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid=".$this->rowid;
3891 3891
 
3892
-        dol_syslog("OrderLine::delete", LOG_DEBUG);
3893
-        $resql=$this->db->query($sql);
3894
-        if ($resql)
3895
-        {
3892
+		dol_syslog("OrderLine::delete", LOG_DEBUG);
3893
+		$resql=$this->db->query($sql);
3894
+		if ($resql)
3895
+		{
3896 3896
 			// Remove extrafields
3897 3897
 			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3898 3898
 			{
@@ -3907,63 +3907,63 @@  discard block
 block discarded – undo
3907 3907
 
3908 3908
 			if (! $error && ! $notrigger)
3909 3909
 			{
3910
-	            // Call trigger
3911
-	            $result=$this->call_trigger('LINEORDER_DELETE',$user);
3912
-	            if ($result < 0) $error++;
3913
-	            // End call triggers
3910
+				// Call trigger
3911
+				$result=$this->call_trigger('LINEORDER_DELETE',$user);
3912
+				if ($result < 0) $error++;
3913
+				// End call triggers
3914
+			}
3915
+
3916
+			if (!$error) {
3917
+				$this->db->commit();
3918
+				return 1;
3919
+			}
3920
+
3921
+			foreach($this->errors as $errmsg)
3922
+			{
3923
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3924
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
3914 3925
 			}
3926
+			$this->db->rollback();
3927
+			return -1*$error;
3928
+		}
3929
+		else
3930
+		{
3931
+			$this->error=$this->db->lasterror();
3932
+			return -1;
3933
+		}
3934
+	}
3915 3935
 
3916
-	        if (!$error) {
3917
-		        $this->db->commit();
3918
-		        return 1;
3919
-	        }
3920
-
3921
-	        foreach($this->errors as $errmsg)
3922
-	        {
3923
-		        dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3924
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
3925
-	        }
3926
-	        $this->db->rollback();
3927
-	        return -1*$error;
3928
-        }
3929
-        else
3930
-        {
3931
-            $this->error=$this->db->lasterror();
3932
-            return -1;
3933
-        }
3934
-    }
3935
-
3936
-    /**
3937
-     *	Insert line into database
3938
-     *
3939
-     *	@param      User	$user        	User that modify
3940
-     *	@param      int		$notrigger		1 = disable triggers
3941
-     *	@return		int						<0 if KO, >0 if OK
3942
-     */
3943
-    function insert($user=null, $notrigger=0)
3944
-    {
3945
-        global $langs, $conf;
3936
+	/**
3937
+	 *	Insert line into database
3938
+	 *
3939
+	 *	@param      User	$user        	User that modify
3940
+	 *	@param      int		$notrigger		1 = disable triggers
3941
+	 *	@return		int						<0 if KO, >0 if OK
3942
+	 */
3943
+	function insert($user=null, $notrigger=0)
3944
+	{
3945
+		global $langs, $conf;
3946 3946
 
3947 3947
 		$error=0;
3948 3948
 
3949
-        $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3949
+		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3950 3950
 
3951
-        dol_syslog(get_class($this)."::insert rang=".$this->rang);
3951
+		dol_syslog(get_class($this)."::insert rang=".$this->rang);
3952 3952
 
3953
-        // Clean parameters
3954
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3955
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3956
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3953
+		// Clean parameters
3954
+		if (empty($this->tva_tx)) $this->tva_tx=0;
3955
+		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3956
+		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3957 3957
 		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3958 3958
 		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3959
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3960
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3961
-        if (empty($this->rang)) $this->rang=0;
3962
-        if (empty($this->remise)) $this->remise=0;
3963
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3964
-        if (empty($this->info_bits)) $this->info_bits=0;
3965
-        if (empty($this->special_code)) $this->special_code=0;
3966
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3959
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
3960
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
3961
+		if (empty($this->rang)) $this->rang=0;
3962
+		if (empty($this->remise)) $this->remise=0;
3963
+		if (empty($this->remise_percent)) $this->remise_percent=0;
3964
+		if (empty($this->info_bits)) $this->info_bits=0;
3965
+		if (empty($this->special_code)) $this->special_code=0;
3966
+		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3967 3967
 		if (empty($this->pa_ht)) $this->pa_ht=0;
3968 3968
 
3969 3969
 		// if buy price not defined, define buyprice as configured in margin admin
@@ -3979,65 +3979,65 @@  discard block
 block discarded – undo
3979 3979
 			}
3980 3980
 		}
3981 3981
 
3982
-        // Check parameters
3983
-        if ($this->product_type < 0) return -1;
3982
+		// Check parameters
3983
+		if ($this->product_type < 0) return -1;
3984 3984
 
3985
-        $this->db->begin();
3985
+		$this->db->begin();
3986 3986
 
3987
-        // Insertion dans base de la ligne
3988
-        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
3989
-        $sql.= ' (fk_commande, fk_parent_line, label, description, qty, ';
3990
-        $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3991
-        $sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
3992
-        $sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
3993
-        $sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
3994
-	    $sql.= ' fk_unit';
3987
+		// Insertion dans base de la ligne
3988
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
3989
+		$sql.= ' (fk_commande, fk_parent_line, label, description, qty, ';
3990
+		$sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3991
+		$sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
3992
+		$sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
3993
+		$sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
3994
+		$sql.= ' fk_unit';
3995 3995
 		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3996 3996
 		$sql.= ')';
3997
-        $sql.= " VALUES (".$this->fk_commande.",";
3998
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3999
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4000
-        $sql.= " '".$this->db->escape($this->desc)."',";
4001
-        $sql.= " '".price2num($this->qty)."',";
4002
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4003
-        $sql.= " '".price2num($this->tva_tx)."',";
4004
-        $sql.= " '".price2num($this->localtax1_tx)."',";
4005
-        $sql.= " '".price2num($this->localtax2_tx)."',";
3997
+		$sql.= " VALUES (".$this->fk_commande.",";
3998
+		$sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3999
+		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4000
+		$sql.= " '".$this->db->escape($this->desc)."',";
4001
+		$sql.= " '".price2num($this->qty)."',";
4002
+		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4003
+		$sql.= " '".price2num($this->tva_tx)."',";
4004
+		$sql.= " '".price2num($this->localtax1_tx)."',";
4005
+		$sql.= " '".price2num($this->localtax2_tx)."',";
4006 4006
 		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
4007 4007
 		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
4008
-        $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
4009
-        $sql.= " '".$this->db->escape($this->product_type)."',";
4010
-        $sql.= " '".price2num($this->remise_percent)."',";
4011
-        $sql.= " ".($this->subprice!=''?"'".price2num($this->subprice)."'":"null").",";
4012
-        $sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").",";
4013
-        $sql.= " '".price2num($this->remise)."',";
4014
-        $sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
4015
-        $sql.= ' '.$this->special_code.',';
4016
-        $sql.= ' '.$this->rang.',';
4008
+		$sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
4009
+		$sql.= " '".$this->db->escape($this->product_type)."',";
4010
+		$sql.= " '".price2num($this->remise_percent)."',";
4011
+		$sql.= " ".($this->subprice!=''?"'".price2num($this->subprice)."'":"null").",";
4012
+		$sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").",";
4013
+		$sql.= " '".price2num($this->remise)."',";
4014
+		$sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
4015
+		$sql.= ' '.$this->special_code.',';
4016
+		$sql.= ' '.$this->rang.',';
4017 4017
 		$sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
4018 4018
 		$sql.= ' '.price2num($this->pa_ht).',';
4019
-        $sql.= " '".$this->db->escape($this->info_bits)."',";
4020
-        $sql.= " '".price2num($this->total_ht)."',";
4021
-        $sql.= " '".price2num($this->total_tva)."',";
4022
-        $sql.= " '".price2num($this->total_localtax1)."',";
4023
-        $sql.= " '".price2num($this->total_localtax2)."',";
4024
-        $sql.= " '".price2num($this->total_ttc)."',";
4025
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
4026
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").',';
4027
-	    $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4019
+		$sql.= " '".$this->db->escape($this->info_bits)."',";
4020
+		$sql.= " '".price2num($this->total_ht)."',";
4021
+		$sql.= " '".price2num($this->total_tva)."',";
4022
+		$sql.= " '".price2num($this->total_localtax1)."',";
4023
+		$sql.= " '".price2num($this->total_localtax2)."',";
4024
+		$sql.= " '".price2num($this->total_ttc)."',";
4025
+		$sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
4026
+		$sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").',';
4027
+		$sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4028 4028
 		$sql.= ", ".$this->fk_multicurrency;
4029 4029
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
4030 4030
 		$sql.= ", ".$this->multicurrency_subprice;
4031 4031
 		$sql.= ", ".$this->multicurrency_total_ht;
4032 4032
 		$sql.= ", ".$this->multicurrency_total_tva;
4033 4033
 		$sql.= ", ".$this->multicurrency_total_ttc;
4034
-        $sql.= ')';
4034
+		$sql.= ')';
4035 4035
 
4036
-        dol_syslog(get_class($this)."::insert", LOG_DEBUG);
4037
-        $resql=$this->db->query($sql);
4038
-        if ($resql)
4039
-        {
4040
-            $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4036
+		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
4037
+		$resql=$this->db->query($sql);
4038
+		if ($resql)
4039
+		{
4040
+			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4041 4041
 
4042 4042
 			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4043 4043
 			{
@@ -4049,42 +4049,42 @@  discard block
 block discarded – undo
4049 4049
 				}
4050 4050
 			}
4051 4051
 
4052
-            if (! $error && ! $notrigger)
4053
-            {
4054
-	            // Call trigger
4055
-	            $result=$this->call_trigger('LINEORDER_INSERT',$user);
4056
-	            if ($result < 0) $error++;
4057
-	            // End call triggers
4058
-            }
4059
-
4060
-	        if (!$error) {
4061
-		        $this->db->commit();
4062
-		        return 1;
4063
-	        }
4064
-
4065
-	        foreach($this->errors as $errmsg)
4066
-	        {
4067
-		        dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4068
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
4069
-	        }
4070
-	        $this->db->rollback();
4071
-	        return -1*$error;
4072
-        }
4073
-        else
4074
-        {
4075
-            $this->error=$this->db->error();
4076
-            $this->db->rollback();
4077
-            return -2;
4078
-        }
4079
-    }
4080
-
4081
-    /**
4082
-     *	Update the line object into db
4083
-     *
4084
-     *	@param      User	$user        	User that modify
4052
+			if (! $error && ! $notrigger)
4053
+			{
4054
+				// Call trigger
4055
+				$result=$this->call_trigger('LINEORDER_INSERT',$user);
4056
+				if ($result < 0) $error++;
4057
+				// End call triggers
4058
+			}
4059
+
4060
+			if (!$error) {
4061
+				$this->db->commit();
4062
+				return 1;
4063
+			}
4064
+
4065
+			foreach($this->errors as $errmsg)
4066
+			{
4067
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4068
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
4069
+			}
4070
+			$this->db->rollback();
4071
+			return -1*$error;
4072
+		}
4073
+		else
4074
+		{
4075
+			$this->error=$this->db->error();
4076
+			$this->db->rollback();
4077
+			return -2;
4078
+		}
4079
+	}
4080
+
4081
+	/**
4082
+	 *	Update the line object into db
4083
+	 *
4084
+	 *	@param      User	$user        	User that modify
4085 4085
 	 *	@param      int		$notrigger		1 = disable triggers
4086
-     *	@return		int		<0 si ko, >0 si ok
4087
-     */
4086
+	 *	@return		int		<0 si ko, >0 si ok
4087
+	 */
4088 4088
 	function update($user=null, $notrigger=0)
4089 4089
 	{
4090 4090
 		global $conf,$langs;
@@ -4107,7 +4107,7 @@  discard block
 block discarded – undo
4107 4107
 		if (empty($this->remise)) $this->remise=0;
4108 4108
 		if (empty($this->remise_percent)) $this->remise_percent=0;
4109 4109
 		if (empty($this->info_bits)) $this->info_bits=0;
4110
-        if (empty($this->special_code)) $this->special_code=0;
4110
+		if (empty($this->special_code)) $this->special_code=0;
4111 4111
 		if (empty($this->product_type)) $this->product_type=0;
4112 4112
 		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4113 4113
 		if (empty($this->pa_ht)) $this->pa_ht=0;
@@ -4153,7 +4153,7 @@  discard block
 block discarded – undo
4153 4153
 		$sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?$this->fk_fournprice:"null");
4154 4154
 		$sql.= " , buy_price_ht='".price2num($this->pa_ht)."'";
4155 4155
 		$sql.= " , info_bits=".$this->info_bits;
4156
-        $sql.= " , special_code=".$this->special_code;
4156
+		$sql.= " , special_code=".$this->special_code;
4157 4157
 		$sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4158 4158
 		$sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4159 4159
 		$sql.= " , product_type=".$this->product_type;
@@ -4163,9 +4163,9 @@  discard block
 block discarded – undo
4163 4163
 
4164 4164
 		// Multicurrency
4165 4165
 		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4166
-        $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4167
-        $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4168
-        $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4166
+		$sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4167
+		$sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4168
+		$sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4169 4169
 
4170 4170
 		$sql.= " WHERE rowid = ".$this->rowid;
4171 4171
 
@@ -4185,10 +4185,10 @@  discard block
 block discarded – undo
4185 4185
 
4186 4186
 			if (! $notrigger)
4187 4187
 			{
4188
-	            // Call trigger
4189
-	            $result=$this->call_trigger('LINEORDER_UPDATE',$user);
4190
-	            if ($result < 0) $error++;
4191
-	            // End call triggers
4188
+				// Call trigger
4189
+				$result=$this->call_trigger('LINEORDER_UPDATE',$user);
4190
+				if ($result < 0) $error++;
4191
+				// End call triggers
4192 4192
 			}
4193 4193
 
4194 4194
 			if (!$error) {
@@ -4212,42 +4212,42 @@  discard block
 block discarded – undo
4212 4212
 		}
4213 4213
 	}
4214 4214
 
4215
-    /**
4216
-     *	Update totals of order into database
4217
-     *
4218
-     *	@return		int		<0 if ko, >0 if ok
4219
-     */
4220
-    function update_total()
4221
-    {
4222
-        $this->db->begin();
4223
-
4224
-        // Clean parameters
4225
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
4226
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
4227
-
4228
-        // Mise a jour ligne en base
4229
-        $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4230
-        $sql.= " total_ht='".price2num($this->total_ht)."'";
4231
-        $sql.= ",total_tva='".price2num($this->total_tva)."'";
4232
-        $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
4233
-        $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
4234
-        $sql.= ",total_ttc='".price2num($this->total_ttc)."'";
4235
-        $sql.= " WHERE rowid = ".$this->rowid;
4236
-
4237
-        dol_syslog("OrderLine::update_total", LOG_DEBUG);
4238
-
4239
-        $resql=$this->db->query($sql);
4240
-        if ($resql)
4241
-        {
4242
-            $this->db->commit();
4243
-            return 1;
4244
-        }
4245
-        else
4246
-        {
4247
-            $this->error=$this->db->error();
4248
-            $this->db->rollback();
4249
-            return -2;
4250
-        }
4251
-    }
4215
+	/**
4216
+	 *	Update totals of order into database
4217
+	 *
4218
+	 *	@return		int		<0 if ko, >0 if ok
4219
+	 */
4220
+	function update_total()
4221
+	{
4222
+		$this->db->begin();
4223
+
4224
+		// Clean parameters
4225
+		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4226
+		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4227
+
4228
+		// Mise a jour ligne en base
4229
+		$sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4230
+		$sql.= " total_ht='".price2num($this->total_ht)."'";
4231
+		$sql.= ",total_tva='".price2num($this->total_tva)."'";
4232
+		$sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
4233
+		$sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
4234
+		$sql.= ",total_ttc='".price2num($this->total_ttc)."'";
4235
+		$sql.= " WHERE rowid = ".$this->rowid;
4236
+
4237
+		dol_syslog("OrderLine::update_total", LOG_DEBUG);
4238
+
4239
+		$resql=$this->db->query($sql);
4240
+		if ($resql)
4241
+		{
4242
+			$this->db->commit();
4243
+			return 1;
4244
+		}
4245
+		else
4246
+		{
4247
+			$this->error=$this->db->error();
4248
+			$this->db->rollback();
4249
+			return -2;
4250
+		}
4251
+	}
4252 4252
 }
4253 4253
 
Please login to merge, or discard this patch.
Spacing   +1035 added lines, -1035 removed lines patch added patch discarded remove patch
@@ -30,23 +30,23 @@  discard block
 block discarded – undo
30 30
  *  \ingroup    commande
31 31
  *  \brief      Fichier des classes de commandes
32 32
  */
33
-include_once DOL_DOCUMENT_ROOT .'/core/class/commonorder.class.php';
34
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php';
35
-require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php';
36
-require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php';
37
-require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php';
33
+include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
34
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
35
+require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
36
+require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
37
+require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
38 38
 
39 39
 /**
40 40
  *  Class to manage customers orders
41 41
  */
42 42
 class Commande extends CommonOrder
43 43
 {
44
-    public $element='commande';
45
-    public $table_element='commande';
44
+    public $element = 'commande';
45
+    public $table_element = 'commande';
46 46
     public $table_element_line = 'commandedet';
47 47
     public $class_element_line = 'OrderLine';
48 48
     public $fk_element = 'fk_commande';
49
-    protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
49
+    protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50 50
     public $picto = 'order';
51 51
 
52 52
     /**
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 	 * @see billed
75 75
 	 */
76 76
     public $facturee;
77
-    public $billed;		// billed or not
77
+    public $billed; // billed or not
78 78
 
79 79
     public $brouillon;
80 80
     public $cond_reglement_code;
@@ -113,25 +113,25 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public $availability;
115 115
 
116
-    public $demand_reason_id;   // Source reason. Why we receive order (after a phone campaign, ...)
116
+    public $demand_reason_id; // Source reason. Why we receive order (after a phone campaign, ...)
117 117
     public $demand_reason_code;
118
-    public $date;				// Date commande
118
+    public $date; // Date commande
119 119
 	/**
120 120
 	 * @deprecated
121 121
 	 * @see date
122 122
 	 */
123 123
     public $date_commande;
124
-    public $date_livraison;	    // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
124
+    public $date_livraison; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
125 125
     public $fk_remise_except;
126 126
     public $remise_percent;
127 127
     public $remise_absolue;
128 128
     public $info_bits;
129 129
     public $rang;
130 130
     public $special_code;
131
-    public $source;			    // Order mode. How we received order (by phone, by email, ...)
132
-    public $extraparams=array();
131
+    public $source; // Order mode. How we received order (by phone, by email, ...)
132
+    public $extraparams = array();
133 133
 
134
-    public $linked_objects=array();
134
+    public $linked_objects = array();
135 135
 
136 136
     public $user_author_id;
137 137
     public $user_valid;
@@ -209,31 +209,31 @@  discard block
 block discarded – undo
209 209
         global $langs, $conf;
210 210
         $langs->load("order");
211 211
 
212
-        if (! empty($conf->global->COMMANDE_ADDON))
212
+        if (!empty($conf->global->COMMANDE_ADDON))
213 213
         {
214
-        	$mybool=false;
214
+        	$mybool = false;
215 215
 
216 216
         	$file = $conf->global->COMMANDE_ADDON.".php";
217 217
 			$classname = $conf->global->COMMANDE_ADDON;
218 218
 
219 219
 			// Include file with class
220
-			$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
220
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
221 221
 			foreach ($dirmodels as $reldir)
222 222
 			{
223 223
                 $dir = dol_buildpath($reldir."core/modules/commande/");
224 224
 
225 225
                 // Load file with numbering class (if found)
226
-                $mybool|=@include_once $dir.$file;
226
+                $mybool |= @include_once $dir.$file;
227 227
             }
228 228
 
229
-            if (! $mybool)
229
+            if (!$mybool)
230 230
             {
231
-                dol_print_error('',"Failed to include file ".$file);
231
+                dol_print_error('', "Failed to include file ".$file);
232 232
                 return '';
233 233
             }
234 234
 
235 235
             $obj = new $classname();
236
-            $numref = $obj->getNextValue($soc,$this);
236
+            $numref = $obj->getNextValue($soc, $this);
237 237
 
238 238
             if ($numref != "")
239 239
             {
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
             }
242 242
             else
243 243
 			{
244
-				$this->error=$obj->error;
244
+				$this->error = $obj->error;
245 245
             	//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
246 246
             	return "";
247 247
             }
@@ -262,12 +262,12 @@  discard block
 block discarded – undo
262 262
      *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
263 263
      *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
264 264
      */
265
-    function valid($user, $idwarehouse=0, $notrigger=0)
265
+    function valid($user, $idwarehouse = 0, $notrigger = 0)
266 266
     {
267
-        global $conf,$langs;
267
+        global $conf, $langs;
268 268
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
269 269
 
270
-        $error=0;
270
+        $error = 0;
271 271
 
272 272
         // Protection
273 273
         if ($this->statut == self::STATUS_VALIDATED)
@@ -276,15 +276,15 @@  discard block
 block discarded – undo
276 276
             return 0;
277 277
         }
278 278
 
279
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
280
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
279
+        if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer))
280
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate))))
281 281
         {
282
-            $this->error='NotEnoughPermissions';
282
+            $this->error = 'NotEnoughPermissions';
283 283
             dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
284 284
             return -1;
285 285
         }
286 286
 
287
-        $now=dol_now();
287
+        $now = dol_now();
288 288
 
289 289
         $this->db->begin();
290 290
 
@@ -293,10 +293,10 @@  discard block
 block discarded – undo
293 293
         $soc->fetch($this->socid);
294 294
 
295 295
         // Class of company linked to order
296
-        $result=$soc->set_as_client();
296
+        $result = $soc->set_as_client();
297 297
 
298 298
         // Define new ref
299
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
299
+        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
300 300
         {
301 301
             $num = $this->getNextNumRef($soc);
302 302
         }
@@ -308,31 +308,31 @@  discard block
 block discarded – undo
308 308
 
309 309
         // Validate
310 310
         $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
311
-        $sql.= " SET ref = '".$num."',";
312
-        $sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
313
-        $sql.= " date_valid='".$this->db->idate($now)."',";
314
-        $sql.= " fk_user_valid = ".$user->id;
315
-        $sql.= " WHERE rowid = ".$this->id;
311
+        $sql .= " SET ref = '".$num."',";
312
+        $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
313
+        $sql .= " date_valid='".$this->db->idate($now)."',";
314
+        $sql .= " fk_user_valid = ".$user->id;
315
+        $sql .= " WHERE rowid = ".$this->id;
316 316
 
317 317
         dol_syslog(get_class($this)."::valid()", LOG_DEBUG);
318
-        $resql=$this->db->query($sql);
319
-        if (! $resql)
318
+        $resql = $this->db->query($sql);
319
+        if (!$resql)
320 320
         {
321 321
             dol_print_error($this->db);
322
-            $this->error=$this->db->lasterror();
322
+            $this->error = $this->db->lasterror();
323 323
             $error++;
324 324
         }
325 325
 
326
-        if (! $error)
326
+        if (!$error)
327 327
         {
328 328
             // If stock is incremented on validate order, we must increment it
329
-            if ($result >= 0 && ! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
329
+            if ($result >= 0 && !empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
330 330
             {
331 331
                 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
332 332
                 $langs->load("agenda");
333 333
 
334 334
                 // Loop on each line
335
-                $cpt=count($this->lines);
335
+                $cpt = count($this->lines);
336 336
                 for ($i = 0; $i < $cpt; $i++)
337 337
                 {
338 338
                     if ($this->lines[$i]->fk_product > 0)
@@ -340,11 +340,11 @@  discard block
 block discarded – undo
340 340
                         $mouvP = new MouvementStock($this->db);
341 341
 						$mouvP->origin = &$this;
342 342
                         // We decrement stock of product (and sub-products)
343
-                        $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr",$num));
343
+                        $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num));
344 344
                         if ($result < 0)
345 345
                         {
346 346
                         	$error++;
347
-                        	$this->error=$mouvP->error;
347
+                        	$this->error = $mouvP->error;
348 348
                         }
349 349
                     }
350 350
                     if ($error) break;
@@ -352,15 +352,15 @@  discard block
 block discarded – undo
352 352
             }
353 353
         }
354 354
 
355
-        if (! $error && ! $notrigger)
355
+        if (!$error && !$notrigger)
356 356
         {
357 357
             // Call trigger
358
-            $result=$this->call_trigger('ORDER_VALIDATE',$user);
358
+            $result = $this->call_trigger('ORDER_VALIDATE', $user);
359 359
             if ($result < 0) $error++;
360 360
             // End call triggers
361 361
         }
362 362
 
363
-        if (! $error)
363
+        if (!$error)
364 364
         {
365 365
             $this->oldref = $this->ref;
366 366
 
@@ -381,13 +381,13 @@  discard block
 block discarded – undo
381 381
                     {
382 382
                         dol_syslog("Rename ok");
383 383
                         // Rename docs starting with $oldref with $newref
384
-                        $listoffiles=dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
385
-                        foreach($listoffiles as $fileentry)
384
+                        $listoffiles = dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
385
+                        foreach ($listoffiles as $fileentry)
386 386
                         {
387
-                        	$dirsource=$fileentry['name'];
388
-                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
389
-                        	$dirsource=$fileentry['path'].'/'.$dirsource;
390
-                        	$dirdest=$fileentry['path'].'/'.$dirdest;
387
+                        	$dirsource = $fileentry['name'];
388
+                        	$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
389
+                        	$dirsource = $fileentry['path'].'/'.$dirsource;
390
+                        	$dirdest = $fileentry['path'].'/'.$dirdest;
391 391
                         	@rename($dirsource, $dirdest);
392 392
                         }
393 393
                     }
@@ -396,13 +396,13 @@  discard block
 block discarded – undo
396 396
         }
397 397
 
398 398
         // Set new ref and current status
399
-        if (! $error)
399
+        if (!$error)
400 400
         {
401 401
             $this->ref = $num;
402 402
             $this->statut = self::STATUS_VALIDATED;
403 403
         }
404 404
 
405
-        if (! $error)
405
+        if (!$error)
406 406
         {
407 407
             $this->db->commit();
408 408
             return 1;
@@ -421,11 +421,11 @@  discard block
 block discarded – undo
421 421
      *	@param	int		$idwarehouse	Id warehouse to use for stock change.
422 422
      *	@return	int						<0 if KO, >0 if OK
423 423
      */
424
-    function set_draft($user, $idwarehouse=-1)
424
+    function set_draft($user, $idwarehouse = -1)
425 425
     {
426
-        global $conf,$langs;
426
+        global $conf, $langs;
427 427
 
428
-        $error=0;
428
+        $error = 0;
429 429
 
430 430
         // Protection
431 431
         if ($this->statut <= self::STATUS_DRAFT)
@@ -433,31 +433,31 @@  discard block
 block discarded – undo
433 433
             return 0;
434 434
         }
435 435
 
436
-        if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
437
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
436
+        if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer))
437
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate))))
438 438
         {
439
-            $this->error='Permission denied';
439
+            $this->error = 'Permission denied';
440 440
             return -1;
441 441
         }
442 442
 
443 443
         $this->db->begin();
444 444
 
445 445
         $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
446
-        $sql.= " SET fk_statut = ".self::STATUS_DRAFT;
447
-        $sql.= " WHERE rowid = ".$this->id;
446
+        $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
447
+        $sql .= " WHERE rowid = ".$this->id;
448 448
 
449 449
         dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
450 450
         if ($this->db->query($sql))
451 451
         {
452 452
             // If stock is decremented on validate order, we must reincrement it
453
-            if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
453
+            if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
454 454
             {
455 455
                 $result = 0;
456 456
 
457 457
                 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
458 458
                 $langs->load("agenda");
459 459
 
460
-                $num=count($this->lines);
460
+                $num = count($this->lines);
461 461
                 for ($i = 0; $i < $num; $i++)
462 462
                 {
463 463
                     if ($this->lines[$i]->fk_product > 0)
@@ -465,30 +465,30 @@  discard block
 block discarded – undo
465 465
                         $mouvP = new MouvementStock($this->db);
466 466
                         $mouvP->origin = &$this;
467 467
                         // We increment stock of product (and sub-products)
468
-                        $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr",$this->ref));
469
-                        if ($result < 0) { $error++; $this->error=$mouvP->error; break; }
468
+                        $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr", $this->ref));
469
+                        if ($result < 0) { $error++; $this->error = $mouvP->error; break; }
470 470
                     }
471 471
                 }
472 472
             }
473 473
 
474 474
             if (!$error) {
475 475
             	// Call trigger
476
-            	$result=$this->call_trigger('ORDER_UNVALIDATE',$user);
476
+            	$result = $this->call_trigger('ORDER_UNVALIDATE', $user);
477 477
             	if ($result < 0) $error++;
478 478
             }
479 479
 
480 480
             if (!$error) {
481
-           		$this->statut=self::STATUS_DRAFT;
481
+           		$this->statut = self::STATUS_DRAFT;
482 482
             	$this->db->commit();
483 483
             	return 1;
484
-            }else {
484
+            } else {
485 485
             	$this->db->rollback();
486 486
             	return -1;
487 487
             }
488 488
         }
489 489
         else
490 490
         {
491
-            $this->error=$this->db->error();
491
+            $this->error = $this->db->error();
492 492
             $this->db->rollback();
493 493
             return -1;
494 494
         }
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
      */
505 505
     function set_reopen($user)
506 506
     {
507
-        $error=0;
507
+        $error = 0;
508 508
 
509 509
         if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED)
510 510
         {
@@ -515,26 +515,26 @@  discard block
 block discarded – undo
515 515
         $this->db->begin();
516 516
 
517 517
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
518
-        $sql.= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0';
519
-        $sql.= ' WHERE rowid = '.$this->id;
518
+        $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0';
519
+        $sql .= ' WHERE rowid = '.$this->id;
520 520
 
521 521
         dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
522 522
         $resql = $this->db->query($sql);
523 523
         if ($resql)
524 524
         {
525 525
             // Call trigger
526
-            $result=$this->call_trigger('ORDER_REOPEN',$user);
526
+            $result = $this->call_trigger('ORDER_REOPEN', $user);
527 527
             if ($result < 0) $error++;
528 528
             // End call triggers
529 529
         }
530 530
         else
531 531
         {
532 532
             $error++;
533
-            $this->error=$this->db->lasterror();
533
+            $this->error = $this->db->lasterror();
534 534
             dol_print_error($this->db);
535 535
         }
536 536
 
537
-        if (! $error)
537
+        if (!$error)
538 538
         {
539 539
         	$this->statut = self::STATUS_VALIDATED;
540 540
         	$this->billed = 0;
@@ -545,13 +545,13 @@  discard block
 block discarded – undo
545 545
         }
546 546
         else
547 547
         {
548
-	        foreach($this->errors as $errmsg)
548
+	        foreach ($this->errors as $errmsg)
549 549
 	        {
550 550
 		        dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
551
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
551
+		        $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
552 552
 	        }
553 553
 	        $this->db->rollback();
554
-	        return -1*$error;
554
+	        return -1 * $error;
555 555
         }
556 556
     }
557 557
 
@@ -565,31 +565,31 @@  discard block
 block discarded – undo
565 565
     {
566 566
         global $conf;
567 567
 
568
-        $error=0;
568
+        $error = 0;
569 569
 
570
-        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
571
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))
570
+        if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer))
571
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))
572 572
         {
573 573
             $this->db->begin();
574 574
 
575
-            $now=dol_now();
575
+            $now = dol_now();
576 576
 
577 577
             $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
578
-            $sql.= ' SET fk_statut = '.self::STATUS_CLOSED.',';
579
-            $sql.= ' fk_user_cloture = '.$user->id.',';
580
-            $sql.= " date_cloture = '".$this->db->idate($now)."'";
581
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
578
+            $sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
579
+            $sql .= ' fk_user_cloture = '.$user->id.',';
580
+            $sql .= " date_cloture = '".$this->db->idate($now)."'";
581
+            $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
582 582
 
583 583
             if ($this->db->query($sql))
584 584
             {
585 585
 	            // Call trigger
586
-	            $result=$this->call_trigger('ORDER_CLOSE',$user);
586
+	            $result = $this->call_trigger('ORDER_CLOSE', $user);
587 587
 	            if ($result < 0) $error++;
588 588
 	            // End call triggers
589 589
 
590
-                if (! $error)
590
+                if (!$error)
591 591
                 {
592
-                	$this->statut=self::STATUS_CLOSED;
592
+                	$this->statut = self::STATUS_CLOSED;
593 593
 
594 594
                     $this->db->commit();
595 595
                     return 1;
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
             }
603 603
             else
604 604
             {
605
-                $this->error=$this->db->lasterror();
605
+                $this->error = $this->db->lasterror();
606 606
 
607 607
                 $this->db->rollback();
608 608
                 return -1;
@@ -617,74 +617,74 @@  discard block
 block discarded – undo
617 617
      *	@param	int		$idwarehouse	Id warehouse to use for stock change.
618 618
      *	@return	int						<0 if KO, >0 if OK
619 619
      */
620
-	function cancel($idwarehouse=-1)
620
+	function cancel($idwarehouse = -1)
621 621
 	{
622
-		global $conf,$user,$langs;
622
+		global $conf, $user, $langs;
623 623
 
624
-		$error=0;
624
+		$error = 0;
625 625
 
626 626
 		$this->db->begin();
627 627
 
628 628
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
629
-		$sql.= " SET fk_statut = ".self::STATUS_CANCELED;
630
-		$sql.= " WHERE rowid = ".$this->id;
631
-		$sql.= " AND fk_statut = ".self::STATUS_VALIDATED;
629
+		$sql .= " SET fk_statut = ".self::STATUS_CANCELED;
630
+		$sql .= " WHERE rowid = ".$this->id;
631
+		$sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
632 632
 
633 633
 		dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
634 634
 		if ($this->db->query($sql))
635 635
 		{
636 636
 			// If stock is decremented on validate order, we must reincrement it
637
-			if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
637
+			if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
638 638
 			{
639 639
 				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
640 640
 				$langs->load("agenda");
641 641
 
642
-				$num=count($this->lines);
642
+				$num = count($this->lines);
643 643
 				for ($i = 0; $i < $num; $i++)
644 644
 				{
645 645
 					if ($this->lines[$i]->fk_product > 0)
646 646
 					{
647 647
 						$mouvP = new MouvementStock($this->db);
648 648
 						// We increment stock of product (and sub-products)
649
-						$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr",$this->ref));  // price is 0, we don't want WAP to be changed
649
+						$result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed
650 650
 						if ($result < 0)
651 651
 						{
652 652
 							$error++;
653
-							$this->error=$mouvP->error;
653
+							$this->error = $mouvP->error;
654 654
 							break;
655 655
 						}
656 656
 					}
657 657
 				}
658 658
 			}
659 659
 
660
-			if (! $error)
660
+			if (!$error)
661 661
 			{
662 662
 	            // Call trigger
663
-	            $result=$this->call_trigger('ORDER_CANCEL',$user);
663
+	            $result = $this->call_trigger('ORDER_CANCEL', $user);
664 664
 	            if ($result < 0) $error++;
665 665
 	            // End call triggers
666 666
 			}
667 667
 
668
-			if (! $error)
668
+			if (!$error)
669 669
 			{
670
-				$this->statut=self::STATUS_CANCELED;
670
+				$this->statut = self::STATUS_CANCELED;
671 671
 				$this->db->commit();
672 672
 				return 1;
673 673
 			}
674 674
 			else
675 675
 			{
676
-				foreach($this->errors as $errmsg)
676
+				foreach ($this->errors as $errmsg)
677 677
 				{
678 678
 					dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
679
-					$this->error.=($this->error?', '.$errmsg:$errmsg);
679
+					$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
680 680
 				}
681 681
 				$this->db->rollback();
682
-				return -1*$error;
682
+				return -1 * $error;
683 683
 			}
684 684
 		}
685 685
 		else
686 686
 		{
687
-			$this->error=$this->db->error();
687
+			$this->error = $this->db->error();
688 688
 			$this->db->rollback();
689 689
 			return -1;
690 690
 		}
@@ -698,19 +698,19 @@  discard block
 block discarded – undo
698 698
      *	@param		int	    $notrigger	Disable all triggers
699 699
      *	@return 	int			        <0 if KO, >0 if OK
700 700
      */
701
-    function create($user, $notrigger=0)
701
+    function create($user, $notrigger = 0)
702 702
     {
703
-        global $conf,$langs;
704
-        $error=0;
703
+        global $conf, $langs;
704
+        $error = 0;
705 705
 
706 706
         // Clean parameters
707
-        $this->brouillon = 1;		// set command as draft
707
+        $this->brouillon = 1; // set command as draft
708 708
 
709 709
 		// $date_commande is deprecated
710 710
         $date = ($this->date_commande ? $this->date_commande : $this->date);
711 711
 
712 712
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
713
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
713
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
714 714
 		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
715 715
 		if (empty($this->fk_multicurrency))
716 716
 		{
@@ -722,99 +722,99 @@  discard block
 block discarded – undo
722 722
         dol_syslog(get_class($this)."::create user=".$user->id);
723 723
 
724 724
         // Check parameters
725
-    	if (! empty($this->ref))	// We check that ref is not already used
725
+    	if (!empty($this->ref))	// We check that ref is not already used
726 726
     	{
727
-    		$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
727
+    		$result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
728 728
     		if ($result > 0)
729 729
     		{
730
-    			$this->error='ErrorRefAlreadyExists';
731
-    			dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
730
+    			$this->error = 'ErrorRefAlreadyExists';
731
+    			dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
732 732
     			$this->db->rollback();
733 733
     			return -1;
734 734
     		}
735 735
     	}
736 736
 
737 737
         $soc = new Societe($this->db);
738
-        $result=$soc->fetch($this->socid);
738
+        $result = $soc->fetch($this->socid);
739 739
         if ($result < 0)
740 740
         {
741
-            $this->error="Failed to fetch company";
741
+            $this->error = "Failed to fetch company";
742 742
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
743 743
             return -2;
744 744
         }
745
-        if (! empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
745
+        if (!empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
746 746
         {
747
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Source"));
747
+            $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("Source"));
748 748
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
749 749
             return -1;
750 750
         }
751 751
 
752
-        $now=dol_now();
752
+        $now = dol_now();
753 753
 
754 754
         $this->db->begin();
755 755
 
756 756
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
757
-        $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
758
-        $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
759
-        $sql.= ", fk_shipping_method";
760
-        $sql.= ", fk_warehouse";
761
-        $sql.= ", remise_absolue, remise_percent";
762
-        $sql.= ", fk_incoterms, location_incoterms";
763
-        $sql.= ", entity";
764
-        $sql.= ", fk_multicurrency";
765
-        $sql.= ", multicurrency_code";
766
-        $sql.= ", multicurrency_tx";
767
-        $sql.= ")";
768
-        $sql.= " VALUES ('(PROV)',".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
769
-        $sql.= ", ".($this->fk_project>0?$this->fk_project:"null");
770
-        $sql.= ", '".$this->db->idate($date)."'";
771
-        $sql.= ", ".($this->source>=0 && $this->source != '' ?$this->db->escape($this->source):'null');
772
-        $sql.= ", '".$this->db->escape($this->note_private)."'";
773
-        $sql.= ", '".$this->db->escape($this->note_public)."'";
774
-        $sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
775
-        $sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
776
-        $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
777
-        $sql.= ", '".$this->db->escape($this->modelpdf)."'";
778
-        $sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null");
779
-        $sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null");
780
-        $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
781
-        $sql.= ", ".($this->availability_id>0?$this->availability_id:"null");
782
-        $sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null");
783
-        $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
784
-        $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL');
785
-        $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
786
-        $sql.= ", ".($this->warehouse_id>0?$this->warehouse_id:'NULL');
787
-        $sql.= ", ".($this->remise_absolue>0?$this->db->escape($this->remise_absolue):'NULL');
788
-        $sql.= ", ".($this->remise_percent>0?$this->db->escape($this->remise_percent):0);
789
-        $sql.= ", ".(int) $this->fk_incoterms;
790
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
791
-        $sql.= ", ".$conf->entity;
792
-		$sql.= ", ".(int) $this->fk_multicurrency;
793
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
794
-		$sql.= ", ".(double) $this->multicurrency_tx;
795
-        $sql.= ")";
757
+        $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
758
+        $sql .= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
759
+        $sql .= ", fk_shipping_method";
760
+        $sql .= ", fk_warehouse";
761
+        $sql .= ", remise_absolue, remise_percent";
762
+        $sql .= ", fk_incoterms, location_incoterms";
763
+        $sql .= ", entity";
764
+        $sql .= ", fk_multicurrency";
765
+        $sql .= ", multicurrency_code";
766
+        $sql .= ", multicurrency_tx";
767
+        $sql .= ")";
768
+        $sql .= " VALUES ('(PROV)',".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
769
+        $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
770
+        $sql .= ", '".$this->db->idate($date)."'";
771
+        $sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape($this->source) : 'null');
772
+        $sql .= ", '".$this->db->escape($this->note_private)."'";
773
+        $sql .= ", '".$this->db->escape($this->note_public)."'";
774
+        $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
775
+        $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
776
+        $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
777
+        $sql .= ", '".$this->db->escape($this->modelpdf)."'";
778
+        $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : "null");
779
+        $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "null");
780
+        $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
781
+        $sql .= ", ".($this->availability_id > 0 ? $this->availability_id : "null");
782
+        $sql .= ", ".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null");
783
+        $sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null");
784
+        $sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : 'NULL');
785
+        $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
786
+        $sql .= ", ".($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
787
+        $sql .= ", ".($this->remise_absolue > 0 ? $this->db->escape($this->remise_absolue) : 'NULL');
788
+        $sql .= ", ".($this->remise_percent > 0 ? $this->db->escape($this->remise_percent) : 0);
789
+        $sql .= ", ".(int) $this->fk_incoterms;
790
+        $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
791
+        $sql .= ", ".$conf->entity;
792
+		$sql .= ", ".(int) $this->fk_multicurrency;
793
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
794
+		$sql .= ", ".(double) $this->multicurrency_tx;
795
+        $sql .= ")";
796 796
 
797 797
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
798
-        $resql=$this->db->query($sql);
798
+        $resql = $this->db->query($sql);
799 799
         if ($resql)
800 800
         {
801 801
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
802 802
 
803 803
             if ($this->id)
804 804
             {
805
-                $fk_parent_line=0;
806
-                $num=count($this->lines);
805
+                $fk_parent_line = 0;
806
+                $num = count($this->lines);
807 807
 
808 808
                 /*
809 809
                  *  Insert products details into db
810 810
                  */
811
-                for ($i=0;$i<$num;$i++)
811
+                for ($i = 0; $i < $num; $i++)
812 812
                 {
813 813
                 	$line = $this->lines[$i];
814 814
 
815 815
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
816 816
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
817
-                	if (! is_object($line)) $line = (object) $line;
817
+                	if (!is_object($line)) $line = (object) $line;
818 818
 
819 819
                     // Reset fk_parent_line for no child products and special product
820 820
                     if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
@@ -852,7 +852,7 @@  discard block
 block discarded – undo
852 852
                     {
853 853
                     	if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER)
854 854
                     	{
855
-                        	$this->error=$this->db->lasterror();
855
+                        	$this->error = $this->db->lasterror();
856 856
                         	dol_print_error($this->db);
857 857
                     	}
858 858
                         $this->db->rollback();
@@ -865,8 +865,8 @@  discard block
 block discarded – undo
865 865
                 }
866 866
 
867 867
                 // update ref
868
-                $initialref='(PROV'.$this->id.')';
869
-                if (! empty($this->ref)) $initialref=$this->ref;
868
+                $initialref = '(PROV'.$this->id.')';
869
+                if (!empty($this->ref)) $initialref = $this->ref;
870 870
 
871 871
                 $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
872 872
                 if ($this->db->query($sql))
@@ -876,16 +876,16 @@  discard block
 block discarded – undo
876 876
                     	$this->ref = $initialref;
877 877
 
878 878
                         // Add object linked
879
-                        if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
879
+                        if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects))
880 880
                         {
881
-                        	foreach($this->linked_objects as $origin => $tmp_origin_id)
881
+                        	foreach ($this->linked_objects as $origin => $tmp_origin_id)
882 882
                         	{
883 883
                         	    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
884 884
                         	    {
885
-                        	        foreach($tmp_origin_id as $origin_id)
885
+                        	        foreach ($tmp_origin_id as $origin_id)
886 886
                         	        {
887 887
                         	            $ret = $this->add_object_linked($origin, $origin_id);
888
-                        	            if (! $ret)
888
+                        	            if (!$ret)
889 889
                         	            {
890 890
                         	                dol_print_error($this->db);
891 891
                         	                $error++;
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
                         	    {
897 897
                         	        $origin_id = $tmp_origin_id;
898 898
                         	        $ret = $this->add_object_linked($origin, $origin_id);
899
-                        	        if (! $ret)
899
+                        	        if (!$ret)
900 900
                         	        {
901 901
                         	            dol_print_error($this->db);
902 902
                         	            $error++;
@@ -905,13 +905,13 @@  discard block
 block discarded – undo
905 905
                         	}
906 906
                         }
907 907
 
908
-            			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
908
+            			if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id))   // Get contact from origin object
909 909
             			{
910 910
             				$originforcontact = $this->origin;
911 911
             				$originidforcontact = $this->origin_id;
912 912
                 		    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
913 913
                 		    {
914
-                		        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
914
+                		        require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
915 915
                 		        $exp = new Expedition($db);
916 916
                 		        $exp->fetch($this->origin_id);
917 917
                 		        $exp->fetchObjectLinked();
@@ -928,36 +928,36 @@  discard block
 block discarded – undo
928 928
                 		    }
929 929
 
930 930
                 		    $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
931
-                		    $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
931
+                		    $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
932 932
 
933 933
                 		    $resqlcontact = $this->db->query($sqlcontact);
934 934
                 		    if ($resqlcontact)
935 935
                 		    {
936
-                		        while($objcontact = $this->db->fetch_object($resqlcontact))
936
+                		        while ($objcontact = $this->db->fetch_object($resqlcontact))
937 937
                 		        {
938 938
         					        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
939
-                		            $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
939
+                		            $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
940 940
                 		        }
941 941
                 		    }
942 942
                 		    else dol_print_error($resqlcontact);
943 943
                 		}
944 944
                     }
945 945
 
946
-                    if (! $error)
946
+                    if (!$error)
947 947
                     {
948
-                   		$result=$this->insertExtraFields();
948
+                   		$result = $this->insertExtraFields();
949 949
                    		if ($result < 0) $error++;
950 950
                     }
951 951
 
952
-                    if (! $error && ! $notrigger)
952
+                    if (!$error && !$notrigger)
953 953
                     {
954 954
 			            // Call trigger
955
-			            $result=$this->call_trigger('ORDER_CREATE',$user);
955
+			            $result = $this->call_trigger('ORDER_CREATE', $user);
956 956
 			            if ($result < 0) $error++;
957 957
 			            // End call triggers
958 958
                     }
959 959
 
960
-	                if (! $error)
960
+	                if (!$error)
961 961
 	                {
962 962
 		                $this->db->commit();
963 963
 		                return $this->id;
@@ -965,12 +965,12 @@  discard block
 block discarded – undo
965 965
 	                else
966 966
 					{
967 967
 	                	$this->db->rollback();
968
-	                	return -1*$error;
968
+	                	return -1 * $error;
969 969
 					}
970 970
                 }
971 971
                 else
972 972
 				{
973
-					$this->error=$this->db->lasterror();
973
+					$this->error = $this->db->lasterror();
974 974
                     $this->db->rollback();
975 975
                     return -1;
976 976
                 }
@@ -991,70 +991,70 @@  discard block
 block discarded – undo
991 991
      *	@param		int			$socid			Id of thirdparty
992 992
      *	@return		int							New id of clone
993 993
      */
994
-    function createFromClone($socid=0)
994
+    function createFromClone($socid = 0)
995 995
     {
996
-        global $user,$hookmanager;
996
+        global $user, $hookmanager;
997 997
 
998
-        $error=0;
998
+        $error = 0;
999 999
 
1000 1000
         $this->context['createfromclone'] = 'createfromclone';
1001 1001
 
1002 1002
         $this->db->begin();
1003 1003
 
1004 1004
 		// get lines so they will be clone
1005
-		foreach($this->lines as $line)
1005
+		foreach ($this->lines as $line)
1006 1006
 			$line->fetch_optionals($line->rowid);
1007 1007
 
1008 1008
         // Load source object
1009 1009
         $objFrom = clone $this;
1010 1010
 
1011 1011
         // Change socid if needed
1012
-        if (! empty($socid) && $socid != $this->socid)
1012
+        if (!empty($socid) && $socid != $this->socid)
1013 1013
         {
1014 1014
             $objsoc = new Societe($this->db);
1015 1015
 
1016
-            if ($objsoc->fetch($socid)>0)
1016
+            if ($objsoc->fetch($socid) > 0)
1017 1017
             {
1018
-                $this->socid 				= $objsoc->id;
1019
-                $this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1020
-                $this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1021
-                $this->fk_project			= '';
1022
-                $this->fk_delivery_address	= '';
1018
+                $this->socid = $objsoc->id;
1019
+                $this->cond_reglement_id	= (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1020
+                $this->mode_reglement_id	= (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1021
+                $this->fk_project = '';
1022
+                $this->fk_delivery_address = '';
1023 1023
             }
1024 1024
 
1025 1025
             // TODO Change product price if multi-prices
1026 1026
         }
1027 1027
 
1028
-        $this->id=0;
1028
+        $this->id = 0;
1029 1029
 		$this->ref = '';
1030
-        $this->statut=self::STATUS_DRAFT;
1030
+        $this->statut = self::STATUS_DRAFT;
1031 1031
 
1032 1032
         // Clear fields
1033 1033
         $this->user_author_id     = $user->id;
1034 1034
         $this->user_valid         = '';
1035
-		$this->date				  = dol_now();
1036
-		$this->date_commande	  = dol_now();
1035
+		$this->date = dol_now();
1036
+		$this->date_commande = dol_now();
1037 1037
         $this->date_creation      = '';
1038 1038
         $this->date_validation    = '';
1039 1039
         $this->ref_client         = '';
1040 1040
 
1041 1041
         // Create clone
1042
-        $result=$this->create($user);
1042
+        $result = $this->create($user);
1043 1043
         if ($result < 0) $error++;
1044 1044
 
1045
-        if (! $error)
1045
+        if (!$error)
1046 1046
         {
1047 1047
             // Hook of thirdparty module
1048 1048
             if (is_object($hookmanager))
1049 1049
             {
1050
-                $parameters=array('objFrom'=>$objFrom);
1051
-                $action='';
1052
-                $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1050
+                $parameters = array('objFrom'=>$objFrom);
1051
+                $action = '';
1052
+                $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1053 1053
                 if ($reshook < 0) $error++;
1054 1054
             }
1055 1055
 
1056 1056
             // Call trigger
1057
-            $result=$this->call_trigger('ORDER_CLONE',$user);
1057
+            $result = $this->call_trigger('ORDER_CLONE', $user);
1058 1058
             if ($result < 0) $error++;
1059 1059
             // End call triggers
1060 1060
         }
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
         unset($this->context['createfromclone']);
1063 1063
 
1064 1064
         // End
1065
-        if (! $error)
1065
+        if (!$error)
1066 1066
         {
1067 1067
             $this->db->commit();
1068 1068
             return $this->id;
@@ -1083,17 +1083,17 @@  discard block
 block discarded – undo
1083 1083
      */
1084 1084
     function createFromProposal($object)
1085 1085
     {
1086
-        global $conf,$user,$hookmanager;
1086
+        global $conf, $user, $hookmanager;
1087 1087
 
1088 1088
 		dol_include_once('/core/class/extrafields.class.php');
1089 1089
 
1090
-        $error=0;
1090
+        $error = 0;
1091 1091
 
1092 1092
 
1093 1093
         $this->date_commande = dol_now();
1094 1094
         $this->source = 0;
1095 1095
 
1096
-        $num=count($object->lines);
1096
+        $num = count($object->lines);
1097 1097
         for ($i = 0; $i < $num; $i++)
1098 1098
         {
1099 1099
             $line = new OrderLine($this->db);
@@ -1116,12 +1116,12 @@  discard block
 block discarded – undo
1116 1116
             $line->rang              = $object->lines[$i]->rang;
1117 1117
             $line->special_code      = $object->lines[$i]->special_code;
1118 1118
             $line->fk_parent_line    = $object->lines[$i]->fk_parent_line;
1119
-	        $line->fk_unit			 = $object->lines[$i]->fk_unit;
1119
+	        $line->fk_unit = $object->lines[$i]->fk_unit;
1120 1120
 
1121
-            $line->date_start      	= $object->lines[$i]->date_start;
1122
-            $line->date_end    		= $object->lines[$i]->date_end;
1121
+            $line->date_start = $object->lines[$i]->date_start;
1122
+            $line->date_end = $object->lines[$i]->date_end;
1123 1123
 
1124
-			$line->fk_fournprice	= $object->lines[$i]->fk_fournprice;
1124
+			$line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1125 1125
 			$marginInfos			= getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1126 1126
 			$line->pa_ht			= $marginInfos[0];
1127 1127
 			$line->marge_tx			= $marginInfos[1];
@@ -1129,7 +1129,7 @@  discard block
 block discarded – undo
1129 1129
 
1130 1130
             // get extrafields from original line
1131 1131
 			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
1132
-			foreach($object->lines[$i]->array_options as $options_key => $value)
1132
+			foreach ($object->lines[$i]->array_options as $options_key => $value)
1133 1133
 				$line->array_options[$options_key] = $value;
1134 1134
 
1135 1135
 			$this->lines[$i] = $line;
@@ -1151,8 +1151,8 @@  discard block
 block discarded – undo
1151 1151
         $this->note_private         = $object->note_private;
1152 1152
         $this->note_public          = $object->note_public;
1153 1153
 
1154
-        $this->origin				= $object->element;
1155
-        $this->origin_id			= $object->id;
1154
+        $this->origin = $object->element;
1155
+        $this->origin_id = $object->id;
1156 1156
 
1157 1157
         // get extrafields from original line
1158 1158
 		$object->fetch_optionals($object->id);
@@ -1160,14 +1160,14 @@  discard block
 block discarded – undo
1160 1160
 		$e = new ExtraFields($this->db);
1161 1161
 		$element_extrafields = $e->fetch_name_optionals_label($this->element);
1162 1162
 
1163
-		foreach($object->array_options as $options_key => $value) {
1164
-			if(array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)){
1163
+		foreach ($object->array_options as $options_key => $value) {
1164
+			if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) {
1165 1165
 				$this->array_options[$options_key] = $value;
1166 1166
 			}
1167 1167
 		}
1168 1168
         // Possibility to add external linked objects with hooks
1169 1169
         $this->linked_objects[$this->origin] = $this->origin_id;
1170
-        if (is_array($object->other_linked_objects) && ! empty($object->other_linked_objects))
1170
+        if (is_array($object->other_linked_objects) && !empty($object->other_linked_objects))
1171 1171
         {
1172 1172
            	$this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1173 1173
         }
@@ -1179,12 +1179,12 @@  discard block
 block discarded – undo
1179 1179
             // Actions hooked (by external module)
1180 1180
             $hookmanager->initHooks(array('orderdao'));
1181 1181
 
1182
-            $parameters=array('objFrom'=>$object);
1183
-            $action='';
1184
-            $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1182
+            $parameters = array('objFrom'=>$object);
1183
+            $action = '';
1184
+            $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1185 1185
             if ($reshook < 0) $error++;
1186 1186
 
1187
-            if (! $error)
1187
+            if (!$error)
1188 1188
             {
1189 1189
                 // Ne pas passer par la commande provisoire
1190 1190
                 if ($conf->global->COMMANDE_VALID_AFTER_CLOSE_PROPAL == 1)
@@ -1238,7 +1238,7 @@  discard block
 block discarded – undo
1238 1238
      *	par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
1239 1239
      *	et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
1240 1240
      */
1241
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise = 0)
1241
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $info_bits = 0, $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $date_start = '', $date_end = '', $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0)
1242 1242
     {
1243 1243
     	global $mysoc, $conf, $langs, $user;
1244 1244
 
@@ -1247,34 +1247,34 @@  discard block
 block discarded – undo
1247 1247
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1248 1248
 
1249 1249
         // Clean parameters
1250
-        if (empty($remise_percent)) $remise_percent=0;
1251
-        if (empty($qty)) $qty=0;
1252
-        if (empty($info_bits)) $info_bits=0;
1253
-        if (empty($rang)) $rang=0;
1254
-        if (empty($txtva)) $txtva=0;
1255
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1256
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1257
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
1258
-        if (empty($this->fk_multicurrency)) $this->fk_multicurrency=0;
1259
-
1260
-        $remise_percent=price2num($remise_percent);
1261
-        $qty=price2num($qty);
1262
-        $pu_ht=price2num($pu_ht);
1263
-        $pu_ttc=price2num($pu_ttc);
1264
-    	$pa_ht=price2num($pa_ht);
1250
+        if (empty($remise_percent)) $remise_percent = 0;
1251
+        if (empty($qty)) $qty = 0;
1252
+        if (empty($info_bits)) $info_bits = 0;
1253
+        if (empty($rang)) $rang = 0;
1254
+        if (empty($txtva)) $txtva = 0;
1255
+        if (empty($txlocaltax1)) $txlocaltax1 = 0;
1256
+        if (empty($txlocaltax2)) $txlocaltax2 = 0;
1257
+        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
1258
+        if (empty($this->fk_multicurrency)) $this->fk_multicurrency = 0;
1259
+
1260
+        $remise_percent = price2num($remise_percent);
1261
+        $qty = price2num($qty);
1262
+        $pu_ht = price2num($pu_ht);
1263
+        $pu_ttc = price2num($pu_ttc);
1264
+    	$pa_ht = price2num($pa_ht);
1265 1265
         $txtva = price2num($txtva);
1266 1266
         $txlocaltax1 = price2num($txlocaltax1);
1267 1267
         $txlocaltax2 = price2num($txlocaltax2);
1268
-        if ($price_base_type=='HT')
1268
+        if ($price_base_type == 'HT')
1269 1269
         {
1270
-            $pu=$pu_ht;
1270
+            $pu = $pu_ht;
1271 1271
         }
1272 1272
         else
1273 1273
         {
1274
-            $pu=$pu_ttc;
1274
+            $pu = $pu_ttc;
1275 1275
         }
1276
-        $label=trim($label);
1277
-        $desc=trim($desc);
1276
+        $label = trim($label);
1277
+        $desc = trim($desc);
1278 1278
 
1279 1279
         // Check parameters
1280 1280
         if ($type < 0) return -1;
@@ -1283,17 +1283,17 @@  discard block
 block discarded – undo
1283 1283
         {
1284 1284
             $this->db->begin();
1285 1285
 
1286
-        	$product_type=$type;
1286
+        	$product_type = $type;
1287 1287
 			if (!empty($fk_product))
1288 1288
 			{
1289
-				$product=new Product($this->db);
1290
-				$result=$product->fetch($fk_product);
1291
-				$product_type=$product->type;
1289
+				$product = new Product($this->db);
1290
+				$result = $product->fetch($fk_product);
1291
+				$product_type = $product->type;
1292 1292
 
1293
-				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
1293
+				if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
1294 1294
 				{
1295 1295
                     $langs->load("errors");
1296
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1296
+				    $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1297 1297
 					dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1298 1298
 					$this->db->rollback();
1299 1299
 					return self::STOCK_NOT_ENOUGH_FOR_ORDER;
@@ -1304,14 +1304,14 @@  discard block
 block discarded – undo
1304 1304
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1305 1305
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1306 1306
 
1307
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
1307
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1308 1308
 
1309 1309
        		// Clean vat code
1310
-    		$vat_src_code='';
1310
+    		$vat_src_code = '';
1311 1311
     		if (preg_match('/\((.*)\)/', $txtva, $reg))
1312 1312
     		{
1313 1313
     		    $vat_src_code = $reg[1];
1314
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1314
+    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1315 1315
     		}
1316 1316
 
1317 1317
             $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
@@ -1324,7 +1324,7 @@  discard block
 block discarded – undo
1324 1324
 			$pu_ht = $tabprice[3];
1325 1325
 
1326 1326
 			// MultiCurrency
1327
-			$multicurrency_total_ht  = $tabprice[16];
1327
+			$multicurrency_total_ht = $tabprice[16];
1328 1328
             $multicurrency_total_tva = $tabprice[17];
1329 1329
             $multicurrency_total_ttc = $tabprice[18];
1330 1330
 			$pu_ht_devise = $tabprice[19];
@@ -1348,70 +1348,70 @@  discard block
 block discarded – undo
1348 1348
             }
1349 1349
 
1350 1350
             // Insert line
1351
-            $this->line=new OrderLine($this->db);
1351
+            $this->line = new OrderLine($this->db);
1352 1352
 
1353 1353
             $this->line->context = $this->context;
1354 1354
 
1355
-            $this->line->fk_commande=$this->id;
1356
-            $this->line->label=$label;
1357
-            $this->line->desc=$desc;
1358
-            $this->line->qty=$qty;
1359
-
1360
-			$this->line->vat_src_code=$vat_src_code;
1361
-            $this->line->tva_tx=$txtva;
1362
-            $this->line->localtax1_tx=$localtaxes_type[1];
1363
-            $this->line->localtax2_tx=$localtaxes_type[3];
1364
-			$this->line->localtax1_type=$localtaxes_type[0];
1365
-			$this->line->localtax2_type=$localtaxes_type[2];
1366
-            $this->line->fk_product=$fk_product;
1367
-			$this->line->product_type=$product_type;
1368
-            $this->line->fk_remise_except=$fk_remise_except;
1369
-            $this->line->remise_percent=$remise_percent;
1370
-            $this->line->subprice=$pu_ht;
1371
-            $this->line->rang=$rangtouse;
1372
-            $this->line->info_bits=$info_bits;
1373
-            $this->line->total_ht=$total_ht;
1374
-            $this->line->total_tva=$total_tva;
1375
-            $this->line->total_localtax1=$total_localtax1;
1376
-            $this->line->total_localtax2=$total_localtax2;
1377
-            $this->line->total_ttc=$total_ttc;
1378
-            $this->line->product_type=$type;
1379
-            $this->line->special_code=$special_code;
1380
-            $this->line->origin=$origin;
1381
-            $this->line->origin_id=$origin_id;
1382
-            $this->line->fk_parent_line=$fk_parent_line;
1383
-	        $this->line->fk_unit=$fk_unit;
1384
-
1385
-            $this->line->date_start=$date_start;
1386
-            $this->line->date_end=$date_end;
1355
+            $this->line->fk_commande = $this->id;
1356
+            $this->line->label = $label;
1357
+            $this->line->desc = $desc;
1358
+            $this->line->qty = $qty;
1359
+
1360
+			$this->line->vat_src_code = $vat_src_code;
1361
+            $this->line->tva_tx = $txtva;
1362
+            $this->line->localtax1_tx = $localtaxes_type[1];
1363
+            $this->line->localtax2_tx = $localtaxes_type[3];
1364
+			$this->line->localtax1_type = $localtaxes_type[0];
1365
+			$this->line->localtax2_type = $localtaxes_type[2];
1366
+            $this->line->fk_product = $fk_product;
1367
+			$this->line->product_type = $product_type;
1368
+            $this->line->fk_remise_except = $fk_remise_except;
1369
+            $this->line->remise_percent = $remise_percent;
1370
+            $this->line->subprice = $pu_ht;
1371
+            $this->line->rang = $rangtouse;
1372
+            $this->line->info_bits = $info_bits;
1373
+            $this->line->total_ht = $total_ht;
1374
+            $this->line->total_tva = $total_tva;
1375
+            $this->line->total_localtax1 = $total_localtax1;
1376
+            $this->line->total_localtax2 = $total_localtax2;
1377
+            $this->line->total_ttc = $total_ttc;
1378
+            $this->line->product_type = $type;
1379
+            $this->line->special_code = $special_code;
1380
+            $this->line->origin = $origin;
1381
+            $this->line->origin_id = $origin_id;
1382
+            $this->line->fk_parent_line = $fk_parent_line;
1383
+	        $this->line->fk_unit = $fk_unit;
1384
+
1385
+            $this->line->date_start = $date_start;
1386
+            $this->line->date_end = $date_end;
1387 1387
 
1388 1388
 			$this->line->fk_fournprice = $fk_fournprice;
1389 1389
 			$this->line->pa_ht = $pa_ht;
1390 1390
 
1391 1391
 			// Multicurrency
1392
-			$this->line->fk_multicurrency			= $this->fk_multicurrency;
1393
-			$this->line->multicurrency_code			= $this->multicurrency_code;
1392
+			$this->line->fk_multicurrency = $this->fk_multicurrency;
1393
+			$this->line->multicurrency_code = $this->multicurrency_code;
1394 1394
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
1395 1395
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
1396 1396
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
1397 1397
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
1398 1398
 
1399 1399
             // TODO Ne plus utiliser
1400
-            $this->line->price=$price;
1401
-            $this->line->remise=$remise;
1400
+            $this->line->price = $price;
1401
+            $this->line->remise = $remise;
1402 1402
 
1403
-			if (is_array($array_options) && count($array_options)>0) {
1404
-				$this->line->array_options=$array_options;
1403
+			if (is_array($array_options) && count($array_options) > 0) {
1404
+				$this->line->array_options = $array_options;
1405 1405
 			}
1406 1406
 
1407
-            $result=$this->line->insert($user);
1407
+            $result = $this->line->insert($user);
1408 1408
             if ($result > 0)
1409 1409
             {
1410 1410
                 // Reorder if child line
1411
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1411
+                if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
1412 1412
 
1413 1413
                 // Mise a jour informations denormalisees au niveau de la commande meme
1414
-                $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1414
+                $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1415 1415
                 if ($result > 0)
1416 1416
                 {
1417 1417
                     $this->db->commit();
@@ -1425,7 +1425,7 @@  discard block
 block discarded – undo
1425 1425
             }
1426 1426
             else
1427 1427
             {
1428
-                $this->error=$this->line->error;
1428
+                $this->error = $this->line->error;
1429 1429
                 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1430 1430
                 $this->db->rollback();
1431 1431
                 return -2;
@@ -1453,53 +1453,53 @@  discard block
 block discarded – undo
1453 1453
      *	TODO	Remplacer les appels a cette fonction par generation objet Ligne
1454 1454
      *			insere dans tableau $this->products
1455 1455
      */
1456
-    function add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
1456
+    function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '')
1457 1457
     {
1458 1458
         global $conf, $mysoc;
1459 1459
 
1460
-        if (! $qty) $qty = 1;
1460
+        if (!$qty) $qty = 1;
1461 1461
 
1462 1462
         if ($idproduct > 0)
1463 1463
         {
1464
-            $prod=new Product($this->db);
1464
+            $prod = new Product($this->db);
1465 1465
             $prod->fetch($idproduct);
1466 1466
 
1467
-            $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
1468
-            $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
1469
-            if (empty($tva_tx)) $tva_npr=0;
1470
-            $vat_src_code = '';     // May be defined into tva_tx
1467
+            $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
1468
+            $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
1469
+            if (empty($tva_tx)) $tva_npr = 0;
1470
+            $vat_src_code = ''; // May be defined into tva_tx
1471 1471
 
1472
-            $localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
1473
-            $localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
1472
+            $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr);
1473
+            $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr);
1474 1474
 
1475 1475
             // multiprix
1476
-            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
1476
+            if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
1477 1477
             $price = $prod->multiprices[$this->thirdparty->price_level];
1478 1478
             else
1479 1479
             $price = $prod->price;
1480 1480
 
1481
-            $line=new OrderLine($this->db);
1481
+            $line = new OrderLine($this->db);
1482 1482
 
1483 1483
             $line->context = $this->context;
1484 1484
 
1485
-            $line->fk_product=$idproduct;
1486
-            $line->desc=$prod->description;
1487
-            $line->qty=$qty;
1488
-            $line->subprice=$price;
1489
-            $line->remise_percent=$remise_percent;
1490
-            $line->vat_src_code=$vat_src_code;
1491
-            $line->tva_tx=$tva_tx;
1492
-            $line->localtax1_tx=$localtax1_tx;
1493
-            $line->localtax2_tx=$localtax2_tx;
1494
-            $line->ref=$prod->ref;
1495
-            $line->libelle=$prod->label;
1496
-            $line->product_desc=$prod->description;
1497
-	        $line->fk_unit=$prod->fk_unit;
1485
+            $line->fk_product = $idproduct;
1486
+            $line->desc = $prod->description;
1487
+            $line->qty = $qty;
1488
+            $line->subprice = $price;
1489
+            $line->remise_percent = $remise_percent;
1490
+            $line->vat_src_code = $vat_src_code;
1491
+            $line->tva_tx = $tva_tx;
1492
+            $line->localtax1_tx = $localtax1_tx;
1493
+            $line->localtax2_tx = $localtax2_tx;
1494
+            $line->ref = $prod->ref;
1495
+            $line->libelle = $prod->label;
1496
+            $line->product_desc = $prod->description;
1497
+	        $line->fk_unit = $prod->fk_unit;
1498 1498
 
1499 1499
             // Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1500 1500
             // Save the start and end date of the line in the object
1501 1501
             if ($date_start) { $line->date_start = $date_start; }
1502
-            if ($date_end)   { $line->date_end = $date_end; }
1502
+            if ($date_end) { $line->date_end = $date_end; }
1503 1503
 
1504 1504
             $this->lines[] = $line;
1505 1505
 
@@ -1536,39 +1536,39 @@  discard block
 block discarded – undo
1536 1536
      * 	@param		string		$ref_int		Internal reference of other object
1537 1537
      *	@return     int         				>0 if OK, <0 if KO, 0 if not found
1538 1538
      */
1539
-    function fetch($id, $ref='', $ref_ext='', $ref_int='')
1539
+    function fetch($id, $ref = '', $ref_ext = '', $ref_int = '')
1540 1540
     {
1541 1541
 
1542 1542
         // Check parameters
1543 1543
         if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1544 1544
 
1545 1545
         $sql = 'SELECT c.rowid, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
1546
-        $sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1547
-        $sql.= ', c.fk_account';
1548
-        $sql.= ', c.date_commande';
1549
-        $sql.= ', c.date_livraison';
1550
-        $sql.= ', c.fk_shipping_method';
1551
-        $sql.= ', c.fk_warehouse';
1552
-        $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
1553
-        $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
1554
-        $sql.= ', c.fk_incoterms, c.location_incoterms';
1555
-		$sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
1556
-        $sql.= ", i.libelle as libelle_incoterms";
1557
-        $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1558
-        $sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
1559
-        $sql.= ', ca.code as availability_code, ca.label as availability_label';
1560
-        $sql.= ', dr.code as demand_reason_code';
1561
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
1562
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term') . ')';
1563
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement') . ')';
1564
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
1565
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1566
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1567
-        $sql.= " WHERE c.entity IN (".getEntity('commande').")";
1568
-        if ($id)   	  $sql.= " AND c.rowid=".$id;
1569
-        if ($ref)     $sql.= " AND c.ref='".$this->db->escape($ref)."'";
1570
-        if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1571
-        if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1546
+        $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1547
+        $sql .= ', c.fk_account';
1548
+        $sql .= ', c.date_commande';
1549
+        $sql .= ', c.date_livraison';
1550
+        $sql .= ', c.fk_shipping_method';
1551
+        $sql .= ', c.fk_warehouse';
1552
+        $sql .= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
1553
+        $sql .= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
1554
+        $sql .= ', c.fk_incoterms, c.location_incoterms';
1555
+		$sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
1556
+        $sql .= ", i.libelle as libelle_incoterms";
1557
+        $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1558
+        $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
1559
+        $sql .= ', ca.code as availability_code, ca.label as availability_label';
1560
+        $sql .= ', dr.code as demand_reason_code';
1561
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
1562
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
1563
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')';
1564
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
1565
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1566
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1567
+        $sql .= " WHERE c.entity IN (".getEntity('commande').")";
1568
+        if ($id)   	  $sql .= " AND c.rowid=".$id;
1569
+        if ($ref)     $sql .= " AND c.ref='".$this->db->escape($ref)."'";
1570
+        if ($ref_ext) $sql .= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1571
+        if ($ref_int) $sql .= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1572 1572
 
1573 1573
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1574 1574
         $result = $this->db->query($sql);
@@ -1577,51 +1577,51 @@  discard block
 block discarded – undo
1577 1577
             $obj = $this->db->fetch_object($result);
1578 1578
             if ($obj)
1579 1579
             {
1580
-                $this->id					= $obj->rowid;
1581
-                $this->ref					= $obj->ref;
1582
-                $this->ref_client			= $obj->ref_client;
1583
-                $this->ref_customer			= $obj->ref_client;
1580
+                $this->id = $obj->rowid;
1581
+                $this->ref = $obj->ref;
1582
+                $this->ref_client = $obj->ref_client;
1583
+                $this->ref_customer = $obj->ref_client;
1584 1584
                 $this->ref_ext				= $obj->ref_ext;
1585 1585
                 $this->ref_int				= $obj->ref_int;
1586
-                $this->socid				= $obj->fk_soc;
1587
-                $this->statut				= $obj->fk_statut;
1588
-                $this->user_author_id		= $obj->fk_user_author;
1589
-                $this->user_valid           = $obj->fk_user_valid;
1586
+                $this->socid = $obj->fk_soc;
1587
+                $this->statut = $obj->fk_statut;
1588
+                $this->user_author_id = $obj->fk_user_author;
1589
+                $this->user_valid = $obj->fk_user_valid;
1590 1590
                 $this->total_ht				= $obj->total_ht;
1591 1591
                 $this->total_tva			= $obj->total_tva;
1592 1592
                 $this->total_localtax1		= $obj->total_localtax1;
1593 1593
                 $this->total_localtax2		= $obj->total_localtax2;
1594 1594
                 $this->total_ttc			= $obj->total_ttc;
1595
-                $this->date					= $this->db->jdate($obj->date_commande);
1596
-                $this->date_commande		= $this->db->jdate($obj->date_commande);
1595
+                $this->date = $this->db->jdate($obj->date_commande);
1596
+                $this->date_commande = $this->db->jdate($obj->date_commande);
1597 1597
                 $this->remise				= $obj->remise;
1598 1598
                 $this->remise_percent		= $obj->remise_percent;
1599 1599
                 $this->remise_absolue		= $obj->remise_absolue;
1600 1600
                 $this->source				= $obj->source;
1601
-                $this->facturee				= $obj->billed;			// deprecated
1601
+                $this->facturee = $obj->billed; // deprecated
1602 1602
                 $this->billed				= $obj->billed;
1603
-                $this->note					= $obj->note_private;	// deprecated
1604
-                $this->note_private			= $obj->note_private;
1605
-                $this->note_public			= $obj->note_public;
1606
-                $this->fk_project			= $obj->fk_projet;
1607
-                $this->modelpdf				= $obj->model_pdf;
1603
+                $this->note = $obj->note_private; // deprecated
1604
+                $this->note_private = $obj->note_private;
1605
+                $this->note_public = $obj->note_public;
1606
+                $this->fk_project = $obj->fk_projet;
1607
+                $this->modelpdf = $obj->model_pdf;
1608 1608
                 $this->mode_reglement_id	= $obj->fk_mode_reglement;
1609 1609
                 $this->mode_reglement_code	= $obj->mode_reglement_code;
1610 1610
                 $this->mode_reglement		= $obj->mode_reglement_libelle;
1611 1611
                 $this->cond_reglement_id	= $obj->fk_cond_reglement;
1612 1612
                 $this->cond_reglement_code	= $obj->cond_reglement_code;
1613 1613
                 $this->cond_reglement		= $obj->cond_reglement_libelle;
1614
-                $this->cond_reglement_doc	= $obj->cond_reglement_libelle_doc;
1615
-                $this->fk_account           = $obj->fk_account;
1616
-                $this->availability_id		= $obj->fk_availability;
1614
+                $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1615
+                $this->fk_account = $obj->fk_account;
1616
+                $this->availability_id = $obj->fk_availability;
1617 1617
                 $this->availability_code	= $obj->availability_code;
1618 1618
                 $this->availability	    	= $obj->availability_label;
1619 1619
                 $this->demand_reason_id		= $obj->fk_input_reason;
1620
-                $this->demand_reason_code	= $obj->demand_reason_code;
1621
-                $this->date_livraison		= $this->db->jdate($obj->date_livraison);
1622
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1623
-                $this->warehouse_id           = ($obj->fk_warehouse>0)?$obj->fk_warehouse:null;
1624
-                $this->fk_delivery_address	= $obj->fk_delivery_address;
1620
+                $this->demand_reason_code = $obj->demand_reason_code;
1621
+                $this->date_livraison = $this->db->jdate($obj->date_livraison);
1622
+                $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1623
+                $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
1624
+                $this->fk_delivery_address = $obj->fk_delivery_address;
1625 1625
 
1626 1626
 				//Incoterms
1627 1627
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -1630,31 +1630,31 @@  discard block
 block discarded – undo
1630 1630
 
1631 1631
 				// Multicurrency
1632 1632
 				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1633
-				$this->multicurrency_code 		= $obj->multicurrency_code;
1633
+				$this->multicurrency_code = $obj->multicurrency_code;
1634 1634
 				$this->multicurrency_tx 		= $obj->multicurrency_tx;
1635
-				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1635
+				$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1636 1636
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1637 1637
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1638 1638
 
1639
-                $this->extraparams			= (array) json_decode($obj->extraparams, true);
1639
+                $this->extraparams = (array) json_decode($obj->extraparams, true);
1640 1640
 
1641
-                $this->lines				= array();
1641
+                $this->lines = array();
1642 1642
 
1643 1643
                 if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
1644 1644
 
1645 1645
                 // Retrieve all extrafields for invoice
1646 1646
                 // fetch optionals attributes and labels
1647 1647
                 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1648
-                $extrafields=new ExtraFields($this->db);
1649
-                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1650
-               	$this->fetch_optionals($this->id,$extralabels);
1648
+                $extrafields = new ExtraFields($this->db);
1649
+                $extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true);
1650
+               	$this->fetch_optionals($this->id, $extralabels);
1651 1651
 
1652 1652
                 $this->db->free($result);
1653 1653
 
1654 1654
                 /*
1655 1655
                  * Lines
1656 1656
                  */
1657
-                $result=$this->fetch_lines();
1657
+                $result = $this->fetch_lines();
1658 1658
                 if ($result < 0)
1659 1659
                 {
1660 1660
                     return -3;
@@ -1663,13 +1663,13 @@  discard block
 block discarded – undo
1663 1663
             }
1664 1664
             else
1665 1665
             {
1666
-                $this->error='Order with id '.$id.' not found sql='.$sql;
1666
+                $this->error = 'Order with id '.$id.' not found sql='.$sql;
1667 1667
                 return 0;
1668 1668
             }
1669 1669
         }
1670 1670
         else
1671 1671
         {
1672
-            $this->error=$this->db->error();
1672
+            $this->error = $this->db->error();
1673 1673
             return -1;
1674 1674
         }
1675 1675
     }
@@ -1690,42 +1690,42 @@  discard block
 block discarded – undo
1690 1690
 
1691 1691
         $this->db->begin();
1692 1692
 
1693
-        $remise=new DiscountAbsolute($this->db);
1694
-        $result=$remise->fetch($idremise);
1693
+        $remise = new DiscountAbsolute($this->db);
1694
+        $result = $remise->fetch($idremise);
1695 1695
 
1696 1696
         if ($result > 0)
1697 1697
         {
1698 1698
             if ($remise->fk_facture)	// Protection against multiple submission
1699 1699
             {
1700
-                $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1700
+                $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
1701 1701
                 $this->db->rollback();
1702 1702
                 return -5;
1703 1703
             }
1704 1704
 
1705 1705
             $line = new OrderLine($this->db);
1706 1706
 
1707
-            $line->fk_commande=$this->id;
1708
-            $line->fk_remise_except=$remise->id;
1709
-            $line->desc=$remise->description;   	// Description ligne
1710
-            $line->vat_src_code=$remise->vat_src_code;
1711
-            $line->tva_tx=$remise->tva_tx;
1712
-            $line->subprice=-$remise->amount_ht;
1713
-            $line->price=-$remise->amount_ht;
1714
-            $line->fk_product=0;					// Id produit predefini
1715
-            $line->qty=1;
1716
-            $line->remise=0;
1717
-            $line->remise_percent=0;
1718
-            $line->rang=-1;
1719
-            $line->info_bits=2;
1707
+            $line->fk_commande = $this->id;
1708
+            $line->fk_remise_except = $remise->id;
1709
+            $line->desc = $remise->description; // Description ligne
1710
+            $line->vat_src_code = $remise->vat_src_code;
1711
+            $line->tva_tx = $remise->tva_tx;
1712
+            $line->subprice = -$remise->amount_ht;
1713
+            $line->price = -$remise->amount_ht;
1714
+            $line->fk_product = 0; // Id produit predefini
1715
+            $line->qty = 1;
1716
+            $line->remise = 0;
1717
+            $line->remise_percent = 0;
1718
+            $line->rang = -1;
1719
+            $line->info_bits = 2;
1720 1720
 
1721 1721
             $line->total_ht  = -$remise->amount_ht;
1722 1722
             $line->total_tva = -$remise->amount_tva;
1723 1723
             $line->total_ttc = -$remise->amount_ttc;
1724 1724
 
1725
-            $result=$line->insert();
1725
+            $result = $line->insert();
1726 1726
             if ($result > 0)
1727 1727
             {
1728
-                $result=$this->update_price(1);
1728
+                $result = $this->update_price(1);
1729 1729
                 if ($result > 0)
1730 1730
                 {
1731 1731
                     $this->db->commit();
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
             }
1740 1740
             else
1741 1741
             {
1742
-                $this->error=$line->error;
1742
+                $this->error = $line->error;
1743 1743
                 $this->db->rollback();
1744 1744
                 return -2;
1745 1745
             }
@@ -1758,20 +1758,20 @@  discard block
 block discarded – undo
1758 1758
      *	@param		int		$only_product	Return only physical products
1759 1759
      *	@return		int						<0 if KO, >0 if OK
1760 1760
      */
1761
-    function fetch_lines($only_product=0)
1761
+    function fetch_lines($only_product = 0)
1762 1762
     {
1763
-        $this->lines=array();
1763
+        $this->lines = array();
1764 1764
 
1765 1765
         $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,';
1766
-        $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
1767
-        $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
1768
-	    $sql.= ' l.fk_unit,';
1769
-		$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1770
-        $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,';
1771
-        $sql.= ' p.weight, p.weight_units, p.volume, p.volume_units';
1772
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1773
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1774
-        $sql.= ' WHERE l.fk_commande = '.$this->id;
1766
+        $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
1767
+        $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
1768
+	    $sql .= ' l.fk_unit,';
1769
+		$sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1770
+        $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,';
1771
+        $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units';
1772
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1773
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1774
+        $sql .= ' WHERE l.fk_commande = '.$this->id;
1775 1775
         if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1776 1776
         $sql .= ' ORDER BY l.rang, l.rowid';
1777 1777
 
@@ -1794,17 +1794,17 @@  discard block
 block discarded – undo
1794 1794
                 $line->commande_id      = $objp->fk_commande;
1795 1795
                 $line->label            = $objp->custom_label;
1796 1796
                 $line->desc             = $objp->description;
1797
-                $line->description      = $objp->description;		// Description line
1797
+                $line->description      = $objp->description; // Description line
1798 1798
                 $line->product_type     = $objp->product_type;
1799 1799
                 $line->qty              = $objp->qty;
1800 1800
 
1801 1801
                 $line->vat_src_code     = $objp->vat_src_code;
1802 1802
                 $line->tva_tx           = $objp->tva_tx;
1803
-	            $line->localtax1_tx     = $objp->localtax1_tx;
1803
+	            $line->localtax1_tx = $objp->localtax1_tx;
1804 1804
                 $line->localtax2_tx     = $objp->localtax2_tx;
1805 1805
 	            $line->localtax1_type	= $objp->localtax1_type;
1806 1806
 	            $line->localtax2_type	= $objp->localtax2_type;
1807
-	            $line->total_ht         = $objp->total_ht;
1807
+	            $line->total_ht = $objp->total_ht;
1808 1808
                 $line->total_ttc        = $objp->total_ttc;
1809 1809
                 $line->total_tva        = $objp->total_tva;
1810 1810
                 $line->total_localtax1  = $objp->total_localtax1;
@@ -1814,23 +1814,23 @@  discard block
 block discarded – undo
1814 1814
                 $line->remise_percent   = $objp->remise_percent;
1815 1815
                 $line->price            = $objp->price;
1816 1816
                 $line->fk_product       = $objp->fk_product;
1817
-				$line->fk_fournprice 	= $objp->fk_fournprice;
1818
-		      	$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1819
-		   		$line->pa_ht 			= $marginInfos[0];
1820
-		    	$line->marge_tx			= $marginInfos[1];
1821
-		     	$line->marque_tx		= $marginInfos[2];
1817
+				$line->fk_fournprice = $objp->fk_fournprice;
1818
+		      	$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1819
+		   		$line->pa_ht = $marginInfos[0];
1820
+		    	$line->marge_tx = $marginInfos[1];
1821
+		     	$line->marque_tx = $marginInfos[2];
1822 1822
                 $line->rang             = $objp->rang;
1823 1823
                 $line->info_bits        = $objp->info_bits;
1824
-                $line->special_code		= $objp->special_code;
1825
-                $line->fk_parent_line	= $objp->fk_parent_line;
1824
+                $line->special_code = $objp->special_code;
1825
+                $line->fk_parent_line = $objp->fk_parent_line;
1826 1826
 
1827
-                $line->ref				= $objp->product_ref;
1828
-                $line->product_ref		= $objp->product_ref;
1829
-                $line->libelle			= $objp->product_label;
1830
-                $line->product_label	= $objp->product_label;
1827
+                $line->ref = $objp->product_ref;
1828
+                $line->product_ref = $objp->product_ref;
1829
+                $line->libelle = $objp->product_label;
1830
+                $line->product_label = $objp->product_label;
1831 1831
                 $line->product_desc     = $objp->product_desc;
1832 1832
                 $line->product_tobatch  = $objp->product_tobatch;
1833
-                $line->fk_product_type  = $objp->fk_product_type;	// Produit ou service
1833
+                $line->fk_product_type  = $objp->fk_product_type; // Produit ou service
1834 1834
 	            $line->fk_unit          = $objp->fk_unit;
1835 1835
 
1836 1836
 	            $line->weight           = $objp->weight;
@@ -1842,8 +1842,8 @@  discard block
 block discarded – undo
1842 1842
                 $line->date_end         = $this->db->jdate($objp->date_end);
1843 1843
 
1844 1844
 				// Multicurrency
1845
-				$line->fk_multicurrency 		= $objp->fk_multicurrency;
1846
-				$line->multicurrency_code 		= $objp->multicurrency_code;
1845
+				$line->fk_multicurrency = $objp->fk_multicurrency;
1846
+				$line->multicurrency_code = $objp->multicurrency_code;
1847 1847
 				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
1848 1848
 				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
1849 1849
 				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
         }
1861 1861
         else
1862 1862
         {
1863
-            $this->error=$this->db->error();
1863
+            $this->error = $this->db->error();
1864 1864
             return -3;
1865 1865
         }
1866 1866
     }
@@ -1873,8 +1873,8 @@  discard block
 block discarded – undo
1873 1873
      */
1874 1874
     function getNbOfProductsLines()
1875 1875
     {
1876
-        $nb=0;
1877
-        foreach($this->lines as $line)
1876
+        $nb = 0;
1877
+        foreach ($this->lines as $line)
1878 1878
         {
1879 1879
             if ($line->product_type == 0) $nb++;
1880 1880
         }
@@ -1888,8 +1888,8 @@  discard block
 block discarded – undo
1888 1888
      */
1889 1889
     function getNbOfServicesLines()
1890 1890
     {
1891
-        $nb=0;
1892
-        foreach($this->lines as $line)
1891
+        $nb = 0;
1892
+        foreach ($this->lines as $line)
1893 1893
         {
1894 1894
             if ($line->product_type == 1) $nb++;
1895 1895
         }
@@ -1903,22 +1903,22 @@  discard block
 block discarded – undo
1903 1903
      *	@param      int		$filtre_statut      Filter on shipment status
1904 1904
      * 	@return     int                			<0 if KO, Nb of lines found if OK
1905 1905
      */
1906
-    function loadExpeditions($filtre_statut=-1)
1906
+    function loadExpeditions($filtre_statut = -1)
1907 1907
     {
1908 1908
         $this->expeditions = array();
1909 1909
 
1910 1910
         $sql = 'SELECT cd.rowid, cd.fk_product,';
1911
-        $sql.= ' sum(ed.qty) as qty';
1912
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
1913
-        if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
1914
-        $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
1915
-        $sql.= ' WHERE';
1916
-        if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND';
1917
-        $sql.= ' ed.fk_origin_line = cd.rowid';
1918
-        $sql.= ' AND cd.fk_commande =' .$this->id;
1919
-        if ($this->fk_product > 0) $sql.= ' AND cd.fk_product = '.$this->fk_product;
1920
-        if ($filtre_statut >= 0) $sql.=' AND e.fk_statut >= '.$filtre_statut;
1921
-        $sql.= ' GROUP BY cd.rowid, cd.fk_product';
1911
+        $sql .= ' sum(ed.qty) as qty';
1912
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
1913
+        if ($filtre_statut >= 0) $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,';
1914
+        $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd';
1915
+        $sql .= ' WHERE';
1916
+        if ($filtre_statut >= 0) $sql .= ' ed.fk_expedition = e.rowid AND';
1917
+        $sql .= ' ed.fk_origin_line = cd.rowid';
1918
+        $sql .= ' AND cd.fk_commande ='.$this->id;
1919
+        if ($this->fk_product > 0) $sql .= ' AND cd.fk_product = '.$this->fk_product;
1920
+        if ($filtre_statut >= 0) $sql .= ' AND e.fk_statut >= '.$filtre_statut;
1921
+        $sql .= ' GROUP BY cd.rowid, cd.fk_product';
1922 1922
         //print $sql;
1923 1923
 
1924 1924
         dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
@@ -1938,7 +1938,7 @@  discard block
 block discarded – undo
1938 1938
         }
1939 1939
         else
1940 1940
         {
1941
-            $this->error=$this->db->lasterror();
1941
+            $this->error = $this->db->lasterror();
1942 1942
             return -1;
1943 1943
         }
1944 1944
 
@@ -1954,11 +1954,11 @@  discard block
 block discarded – undo
1954 1954
     function nb_expedition()
1955 1955
     {
1956 1956
         $sql = 'SELECT count(*)';
1957
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
1958
-        $sql.= ', '.MAIN_DB_PREFIX.'element_element as el';
1959
-        $sql.= ' WHERE el.fk_source = '.$this->id;
1960
-        $sql.= " AND el.fk_target = e.rowid";
1961
-        $sql.= " AND el.targettype = 'shipping'";
1957
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
1958
+        $sql .= ', '.MAIN_DB_PREFIX.'element_element as el';
1959
+        $sql .= ' WHERE el.fk_source = '.$this->id;
1960
+        $sql .= " AND el.fk_target = e.rowid";
1961
+        $sql .= " AND el.targettype = 'shipping'";
1962 1962
 
1963 1963
         $resql = $this->db->query($sql);
1964 1964
         if ($resql)
@@ -1977,21 +1977,21 @@  discard block
 block discarded – undo
1977 1977
      *
1978 1978
      *	TODO		FONCTION NON FINIE A FINIR
1979 1979
      */
1980
-    function stock_array($filtre_statut=self::STATUS_CANCELED)
1980
+    function stock_array($filtre_statut = self::STATUS_CANCELED)
1981 1981
     {
1982 1982
         $this->stocks = array();
1983 1983
 
1984 1984
         // Tableau des id de produit de la commande
1985
-		$array_of_product=array();
1985
+		$array_of_product = array();
1986 1986
 
1987 1987
         // Recherche total en stock pour chaque produit
1988 1988
         // TODO $array_of_product est défini vide juste au dessus !!
1989 1989
         if (count($array_of_product))
1990 1990
         {
1991 1991
             $sql = "SELECT fk_product, sum(ps.reel) as total";
1992
-            $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
1993
-            $sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")";
1994
-            $sql.= ' GROUP BY fk_product ';
1992
+            $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
1993
+            $sql .= " WHERE ps.fk_product IN (".join(',', $array_of_product).")";
1994
+            $sql .= ' GROUP BY fk_product ';
1995 1995
             $result = $this->db->query($sql);
1996 1996
             if ($result)
1997 1997
             {
@@ -2016,7 +2016,7 @@  discard block
 block discarded – undo
2016 2016
      *  @param      int		$lineid		Id of line to delete
2017 2017
      *  @return     int        		 	>0 if OK, 0 if nothing to do, <0 if KO
2018 2018
      */
2019
-    function deleteline($user=null, $lineid=0)
2019
+    function deleteline($user = null, $lineid = 0)
2020 2020
     {
2021 2021
 
2022 2022
         if ($this->statut == self::STATUS_DRAFT)
@@ -2024,8 +2024,8 @@  discard block
 block discarded – undo
2024 2024
             $this->db->begin();
2025 2025
 
2026 2026
             $sql = "SELECT fk_product, qty";
2027
-            $sql.= " FROM ".MAIN_DB_PREFIX."commandedet";
2028
-            $sql.= " WHERE rowid = ".$lineid;
2027
+            $sql .= " FROM ".MAIN_DB_PREFIX."commandedet";
2028
+            $sql .= " WHERE rowid = ".$lineid;
2029 2029
 
2030 2030
             $result = $this->db->query($sql);
2031 2031
             if ($result)
@@ -2045,7 +2045,7 @@  discard block
 block discarded – undo
2045 2045
 
2046 2046
                     if ($line->delete($user) > 0)
2047 2047
                     {
2048
-                        $result=$this->update_price(1);
2048
+                        $result = $this->update_price(1);
2049 2049
 
2050 2050
                         if ($result > 0)
2051 2051
                         {
@@ -2055,14 +2055,14 @@  discard block
 block discarded – undo
2055 2055
                         else
2056 2056
                         {
2057 2057
                             $this->db->rollback();
2058
-                            $this->error=$this->db->lasterror();
2058
+                            $this->error = $this->db->lasterror();
2059 2059
                             return -1;
2060 2060
                         }
2061 2061
                     }
2062 2062
                     else
2063 2063
                     {
2064 2064
                         $this->db->rollback();
2065
-                        $this->error=$line->error;
2065
+                        $this->error = $line->error;
2066 2066
                         return -1;
2067 2067
                     }
2068 2068
                 }
@@ -2075,7 +2075,7 @@  discard block
 block discarded – undo
2075 2075
             else
2076 2076
             {
2077 2077
                 $this->db->rollback();
2078
-                $this->error=$this->db->lasterror();
2078
+                $this->error = $this->db->lasterror();
2079 2079
                 return -1;
2080 2080
             }
2081 2081
         }
@@ -2093,59 +2093,59 @@  discard block
 block discarded – undo
2093 2093
      * 	@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2094 2094
      *	@return		int 					<0 if KO, >0 if OK
2095 2095
      */
2096
-    function set_remise($user, $remise, $notrigger=0)
2096
+    function set_remise($user, $remise, $notrigger = 0)
2097 2097
     {
2098
-        $remise=trim($remise)?trim($remise):0;
2098
+        $remise = trim($remise) ?trim($remise) : 0;
2099 2099
 
2100 2100
         if ($user->rights->commande->creer)
2101 2101
         {
2102
-        	$error=0;
2102
+        	$error = 0;
2103 2103
 
2104 2104
         	$this->db->begin();
2105 2105
 
2106
-            $remise=price2num($remise);
2106
+            $remise = price2num($remise);
2107 2107
 
2108 2108
             $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2109
-            $sql.= ' SET remise_percent = '.$remise;
2110
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2109
+            $sql .= ' SET remise_percent = '.$remise;
2110
+            $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2111 2111
 
2112 2112
             dol_syslog(__METHOD__, LOG_DEBUG);
2113
-            $resql=$this->db->query($sql);
2113
+            $resql = $this->db->query($sql);
2114 2114
             if (!$resql)
2115 2115
             {
2116
-            	$this->errors[]=$this->db->error();
2116
+            	$this->errors[] = $this->db->error();
2117 2117
             	$error++;
2118 2118
             }
2119 2119
 
2120
-            if (! $error)
2120
+            if (!$error)
2121 2121
             {
2122
-            	$this->oldcopy= clone $this;
2122
+            	$this->oldcopy = clone $this;
2123 2123
             	$this->remise_percent = $remise;
2124 2124
             	$this->update_price(1);
2125 2125
             }
2126 2126
 
2127
-            if (! $notrigger && empty($error))
2127
+            if (!$notrigger && empty($error))
2128 2128
             {
2129 2129
             	// Call trigger
2130
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2130
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2131 2131
             	if ($result < 0) $error++;
2132 2132
             	// End call triggers
2133 2133
             }
2134 2134
 
2135
-            if (! $error)
2135
+            if (!$error)
2136 2136
             {
2137 2137
             	$this->db->commit();
2138 2138
             	return 1;
2139 2139
             }
2140 2140
             else
2141 2141
             {
2142
-            	foreach($this->errors as $errmsg)
2142
+            	foreach ($this->errors as $errmsg)
2143 2143
             	{
2144 2144
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2145
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2145
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2146 2146
             	}
2147 2147
             	$this->db->rollback();
2148
-            	return -1*$error;
2148
+            	return -1 * $error;
2149 2149
             }
2150 2150
         }
2151 2151
     }
@@ -2159,59 +2159,59 @@  discard block
 block discarded – undo
2159 2159
      * 		@param     	int			$notrigger	1=Does not execute triggers, 0= execute triggers
2160 2160
      *		@return		int 					<0 if KO, >0 if OK
2161 2161
      */
2162
-    function set_remise_absolue($user, $remise, $notrigger=0)
2162
+    function set_remise_absolue($user, $remise, $notrigger = 0)
2163 2163
     {
2164
-        $remise=trim($remise)?trim($remise):0;
2164
+        $remise = trim($remise) ?trim($remise) : 0;
2165 2165
 
2166 2166
         if ($user->rights->commande->creer)
2167 2167
         {
2168
-        	$error=0;
2168
+        	$error = 0;
2169 2169
 
2170 2170
         	$this->db->begin();
2171 2171
 
2172
-            $remise=price2num($remise);
2172
+            $remise = price2num($remise);
2173 2173
 
2174 2174
             $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2175
-            $sql.= ' SET remise_absolue = '.$remise;
2176
-            $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2175
+            $sql .= ' SET remise_absolue = '.$remise;
2176
+            $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2177 2177
 
2178 2178
             dol_syslog(__METHOD__, LOG_DEBUG);
2179
-            $resql=$this->db->query($sql);
2179
+            $resql = $this->db->query($sql);
2180 2180
             if (!$resql)
2181 2181
             {
2182
-            	$this->errors[]=$this->db->error();
2182
+            	$this->errors[] = $this->db->error();
2183 2183
             	$error++;
2184 2184
             }
2185 2185
 
2186
-            if (! $error)
2186
+            if (!$error)
2187 2187
             {
2188
-            	$this->oldcopy= clone $this;
2188
+            	$this->oldcopy = clone $this;
2189 2189
             	$this->remise_absolue = $remise;
2190 2190
             	$this->update_price(1);
2191 2191
             }
2192 2192
 
2193
-            if (! $notrigger && empty($error))
2193
+            if (!$notrigger && empty($error))
2194 2194
             {
2195 2195
             	// Call trigger
2196
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2196
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2197 2197
             	if ($result < 0) $error++;
2198 2198
             	// End call triggers
2199 2199
             }
2200 2200
 
2201
-            if (! $error)
2201
+            if (!$error)
2202 2202
             {
2203 2203
             	$this->db->commit();
2204 2204
             	return 1;
2205 2205
             }
2206 2206
             else
2207 2207
             {
2208
-            	foreach($this->errors as $errmsg)
2208
+            	foreach ($this->errors as $errmsg)
2209 2209
             	{
2210 2210
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2211
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2211
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2212 2212
             	}
2213 2213
             	$this->db->rollback();
2214
-            	return -1*$error;
2214
+            	return -1 * $error;
2215 2215
             }
2216 2216
         }
2217 2217
     }
@@ -2225,54 +2225,54 @@  discard block
 block discarded – undo
2225 2225
      * 	@param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2226 2226
      *	@return     int         		<0 if KO, >0 if OK
2227 2227
      */
2228
-    function set_date($user, $date, $notrigger=0)
2228
+    function set_date($user, $date, $notrigger = 0)
2229 2229
     {
2230 2230
         if ($user->rights->commande->creer)
2231 2231
         {
2232
-        	$error=0;
2232
+        	$error = 0;
2233 2233
 
2234 2234
         	$this->db->begin();
2235 2235
 
2236 2236
             $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2237
-            $sql.= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2238
-            $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2237
+            $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2238
+            $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2239 2239
 
2240 2240
             dol_syslog(__METHOD__, LOG_DEBUG);
2241
-            $resql=$this->db->query($sql);
2241
+            $resql = $this->db->query($sql);
2242 2242
             if (!$resql)
2243 2243
             {
2244
-            	$this->errors[]=$this->db->error();
2244
+            	$this->errors[] = $this->db->error();
2245 2245
             	$error++;
2246 2246
             }
2247 2247
 
2248
-            if (! $error)
2248
+            if (!$error)
2249 2249
             {
2250
-            	$this->oldcopy= clone $this;
2250
+            	$this->oldcopy = clone $this;
2251 2251
             	$this->date = $date;
2252 2252
             }
2253 2253
 
2254
-            if (! $notrigger && empty($error))
2254
+            if (!$notrigger && empty($error))
2255 2255
             {
2256 2256
             	// Call trigger
2257
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2257
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2258 2258
             	if ($result < 0) $error++;
2259 2259
             	// End call triggers
2260 2260
             }
2261 2261
 
2262
-            if (! $error)
2262
+            if (!$error)
2263 2263
             {
2264 2264
             	$this->db->commit();
2265 2265
             	return 1;
2266 2266
             }
2267 2267
             else
2268 2268
             {
2269
-            	foreach($this->errors as $errmsg)
2269
+            	foreach ($this->errors as $errmsg)
2270 2270
             	{
2271 2271
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2272
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2272
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2273 2273
             	}
2274 2274
             	$this->db->rollback();
2275
-            	return -1*$error;
2275
+            	return -1 * $error;
2276 2276
             }
2277 2277
         }
2278 2278
         else
@@ -2289,54 +2289,54 @@  discard block
 block discarded – undo
2289 2289
      *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2290 2290
      *	@return     int         				<0 si ko, >0 si ok
2291 2291
      */
2292
-    function set_date_livraison($user, $date_livraison, $notrigger=0)
2292
+    function set_date_livraison($user, $date_livraison, $notrigger = 0)
2293 2293
     {
2294 2294
         if ($user->rights->commande->creer)
2295 2295
         {
2296
-        	$error=0;
2296
+        	$error = 0;
2297 2297
 
2298 2298
         	$this->db->begin();
2299 2299
 
2300 2300
             $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2301
-            $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2302
-            $sql.= " WHERE rowid = ".$this->id;
2301
+            $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2302
+            $sql .= " WHERE rowid = ".$this->id;
2303 2303
 
2304 2304
             dol_syslog(__METHOD__, LOG_DEBUG);
2305
-            $resql=$this->db->query($sql);
2305
+            $resql = $this->db->query($sql);
2306 2306
             if (!$resql)
2307 2307
             {
2308
-            	$this->errors[]=$this->db->error();
2308
+            	$this->errors[] = $this->db->error();
2309 2309
             	$error++;
2310 2310
             }
2311 2311
 
2312
-            if (! $error)
2312
+            if (!$error)
2313 2313
             {
2314
-            	$this->oldcopy= clone $this;
2314
+            	$this->oldcopy = clone $this;
2315 2315
             	$this->date_livraison = $date_livraison;
2316 2316
             }
2317 2317
 
2318
-            if (! $notrigger && empty($error))
2318
+            if (!$notrigger && empty($error))
2319 2319
             {
2320 2320
             	// Call trigger
2321
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2321
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2322 2322
             	if ($result < 0) $error++;
2323 2323
             	// End call triggers
2324 2324
             }
2325 2325
 
2326
-            if (! $error)
2326
+            if (!$error)
2327 2327
             {
2328 2328
             	$this->db->commit();
2329 2329
             	return 1;
2330 2330
             }
2331 2331
             else
2332 2332
             {
2333
-            	foreach($this->errors as $errmsg)
2333
+            	foreach ($this->errors as $errmsg)
2334 2334
             	{
2335 2335
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2336
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2336
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2337 2337
             	}
2338 2338
             	$this->db->rollback();
2339
-            	return -1*$error;
2339
+            	return -1 * $error;
2340 2340
             }
2341 2341
         }
2342 2342
         else
@@ -2358,30 +2358,30 @@  discard block
 block discarded – undo
2358 2358
      *  @param    	string	$sortorder		Sort order
2359 2359
      *  @return     int             		-1 if KO, array with result if OK
2360 2360
      */
2361
-    function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
2361
+    function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC')
2362 2362
     {
2363 2363
         global $user;
2364 2364
 
2365 2365
         $ga = array();
2366 2366
 
2367 2367
         $sql = "SELECT s.rowid, s.nom as name, s.client,";
2368
-        $sql.= " c.rowid as cid, c.ref";
2369
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2370
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2371
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2372
-        $sql.= " WHERE c.entity IN (".getEntity('commande').")";
2373
-        $sql.= " AND c.fk_soc = s.rowid";
2374
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2368
+        $sql .= " c.rowid as cid, c.ref";
2369
+        if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
2370
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2371
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2372
+        $sql .= " WHERE c.entity IN (".getEntity('commande').")";
2373
+        $sql .= " AND c.fk_soc = s.rowid";
2374
+        if (!$user->rights->societe->client->voir && !$socid) //restriction
2375 2375
         {
2376
-        	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2376
+        	$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
2377 2377
         }
2378
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2379
-        if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2380
-        if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id;
2381
-        $sql.= $this->db->order($sortfield,$sortorder);
2382
-        $sql.= $this->db->plimit($limit,$offset);
2378
+        if ($socid) $sql .= " AND s.rowid = ".$socid;
2379
+        if ($draft) $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT;
2380
+        if (is_object($excluser)) $sql .= " AND c.fk_user_author <> ".$excluser->id;
2381
+        $sql .= $this->db->order($sortfield, $sortorder);
2382
+        $sql .= $this->db->plimit($limit, $offset);
2383 2383
 
2384
-        $result=$this->db->query($sql);
2384
+        $result = $this->db->query($sql);
2385 2385
         if ($result)
2386 2386
         {
2387 2387
             $numc = $this->db->num_rows($result);
@@ -2402,7 +2402,7 @@  discard block
 block discarded – undo
2402 2402
                     }
2403 2403
                     else
2404 2404
 					{
2405
-                    	$ga[$i]['id']	= $obj->cid;
2405
+                    	$ga[$i]['id'] = $obj->cid;
2406 2406
                     	$ga[$i]['ref'] 	= $obj->ref;
2407 2407
                     	$ga[$i]['name'] = $obj->name;
2408 2408
                     }
@@ -2425,14 +2425,14 @@  discard block
 block discarded – undo
2425 2425
      *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2426 2426
      *	@return     int         				>0 if OK, <0 if KO
2427 2427
      */
2428
-    function availability($availability_id, $notrigger=0)
2428
+    function availability($availability_id, $notrigger = 0)
2429 2429
     {
2430 2430
         global $user;
2431 2431
 
2432 2432
         dol_syslog('Commande::availability('.$availability_id.')');
2433 2433
         if ($this->statut >= self::STATUS_DRAFT)
2434 2434
         {
2435
-        	$error=0;
2435
+        	$error = 0;
2436 2436
 
2437 2437
         	$this->db->begin();
2438 2438
 
@@ -2441,49 +2441,49 @@  discard block
 block discarded – undo
2441 2441
             $sql .= ' WHERE rowid='.$this->id;
2442 2442
 
2443 2443
             dol_syslog(__METHOD__, LOG_DEBUG);
2444
-            $resql=$this->db->query($sql);
2444
+            $resql = $this->db->query($sql);
2445 2445
             if (!$resql)
2446 2446
             {
2447
-            	$this->errors[]=$this->db->error();
2447
+            	$this->errors[] = $this->db->error();
2448 2448
             	$error++;
2449 2449
             }
2450 2450
 
2451
-            if (! $error)
2451
+            if (!$error)
2452 2452
             {
2453
-            	$this->oldcopy= clone $this;
2453
+            	$this->oldcopy = clone $this;
2454 2454
             	$this->availability_id = $availability_id;
2455 2455
             }
2456 2456
 
2457
-            if (! $notrigger && empty($error))
2457
+            if (!$notrigger && empty($error))
2458 2458
             {
2459 2459
             	// Call trigger
2460
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2460
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2461 2461
             	if ($result < 0) $error++;
2462 2462
             	// End call triggers
2463 2463
             }
2464 2464
 
2465
-            if (! $error)
2465
+            if (!$error)
2466 2466
             {
2467 2467
             	$this->db->commit();
2468 2468
             	return 1;
2469 2469
             }
2470 2470
             else
2471 2471
             {
2472
-            	foreach($this->errors as $errmsg)
2472
+            	foreach ($this->errors as $errmsg)
2473 2473
             	{
2474 2474
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2475
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2475
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2476 2476
             	}
2477 2477
             	$this->db->rollback();
2478
-            	return -1*$error;
2478
+            	return -1 * $error;
2479 2479
             }
2480 2480
         }
2481 2481
         else
2482 2482
         {
2483
-        	$error_str='Command status do not meet requirement '.$this->statut;
2483
+        	$error_str = 'Command status do not meet requirement '.$this->statut;
2484 2484
             dol_syslog(__METHOD__.$error_str, LOG_ERR);
2485
-            $this->error=$error_str;
2486
-            $this->errors[]= $this->error;
2485
+            $this->error = $error_str;
2486
+            $this->errors[] = $this->error;
2487 2487
             return -2;
2488 2488
         }
2489 2489
     }
@@ -2495,14 +2495,14 @@  discard block
 block discarded – undo
2495 2495
      *  @param     	int		$notrigger			1=Does not execute triggers, 0= execute triggers
2496 2496
      *  @return     int        			 		>0 if ok, <0 if ko
2497 2497
      */
2498
-    function demand_reason($demand_reason_id, $notrigger=0)
2498
+    function demand_reason($demand_reason_id, $notrigger = 0)
2499 2499
     {
2500 2500
         global $user;
2501 2501
 
2502 2502
         dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2503 2503
         if ($this->statut >= self::STATUS_DRAFT)
2504 2504
         {
2505
-        	$error=0;
2505
+        	$error = 0;
2506 2506
 
2507 2507
         	$this->db->begin();
2508 2508
 
@@ -2511,49 +2511,49 @@  discard block
 block discarded – undo
2511 2511
             $sql .= ' WHERE rowid='.$this->id;
2512 2512
 
2513 2513
             dol_syslog(__METHOD__, LOG_DEBUG);
2514
-            $resql=$this->db->query($sql);
2514
+            $resql = $this->db->query($sql);
2515 2515
             if (!$resql)
2516 2516
             {
2517
-            	$this->errors[]=$this->db->error();
2517
+            	$this->errors[] = $this->db->error();
2518 2518
             	$error++;
2519 2519
             }
2520 2520
 
2521
-            if (! $error)
2521
+            if (!$error)
2522 2522
             {
2523
-            	$this->oldcopy= clone $this;
2523
+            	$this->oldcopy = clone $this;
2524 2524
             	$this->demand_reason_id = $demand_reason_id;
2525 2525
             }
2526 2526
 
2527
-            if (! $notrigger && empty($error))
2527
+            if (!$notrigger && empty($error))
2528 2528
             {
2529 2529
             	// Call trigger
2530
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2530
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2531 2531
             	if ($result < 0) $error++;
2532 2532
             	// End call triggers
2533 2533
             }
2534 2534
 
2535
-            if (! $error)
2535
+            if (!$error)
2536 2536
             {
2537 2537
             	$this->db->commit();
2538 2538
             	return 1;
2539 2539
             }
2540 2540
             else
2541 2541
             {
2542
-            	foreach($this->errors as $errmsg)
2542
+            	foreach ($this->errors as $errmsg)
2543 2543
             	{
2544 2544
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2545
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2545
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2546 2546
             	}
2547 2547
             	$this->db->rollback();
2548
-            	return -1*$error;
2548
+            	return -1 * $error;
2549 2549
             }
2550 2550
         }
2551 2551
         else
2552 2552
         {
2553
-        	$error_str='order status do not meet requirement '.$this->statut;
2553
+        	$error_str = 'order status do not meet requirement '.$this->statut;
2554 2554
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
2555
-        	$this->error=$error_str;
2556
-        	$this->errors[]= $this->error;
2555
+        	$this->error = $error_str;
2556
+        	$this->errors[] = $this->error;
2557 2557
             return -2;
2558 2558
         }
2559 2559
     }
@@ -2566,53 +2566,53 @@  discard block
 block discarded – undo
2566 2566
      *  @param     	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2567 2567
      *	@return     int             		<0 if KO, >0 if OK
2568 2568
      */
2569
-    function set_ref_client($user, $ref_client, $notrigger=0)
2569
+    function set_ref_client($user, $ref_client, $notrigger = 0)
2570 2570
     {
2571 2571
         if ($user->rights->commande->creer)
2572 2572
         {
2573
-        	$error=0;
2573
+        	$error = 0;
2574 2574
 
2575 2575
         	$this->db->begin();
2576 2576
 
2577 2577
             $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET';
2578
-            $sql.= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2579
-            $sql.= ' WHERE rowid = '.$this->id;
2578
+            $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2579
+            $sql .= ' WHERE rowid = '.$this->id;
2580 2580
 
2581 2581
             dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2582
-            $resql=$this->db->query($sql);
2582
+            $resql = $this->db->query($sql);
2583 2583
             if (!$resql)
2584 2584
             {
2585
-            	$this->errors[]=$this->db->error();
2585
+            	$this->errors[] = $this->db->error();
2586 2586
             	$error++;
2587 2587
             }
2588 2588
 
2589
-            if (! $error)
2589
+            if (!$error)
2590 2590
             {
2591
-            	$this->oldcopy= clone $this;
2591
+            	$this->oldcopy = clone $this;
2592 2592
             	$this->ref_client = $ref_client;
2593 2593
             }
2594 2594
 
2595
-            if (! $notrigger && empty($error))
2595
+            if (!$notrigger && empty($error))
2596 2596
             {
2597 2597
             	// Call trigger
2598
-            	$result=$this->call_trigger('ORDER_MODIFY',$user);
2598
+            	$result = $this->call_trigger('ORDER_MODIFY', $user);
2599 2599
             	if ($result < 0) $error++;
2600 2600
             	// End call triggers
2601 2601
             }
2602
-            if (! $error)
2602
+            if (!$error)
2603 2603
             {
2604 2604
             	$this->db->commit();
2605 2605
             	return 1;
2606 2606
             }
2607 2607
             else
2608 2608
             {
2609
-            	foreach($this->errors as $errmsg)
2609
+            	foreach ($this->errors as $errmsg)
2610 2610
             	{
2611 2611
             		dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2612
-            		$this->error.=($this->error?', '.$errmsg:$errmsg);
2612
+            		$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2613 2613
             	}
2614 2614
             	$this->db->rollback();
2615
-            	return -1*$error;
2615
+            	return -1 * $error;
2616 2616
             }
2617 2617
         }
2618 2618
         else
@@ -2628,53 +2628,53 @@  discard block
 block discarded – undo
2628 2628
 	 * @param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
2629 2629
 	 * @return	int                 <0 if KO, >0 if OK
2630 2630
 	 */
2631
-	function classifyBilled(User $user, $notrigger=0)
2631
+	function classifyBilled(User $user, $notrigger = 0)
2632 2632
 	{
2633 2633
         $error = 0;
2634 2634
 
2635 2635
 		$this->db->begin();
2636 2636
 
2637 2637
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
2638
-		$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2638
+		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2639 2639
 
2640 2640
 		dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
2641 2641
 		if ($this->db->query($sql))
2642 2642
 		{
2643 2643
 
2644
-			if (! $error)
2644
+			if (!$error)
2645 2645
 			{
2646
-				$this->oldcopy= clone $this;
2647
-				$this->facturee=1; // deprecated
2648
-				$this->billed=1;
2646
+				$this->oldcopy = clone $this;
2647
+				$this->facturee = 1; // deprecated
2648
+				$this->billed = 1;
2649 2649
 			}
2650 2650
 
2651
-			if (! $notrigger && empty($error))
2651
+			if (!$notrigger && empty($error))
2652 2652
 			{
2653 2653
             	// Call trigger
2654
-            	$result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user);
2654
+            	$result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
2655 2655
             	if ($result < 0) $error++;
2656 2656
             	// End call triggers
2657 2657
 			}
2658 2658
 
2659
-			if (! $error)
2659
+			if (!$error)
2660 2660
 			{
2661 2661
 				$this->db->commit();
2662 2662
 				return 1;
2663 2663
 			}
2664 2664
 			else
2665 2665
 			{
2666
-				foreach($this->errors as $errmsg)
2666
+				foreach ($this->errors as $errmsg)
2667 2667
 				{
2668 2668
 					dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
2669
-					$this->error.=($this->error?', '.$errmsg:$errmsg);
2669
+					$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2670 2670
 				}
2671 2671
 				$this->db->rollback();
2672
-				return -1*$error;
2672
+				return -1 * $error;
2673 2673
 			}
2674 2674
 		}
2675 2675
 		else
2676 2676
 		{
2677
-			$this->error=$this->db->error();
2677
+			$this->error = $this->db->error();
2678 2678
             $this->db->rollback();
2679 2679
 			return -1;
2680 2680
 		}
@@ -2690,7 +2690,7 @@  discard block
 block discarded – undo
2690 2690
 	function classer_facturee()
2691 2691
 	{
2692 2692
 	    global $user;
2693
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
2693
+		dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
2694 2694
 
2695 2695
 		return $this->classifyBilled($user);
2696 2696
 	}
@@ -2708,45 +2708,45 @@  discard block
 block discarded – undo
2708 2708
 	    $this->db->begin();
2709 2709
 
2710 2710
 	    $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0';
2711
-	    $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2711
+	    $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2712 2712
 
2713 2713
 	    dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
2714 2714
 	    if ($this->db->query($sql))
2715 2715
 	    {
2716
-	    	if (! $error)
2716
+	    	if (!$error)
2717 2717
 	    	{
2718
-	    		$this->oldcopy= clone $this;
2719
-	    		$this->facturee=1; // deprecated
2720
-	    		$this->billed=1;
2718
+	    		$this->oldcopy = clone $this;
2719
+	    		$this->facturee = 1; // deprecated
2720
+	    		$this->billed = 1;
2721 2721
 	    	}
2722 2722
 
2723 2723
 	        // Call trigger
2724
-	        $result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED',$user);
2724
+	        $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user);
2725 2725
 	        if ($result < 0) $error++;
2726 2726
 	        // End call triggers
2727 2727
 
2728
-	        if (! $error)
2728
+	        if (!$error)
2729 2729
 	        {
2730
-	            $this->facturee=0; // deprecated
2731
-	            $this->billed=0;
2730
+	            $this->facturee = 0; // deprecated
2731
+	            $this->billed = 0;
2732 2732
 
2733 2733
 	            $this->db->commit();
2734 2734
 	            return 1;
2735 2735
 	        }
2736 2736
 	        else
2737 2737
 	        {
2738
-	            foreach($this->errors as $errmsg)
2738
+	            foreach ($this->errors as $errmsg)
2739 2739
 	            {
2740 2740
 	                dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
2741
-	                $this->error.=($this->error?', '.$errmsg:$errmsg);
2741
+	                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2742 2742
 	            }
2743 2743
 	            $this->db->rollback();
2744
-	            return -1*$error;
2744
+	            return -1 * $error;
2745 2745
 	        }
2746 2746
 	    }
2747 2747
 	    else
2748 2748
 	    {
2749
-	        $this->error=$this->db->error();
2749
+	        $this->error = $this->db->error();
2750 2750
 	        $this->db->rollback();
2751 2751
 	        return -1;
2752 2752
 	    }
@@ -2781,51 +2781,51 @@  discard block
 block discarded – undo
2781 2781
      * 	@param		int				$notrigger			disable line update trigger
2782 2782
      *  @return   	int              					< 0 if KO, > 0 if OK
2783 2783
      */
2784
-	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0,$txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
2784
+	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $price_base_type = 'HT', $info_bits = 0, $date_start = '', $date_end = '', $type = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0)
2785 2785
     {
2786 2786
         global $conf, $mysoc, $langs, $user;
2787 2787
 
2788 2788
         dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code");
2789 2789
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2790 2790
 
2791
-        if (! empty($this->brouillon))
2791
+        if (!empty($this->brouillon))
2792 2792
         {
2793 2793
             $this->db->begin();
2794 2794
 
2795 2795
             // Clean parameters
2796
-            if (empty($qty)) $qty=0;
2797
-            if (empty($info_bits)) $info_bits=0;
2798
-            if (empty($txtva)) $txtva=0;
2799
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2800
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2801
-            if (empty($remise)) $remise=0;
2802
-            if (empty($remise_percent)) $remise_percent=0;
2803
-            if (empty($special_code) || $special_code == 3) $special_code=0;
2804
-
2805
-            $remise_percent=price2num($remise_percent);
2806
-            $qty=price2num($qty);
2796
+            if (empty($qty)) $qty = 0;
2797
+            if (empty($info_bits)) $info_bits = 0;
2798
+            if (empty($txtva)) $txtva = 0;
2799
+            if (empty($txlocaltax1)) $txlocaltax1 = 0;
2800
+            if (empty($txlocaltax2)) $txlocaltax2 = 0;
2801
+            if (empty($remise)) $remise = 0;
2802
+            if (empty($remise_percent)) $remise_percent = 0;
2803
+            if (empty($special_code) || $special_code == 3) $special_code = 0;
2804
+
2805
+            $remise_percent = price2num($remise_percent);
2806
+            $qty = price2num($qty);
2807 2807
             $pu = price2num($pu);
2808
-      		$pa_ht=price2num($pa_ht);
2809
-            $txtva=price2num($txtva);
2810
-            $txlocaltax1=price2num($txlocaltax1);
2811
-            $txlocaltax2=price2num($txlocaltax2);
2808
+      		$pa_ht = price2num($pa_ht);
2809
+            $txtva = price2num($txtva);
2810
+            $txlocaltax1 = price2num($txlocaltax1);
2811
+            $txlocaltax2 = price2num($txlocaltax2);
2812 2812
 
2813 2813
             // Calcul du total TTC et de la TVA pour la ligne a partir de
2814 2814
             // qty, pu, remise_percent et txtva
2815 2815
             // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2816 2816
             // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2817 2817
 
2818
-            $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
2818
+            $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2819 2819
 
2820 2820
        		// Clean vat code
2821
-    		$vat_src_code='';
2821
+    		$vat_src_code = '';
2822 2822
     		if (preg_match('/\((.*)\)/', $txtva, $reg))
2823 2823
     		{
2824 2824
     		    $vat_src_code = $reg[1];
2825
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2825
+    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2826 2826
     		}
2827 2827
 
2828
-            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2828
+            $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2829 2829
 
2830 2830
             $total_ht  = $tabprice[0];
2831 2831
             $total_tva = $tabprice[1];
@@ -2837,7 +2837,7 @@  discard block
 block discarded – undo
2837 2837
 			$pu_ttc = $tabprice[5];
2838 2838
 
2839 2839
 			// MultiCurrency
2840
-			$multicurrency_total_ht  = $tabprice[16];
2840
+			$multicurrency_total_ht = $tabprice[16];
2841 2841
             $multicurrency_total_tva = $tabprice[17];
2842 2842
             $multicurrency_total_ttc = $tabprice[18];
2843 2843
 			$pu_ht_devise = $tabprice[19];
@@ -2855,7 +2855,7 @@  discard block
 block discarded – undo
2855 2855
             $remise = 0;
2856 2856
             if ($remise_percent > 0)
2857 2857
             {
2858
-                $remise = round(($pu * $remise_percent / 100),2);
2858
+                $remise = round(($pu * $remise_percent / 100), 2);
2859 2859
                 $price = ($pu - $remise);
2860 2860
             }
2861 2861
 
@@ -2865,14 +2865,14 @@  discard block
 block discarded – undo
2865 2865
 
2866 2866
             if (!empty($line->fk_product))
2867 2867
             {
2868
-                $product=new Product($this->db);
2869
-                $result=$product->fetch($line->fk_product);
2870
-                $product_type=$product->type;
2868
+                $product = new Product($this->db);
2869
+                $result = $product->fetch($line->fk_product);
2870
+                $product_type = $product->type;
2871 2871
 
2872
-                if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
2872
+                if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
2873 2873
                 {
2874 2874
                     $langs->load("errors");
2875
-                    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
2875
+                    $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
2876 2876
                     dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
2877 2877
                     $this->db->rollback();
2878 2878
                     return self::STOCK_NOT_ENOUGH_FOR_ORDER;
@@ -2886,18 +2886,18 @@  discard block
 block discarded – undo
2886 2886
             $this->line->context = $this->context;
2887 2887
 
2888 2888
             // Reorder if fk_parent_line change
2889
-            if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2889
+            if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2890 2890
             {
2891 2891
             	$rangmax = $this->line_max($fk_parent_line);
2892 2892
             	$this->line->rang = $rangmax + 1;
2893 2893
             }
2894 2894
 
2895
-            $this->line->rowid=$rowid;
2896
-            $this->line->label=$label;
2897
-            $this->line->desc=$desc;
2898
-            $this->line->qty=$qty;
2895
+            $this->line->rowid = $rowid;
2896
+            $this->line->label = $label;
2897
+            $this->line->desc = $desc;
2898
+            $this->line->qty = $qty;
2899 2899
 
2900
-            $this->line->vat_src_code	= $vat_src_code;
2900
+            $this->line->vat_src_code = $vat_src_code;
2901 2901
             $this->line->tva_tx         = $txtva;
2902 2902
             $this->line->localtax1_tx   = $txlocaltax1;
2903 2903
             $this->line->localtax2_tx   = $txlocaltax2;
@@ -2909,15 +2909,15 @@  discard block
 block discarded – undo
2909 2909
             $this->line->special_code   = $special_code;
2910 2910
             $this->line->total_ht       = $total_ht;
2911 2911
             $this->line->total_tva      = $total_tva;
2912
-            $this->line->total_localtax1= $total_localtax1;
2913
-            $this->line->total_localtax2= $total_localtax2;
2912
+            $this->line->total_localtax1 = $total_localtax1;
2913
+            $this->line->total_localtax2 = $total_localtax2;
2914 2914
             $this->line->total_ttc      = $total_ttc;
2915 2915
             $this->line->date_start     = $date_start;
2916 2916
             $this->line->date_end       = $date_end;
2917 2917
             $this->line->product_type   = $type;
2918 2918
             $this->line->fk_parent_line = $fk_parent_line;
2919
-            $this->line->skip_update_total=$skip_update_total;
2920
-	        $this->line->fk_unit        = $fk_unit;
2919
+            $this->line->skip_update_total = $skip_update_total;
2920
+	        $this->line->fk_unit = $fk_unit;
2921 2921
 
2922 2922
 			$this->line->fk_fournprice = $fk_fournprice;
2923 2923
 			$this->line->pa_ht = $pa_ht;
@@ -2929,18 +2929,18 @@  discard block
 block discarded – undo
2929 2929
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2930 2930
 
2931 2931
             // TODO deprecated
2932
-            $this->line->price=$price;
2933
-            $this->line->remise=$remise;
2932
+            $this->line->price = $price;
2933
+            $this->line->remise = $remise;
2934 2934
 
2935
-			if (is_array($array_options) && count($array_options)>0) {
2936
-				$this->line->array_options=$array_options;
2935
+			if (is_array($array_options) && count($array_options) > 0) {
2936
+				$this->line->array_options = $array_options;
2937 2937
 			}
2938 2938
 
2939
-            $result=$this->line->update($user, $notrigger);
2939
+            $result = $this->line->update($user, $notrigger);
2940 2940
             if ($result > 0)
2941 2941
             {
2942 2942
             	// Reorder if child line
2943
-            	if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2943
+            	if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
2944 2944
 
2945 2945
                 // Mise a jour info denormalisees
2946 2946
                 $this->update_price(1);
@@ -2950,7 +2950,7 @@  discard block
 block discarded – undo
2950 2950
             }
2951 2951
             else
2952 2952
             {
2953
-	            $this->error=$this->line->error;
2953
+	            $this->error = $this->line->error;
2954 2954
 
2955 2955
 	            $this->db->rollback();
2956 2956
 	            return -1;
@@ -2958,8 +2958,8 @@  discard block
 block discarded – undo
2958 2958
         }
2959 2959
         else
2960 2960
         {
2961
-            $this->error=get_class($this)."::updateline Order status makes operation forbidden";
2962
-        	$this->errors=array('OrderStatusMakeOperationForbidden');
2961
+            $this->error = get_class($this)."::updateline Order status makes operation forbidden";
2962
+        	$this->errors = array('OrderStatusMakeOperationForbidden');
2963 2963
             return -2;
2964 2964
         }
2965 2965
     }
@@ -2971,17 +2971,17 @@  discard block
 block discarded – undo
2971 2971
 	 *      @param      int		$notrigger	    0=launch triggers after, 1=disable triggers
2972 2972
 	 *      @return     int      			   	<0 if KO, >0 if OK
2973 2973
 	 */
2974
-	function update($user=null, $notrigger=0)
2974
+	function update($user = null, $notrigger = 0)
2975 2975
 	{
2976
-		$error=0;
2976
+		$error = 0;
2977 2977
 
2978 2978
 		// Clean parameters
2979
-		if (isset($this->ref)) $this->ref=trim($this->ref);
2980
-		if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
2981
-		if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2982
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
2983
-		if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
2984
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
2979
+		if (isset($this->ref)) $this->ref = trim($this->ref);
2980
+		if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client);
2981
+		if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2982
+		if (isset($this->note_public)) $this->note_public = trim($this->note_public);
2983
+		if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf);
2984
+		if (isset($this->import_key)) $this->import_key = trim($this->import_key);
2985 2985
 
2986 2986
 		// Check parameters
2987 2987
 		// Put here code to add control on parameters values
@@ -2989,44 +2989,44 @@  discard block
 block discarded – undo
2989 2989
 		// Update request
2990 2990
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commande SET";
2991 2991
 
2992
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
2993
-		$sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
2994
-		$sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").",";
2995
-		$sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
2996
-		$sql.= " date_commande=".(strval($this->date_commande)!='' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
2997
-		$sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2998
-		$sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
2999
-		$sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").",";
3000
-		$sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
3001
-		$sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
3002
-		$sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
3003
-		$sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
3004
-		$sql.= " fk_user_author=".(isset($this->user_author_id)?$this->user_author_id:"null").",";
3005
-		$sql.= " fk_user_valid=".(isset($this->user_valid)?$this->user_valid:"null").",";
3006
-		$sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
3007
-		$sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
3008
-		$sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
3009
-		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
3010
-		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
3011
-		$sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
3012
-		$sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
3013
-
3014
-		$sql.= " WHERE rowid=".$this->id;
2992
+		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2993
+		$sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
2994
+		$sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2995
+		$sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
2996
+		$sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
2997
+		$sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2998
+		$sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
2999
+		$sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
3000
+		$sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
3001
+		$sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
3002
+		$sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
3003
+		$sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
3004
+		$sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
3005
+		$sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").",";
3006
+		$sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
3007
+		$sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
3008
+		$sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
3009
+		$sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
3010
+		$sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
3011
+		$sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").",";
3012
+		$sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
3013
+
3014
+		$sql .= " WHERE rowid=".$this->id;
3015 3015
 
3016 3016
 		$this->db->begin();
3017 3017
 
3018 3018
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
3019 3019
 		$resql = $this->db->query($sql);
3020
-		if (! $resql) {
3021
-			$error++; $this->errors[]="Error ".$this->db->lasterror();
3020
+		if (!$resql) {
3021
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
3022 3022
 		}
3023 3023
 
3024
-		if (! $error)
3024
+		if (!$error)
3025 3025
 		{
3026
-			if (! $notrigger)
3026
+			if (!$notrigger)
3027 3027
 			{
3028 3028
 	            // Call trigger
3029
-	            $result=$this->call_trigger('ORDER_MODIFY',$user);
3029
+	            $result = $this->call_trigger('ORDER_MODIFY', $user);
3030 3030
 	            if ($result < 0) $error++;
3031 3031
 	            // End call triggers
3032 3032
 			}
@@ -3035,13 +3035,13 @@  discard block
 block discarded – undo
3035 3035
 		// Commit or rollback
3036 3036
 		if ($error)
3037 3037
 		{
3038
-			foreach($this->errors as $errmsg)
3038
+			foreach ($this->errors as $errmsg)
3039 3039
 			{
3040 3040
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3041
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
3041
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3042 3042
 			}
3043 3043
 			$this->db->rollback();
3044
-			return -1*$error;
3044
+			return -1 * $error;
3045 3045
 		}
3046 3046
 		else
3047 3047
 		{
@@ -3060,19 +3060,19 @@  discard block
 block discarded – undo
3060 3060
     {
3061 3061
         global $hookmanager, $conf;
3062 3062
 
3063
-    	$action='create';
3063
+    	$action = 'create';
3064 3064
         $error = 0;
3065 3065
 
3066 3066
     	// Actions on extra fields (by external module or standard code)
3067 3067
     	// TODO le hook fait double emploi avec le trigger !!
3068 3068
     	$hookmanager->initHooks(array('orderdao'));
3069
-    	$parameters=array('id'=>$this->id);
3070
-    	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3069
+    	$parameters = array('id'=>$this->id);
3070
+    	$reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3071 3071
     	if (empty($reshook))
3072 3072
     	{
3073 3073
     		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3074 3074
     		{
3075
-    			$result=$this->insertExtraFields();
3075
+    			$result = $this->insertExtraFields();
3076 3076
     			if ($result < 0)
3077 3077
     			{
3078 3078
     				$error++;
@@ -3099,42 +3099,42 @@  discard block
 block discarded – undo
3099 3099
      *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3100 3100
      * 	@return	int					<=0 if KO, >0 if OK
3101 3101
      */
3102
-    function delete($user, $notrigger=0)
3102
+    function delete($user, $notrigger = 0)
3103 3103
     {
3104 3104
         global $conf, $langs;
3105 3105
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3106 3106
 
3107 3107
         $error = 0;
3108 3108
 
3109
-        dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG);
3109
+        dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
3110 3110
 
3111 3111
         $this->db->begin();
3112 3112
 
3113
-        if (! $error && ! $notrigger)
3113
+        if (!$error && !$notrigger)
3114 3114
         {
3115 3115
             // Call trigger
3116
-            $result=$this->call_trigger('ORDER_DELETE',$user);
3116
+            $result = $this->call_trigger('ORDER_DELETE', $user);
3117 3117
             if ($result < 0) $error++;
3118 3118
             // End call triggers
3119 3119
         }
3120 3120
 
3121 3121
         //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail
3122
-        if (! $error)
3122
+        if (!$error)
3123 3123
         {
3124 3124
         	// Delete order details
3125 3125
         	$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id;
3126
-        	if (! $this->db->query($sql) )
3126
+        	if (!$this->db->query($sql))
3127 3127
         	{
3128 3128
         		$error++;
3129
-        		$this->errors[]=$this->db->lasterror();
3129
+        		$this->errors[] = $this->db->lasterror();
3130 3130
         	}
3131 3131
 
3132 3132
         	// Delete order
3133 3133
         	$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id;
3134
-        	if (! $this->db->query($sql) )
3134
+        	if (!$this->db->query($sql))
3135 3135
         	{
3136 3136
         		$error++;
3137
-        		$this->errors[]=$this->db->lasterror();
3137
+        		$this->errors[] = $this->db->lasterror();
3138 3138
         	}
3139 3139
 
3140 3140
         	// Delete linked object
@@ -3146,9 +3146,9 @@  discard block
 block discarded – undo
3146 3146
         	if ($res < 0) $error++;
3147 3147
 
3148 3148
         	// Remove extrafields
3149
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3149
+        	if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3150 3150
         	{
3151
-        		$result=$this->deleteExtraFields();
3151
+        		$result = $this->deleteExtraFields();
3152 3152
         		if ($result < 0)
3153 3153
         		{
3154 3154
         			$error++;
@@ -3160,13 +3160,13 @@  discard block
 block discarded – undo
3160 3160
         	$comref = dol_sanitizeFileName($this->ref);
3161 3161
         	if ($conf->commande->dir_output && !empty($this->ref))
3162 3162
         	{
3163
-        		$dir = $conf->commande->dir_output . "/" . $comref ;
3164
-        		$file = $conf->commande->dir_output . "/" . $comref . "/" . $comref . ".pdf";
3163
+        		$dir = $conf->commande->dir_output."/".$comref;
3164
+        		$file = $conf->commande->dir_output."/".$comref."/".$comref.".pdf";
3165 3165
         		if (file_exists($file))	// We must delete all files before deleting directory
3166 3166
         		{
3167 3167
         			dol_delete_preview($this);
3168 3168
 
3169
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
3169
+        			if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
3170 3170
         			{
3171 3171
         				$this->db->rollback();
3172 3172
         				return 0;
@@ -3174,9 +3174,9 @@  discard block
 block discarded – undo
3174 3174
         		}
3175 3175
         		if (file_exists($dir))
3176 3176
         		{
3177
-        			if (! dol_delete_dir_recursive($dir))
3177
+        			if (!dol_delete_dir_recursive($dir))
3178 3178
         			{
3179
-        				$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
3179
+        				$this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
3180 3180
         				$this->db->rollback();
3181 3181
         				return 0;
3182 3182
         			}
@@ -3186,19 +3186,19 @@  discard block
 block discarded – undo
3186 3186
 
3187 3187
         }
3188 3188
 
3189
-        if (! $error)
3189
+        if (!$error)
3190 3190
         {
3191 3191
         	$this->db->commit();
3192 3192
         	return 1;
3193 3193
         }
3194 3194
         else
3195 3195
         {
3196
-	        foreach($this->errors as $errmsg)
3196
+	        foreach ($this->errors as $errmsg)
3197 3197
 	        {
3198
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
3198
+		        $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3199 3199
 	        }
3200 3200
 	        $this->db->rollback();
3201
-	        return -1*$error;
3201
+	        return -1 * $error;
3202 3202
         }
3203 3203
     }
3204 3204
 
@@ -3216,30 +3216,30 @@  discard block
 block discarded – undo
3216 3216
         $clause = " WHERE";
3217 3217
 
3218 3218
         $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut";
3219
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
3219
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
3220 3220
         if (!$user->rights->societe->client->voir && !$user->societe_id)
3221 3221
         {
3222
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3223
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3222
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3223
+            $sql .= " WHERE sc.fk_user = ".$user->id;
3224 3224
             $clause = " AND";
3225 3225
         }
3226
-        $sql.= $clause." c.entity IN (".getEntity('commande').")";
3226
+        $sql .= $clause." c.entity IN (".getEntity('commande').")";
3227 3227
         //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3228
-        $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))";    // If status is 2 and facture=1, it must be selected
3229
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
3228
+        $sql .= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected
3229
+        if ($user->societe_id) $sql .= " AND c.fk_soc = ".$user->societe_id;
3230 3230
 
3231
-        $resql=$this->db->query($sql);
3231
+        $resql = $this->db->query($sql);
3232 3232
         if ($resql)
3233 3233
         {
3234 3234
 	        $response = new WorkboardResponse();
3235
-	        $response->warning_delay=$conf->commande->client->warning_delay/60/60/24;
3236
-	        $response->label=$langs->trans("OrdersToProcess");
3237
-	        $response->url=DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
3238
-	        $response->img=img_object('',"order");
3235
+	        $response->warning_delay = $conf->commande->client->warning_delay / 60 / 60 / 24;
3236
+	        $response->label = $langs->trans("OrdersToProcess");
3237
+	        $response->url = DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
3238
+	        $response->img = img_object('', "order");
3239 3239
 
3240 3240
             $generic_commande = new Commande($this->db);
3241 3241
 
3242
-            while ($obj=$this->db->fetch_object($resql))
3242
+            while ($obj = $this->db->fetch_object($resql))
3243 3243
             {
3244 3244
                 $response->nbtodo++;
3245 3245
 
@@ -3256,7 +3256,7 @@  discard block
 block discarded – undo
3256 3256
         }
3257 3257
         else
3258 3258
         {
3259
-            $this->error=$this->db->error();
3259
+            $this->error = $this->db->error();
3260 3260
             return -1;
3261 3261
         }
3262 3262
     }
@@ -3270,7 +3270,7 @@  discard block
 block discarded – undo
3270 3270
     {
3271 3271
         global $langs;
3272 3272
 
3273
-        $label=$langs->trans('OrderSource'.$this->source);
3273
+        $label = $langs->trans('OrderSource'.$this->source);
3274 3274
 
3275 3275
         if ($label == 'OrderSource') return '';
3276 3276
         return $label;
@@ -3284,8 +3284,8 @@  discard block
 block discarded – undo
3284 3284
      */
3285 3285
     function getLibStatut($mode)
3286 3286
     {
3287
-        if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility
3288
-        return $this->LibStatut($this->statut,$this->billed,$mode);
3287
+        if ($this->facturee && empty($this->billed)) $this->billed = $this->facturee; // For backward compatibility
3288
+        return $this->LibStatut($this->statut, $this->billed, $mode);
3289 3289
     }
3290 3290
 
3291 3291
     /**
@@ -3297,73 +3297,73 @@  discard block
 block discarded – undo
3297 3297
      *  @param      int     $donotshowbilled  Do not show billed status after order status
3298 3298
      *  @return     string					  Label of status
3299 3299
      */
3300
-    function LibStatut($statut,$billed,$mode,$donotshowbilled=0)
3300
+    function LibStatut($statut, $billed, $mode, $donotshowbilled = 0)
3301 3301
     {
3302 3302
         global $langs, $conf;
3303 3303
 
3304 3304
         $billedtext = '';
3305
-        if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3305
+        if (empty($donotshowbilled)) $billedtext .= ($billed ? ' - '.$langs->trans("Billed") : '');
3306 3306
 
3307 3307
         //print 'x'.$statut.'-'.$billed;
3308 3308
         if ($mode == 0)
3309 3309
         {
3310
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3311
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3312
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3313
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3314
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3315
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3316
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3310
+            if ($statut == self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3311
+            if ($statut == self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3312
+            if ($statut == self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3313
+            if ($statut == self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3314
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3315
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3316
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3317 3317
         }
3318 3318
         elseif ($mode == 1)
3319 3319
         {
3320
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3321
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3322
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3323
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3324
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3325
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3326
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3320
+            if ($statut == self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3321
+            if ($statut == self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3322
+            if ($statut == self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3323
+            if ($statut == self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3324
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3325
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3326
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3327 3327
         }
3328 3328
         elseif ($mode == 2)
3329 3329
         {
3330
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3331
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3332
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3333
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3334
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3335
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3336
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3330
+            if ($statut == self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'), 'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3331
+            if ($statut == self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'), 'statut0').' '.$langs->trans('StatusOrderDraftShort');
3332
+            if ($statut == self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'), 'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3333
+            if ($statut == self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'), 'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3334
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'), 'statut4').' '.$langs->trans('StatusOrderToBillShort');
3335
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext, 'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3336
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'), 'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3337 3337
         }
3338 3338
         elseif ($mode == 3)
3339 3339
         {
3340
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3341
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3342
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3343
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3344
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3345
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3346
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3340
+            if ($statut == self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
3341
+            if ($statut == self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'), 'statut0');
3342
+            if ($statut == self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext, 'statut1');
3343
+            if ($statut == self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext, 'statut3');
3344
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'), 'statut4');
3345
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext, 'statut6');
3346
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'), 'statut6');
3347 3347
         }
3348 3348
         elseif ($mode == 4)
3349 3349
         {
3350
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3351
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3352
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3353
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3354
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3355
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3356
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3350
+            if ($statut == self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'), 'statut5').' '.$langs->trans('StatusOrderCanceled');
3351
+            if ($statut == self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'), 'statut0').' '.$langs->trans('StatusOrderDraft');
3352
+            if ($statut == self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext, 'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3353
+            if ($statut == self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext, 'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3354
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'), 'statut4').' '.$langs->trans('StatusOrderToBill');
3355
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext, 'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3356
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'), 'statut6').' '.$langs->trans('StatusOrderDelivered');
3357 3357
         }
3358 3358
         elseif ($mode == 5)
3359 3359
         {
3360
-            if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3361
-            if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3362
-            if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3363
-            if ($statut==self::STATUS_ACCEPTED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3364
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3365
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3366
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3360
+            if ($statut == self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
3361
+            if ($statut == self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'), 'statut0');
3362
+            if ($statut == self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext, 'statut1');
3363
+            if ($statut == self::STATUS_ACCEPTED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext, 'statut3');
3364
+            if ($statut == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'), 'statut4');
3365
+            if ($statut == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext, 'statut6');
3366
+            if ($statut == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'), 'statut6');
3367 3367
         }
3368 3368
     }
3369 3369
 
@@ -3379,23 +3379,23 @@  discard block
 block discarded – undo
3379 3379
      *  @param      int         $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
3380 3380
      *	@return     string          			          String with URL
3381 3381
      */
3382
-    function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
3382
+    function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1)
3383 3383
     {
3384 3384
         global $conf, $langs, $user;
3385 3385
 
3386
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3386
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
3387 3387
 
3388
-        $result='';
3388
+        $result = '';
3389 3389
 
3390
-        if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3390
+        if (!empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3391 3391
         else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3392 3392
 
3393 3393
         if ($option !== 'nolink')
3394 3394
         {
3395 3395
             // Add param to save lastsearch_values or not
3396
-            $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3397
-            if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3398
-            if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3396
+            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3397
+            if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
3398
+            if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
3399 3399
         }
3400 3400
 
3401 3401
         if ($short) return $url;
@@ -3411,32 +3411,32 @@  discard block
 block discarded – undo
3411 3411
 				$label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3412 3412
 			}
3413 3413
 			if (!empty($this->total_tva)) {
3414
-				$label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1,	$conf->currency);
3414
+				$label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3415 3415
 			}
3416 3416
 			if (!empty($this->total_ttc)) {
3417 3417
 				$label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3418 3418
 			}
3419 3419
 		}
3420 3420
 
3421
-		$linkclose='';
3421
+		$linkclose = '';
3422 3422
 		if (empty($notooltip) && $user->rights->commande->lire)
3423 3423
 		{
3424
-		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3424
+		    if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3425 3425
 		    {
3426
-		        $label=$langs->trans("ShowOrder");
3427
-		        $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3426
+		        $label = $langs->trans("ShowOrder");
3427
+		        $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3428 3428
 		    }
3429
-		    $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3430
-		    $linkclose.=' class="classfortooltip"';
3429
+		    $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
3430
+		    $linkclose .= ' class="classfortooltip"';
3431 3431
 		}
3432 3432
 
3433 3433
         $linkstart = '<a href="'.$url.'"';
3434
-        $linkstart.=$linkclose.'>';
3435
-        $linkend='</a>';
3434
+        $linkstart .= $linkclose.'>';
3435
+        $linkend = '</a>';
3436 3436
 
3437
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3438
-        if ($withpicto && $withpicto != 2) $result.=' ';
3439
-        $result.=$linkstart.$this->ref.$linkend;
3437
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
3438
+        if ($withpicto && $withpicto != 2) $result .= ' ';
3439
+        $result .= $linkstart.$this->ref.$linkend;
3440 3440
         return $result;
3441 3441
     }
3442 3442
 
@@ -3450,12 +3450,12 @@  discard block
 block discarded – undo
3450 3450
     function info($id)
3451 3451
     {
3452 3452
         $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
3453
-        $sql.= ' date_valid as datev,';
3454
-        $sql.= ' date_cloture as datecloture,';
3455
-        $sql.= ' fk_user_author, fk_user_valid, fk_user_cloture';
3456
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
3457
-        $sql.= ' WHERE c.rowid = '.$id;
3458
-        $result=$this->db->query($sql);
3453
+        $sql .= ' date_valid as datev,';
3454
+        $sql .= ' date_cloture as datecloture,';
3455
+        $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture';
3456
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
3457
+        $sql .= ' WHERE c.rowid = '.$id;
3458
+        $result = $this->db->query($sql);
3459 3459
         if ($result)
3460 3460
         {
3461 3461
             if ($this->db->num_rows($result))
@@ -3466,7 +3466,7 @@  discard block
 block discarded – undo
3466 3466
                 {
3467 3467
                     $cuser = new User($this->db);
3468 3468
                     $cuser->fetch($obj->fk_user_author);
3469
-                    $this->user_creation   = $cuser;
3469
+                    $this->user_creation = $cuser;
3470 3470
                 }
3471 3471
 
3472 3472
                 if ($obj->fk_user_valid)
@@ -3480,7 +3480,7 @@  discard block
 block discarded – undo
3480 3480
                 {
3481 3481
                     $cluser = new User($this->db);
3482 3482
                     $cluser->fetch($obj->fk_user_cloture);
3483
-                    $this->user_cloture   = $cluser;
3483
+                    $this->user_cloture = $cluser;
3484 3484
                 }
3485 3485
 
3486 3486
                 $this->date_creation     = $this->db->jdate($obj->datec);
@@ -3516,8 +3516,8 @@  discard block
 block discarded – undo
3516 3516
         $num_prods = 0;
3517 3517
         $prodids = array();
3518 3518
         $sql = "SELECT rowid";
3519
-        $sql.= " FROM ".MAIN_DB_PREFIX."product";
3520
-        $sql.= " WHERE entity IN (".getEntity('product').")";
3519
+        $sql .= " FROM ".MAIN_DB_PREFIX."product";
3520
+        $sql .= " WHERE entity IN (".getEntity('product').")";
3521 3521
         $resql = $this->db->query($sql);
3522 3522
         if ($resql)
3523 3523
         {
@@ -3532,52 +3532,52 @@  discard block
 block discarded – undo
3532 3532
         }
3533 3533
 
3534 3534
         // Initialise parametres
3535
-        $this->id=0;
3535
+        $this->id = 0;
3536 3536
         $this->ref = 'SPECIMEN';
3537
-        $this->specimen=1;
3537
+        $this->specimen = 1;
3538 3538
         $this->socid = 1;
3539 3539
         $this->date = time();
3540
-        $this->date_lim_reglement=$this->date+3600*24*30;
3540
+        $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3541 3541
         $this->cond_reglement_code = 'RECEP';
3542 3542
         $this->mode_reglement_code = 'CHQ';
3543 3543
         $this->availability_code   = 'DSP';
3544 3544
         $this->demand_reason_code  = 'SRC_00';
3545
-        $this->note_public='This is a comment (public)';
3546
-        $this->note_private='This is a comment (private)';
3545
+        $this->note_public = 'This is a comment (public)';
3546
+        $this->note_private = 'This is a comment (private)';
3547 3547
         // Lines
3548 3548
         $nbp = 5;
3549 3549
         $xnbp = 0;
3550 3550
         while ($xnbp < $nbp)
3551 3551
         {
3552
-            $line=new OrderLine($this->db);
3552
+            $line = new OrderLine($this->db);
3553 3553
 
3554
-            $line->desc=$langs->trans("Description")." ".$xnbp;
3555
-            $line->qty=1;
3556
-            $line->subprice=100;
3557
-            $line->price=100;
3558
-            $line->tva_tx=20;
3554
+            $line->desc = $langs->trans("Description")." ".$xnbp;
3555
+            $line->qty = 1;
3556
+            $line->subprice = 100;
3557
+            $line->price = 100;
3558
+            $line->tva_tx = 20;
3559 3559
             if ($xnbp == 2)
3560 3560
             {
3561
-                $line->total_ht=50;
3562
-                $line->total_ttc=60;
3563
-                $line->total_tva=10;
3564
-                $line->remise_percent=50;
3561
+                $line->total_ht = 50;
3562
+                $line->total_ttc = 60;
3563
+                $line->total_tva = 10;
3564
+                $line->remise_percent = 50;
3565 3565
             }
3566 3566
             else
3567 3567
             {
3568
-                $line->total_ht=100;
3569
-                $line->total_ttc=120;
3570
-                $line->total_tva=20;
3571
-                $line->remise_percent=0;
3568
+                $line->total_ht = 100;
3569
+                $line->total_ttc = 120;
3570
+                $line->total_tva = 20;
3571
+                $line->remise_percent = 0;
3572 3572
             }
3573 3573
             if ($num_prods > 0)
3574 3574
             {
3575 3575
             	$prodid = mt_rand(1, $num_prods);
3576
-            	$line->fk_product=$prodids[$prodid];
3577
-				$line->product_ref='SPECIMEN';
3576
+            	$line->fk_product = $prodids[$prodid];
3577
+				$line->product_ref = 'SPECIMEN';
3578 3578
             }
3579 3579
 
3580
-            $this->lines[$xnbp]=$line;
3580
+            $this->lines[$xnbp] = $line;
3581 3581
 
3582 3582
             $this->total_ht       += $line->total_ht;
3583 3583
             $this->total_tva      += $line->total_tva;
@@ -3597,26 +3597,26 @@  discard block
 block discarded – undo
3597 3597
     {
3598 3598
         global $user;
3599 3599
 
3600
-        $this->nb=array();
3600
+        $this->nb = array();
3601 3601
         $clause = "WHERE";
3602 3602
 
3603 3603
         $sql = "SELECT count(co.rowid) as nb";
3604
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande as co";
3605
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3604
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande as co";
3605
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3606 3606
         if (!$user->rights->societe->client->voir && !$user->societe_id)
3607 3607
         {
3608
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3609
-            $sql.= " WHERE sc.fk_user = " .$user->id;
3608
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3609
+            $sql .= " WHERE sc.fk_user = ".$user->id;
3610 3610
             $clause = "AND";
3611 3611
         }
3612
-        $sql.= " ".$clause." co.entity IN (".getEntity('commande').")";
3612
+        $sql .= " ".$clause." co.entity IN (".getEntity('commande').")";
3613 3613
 
3614
-        $resql=$this->db->query($sql);
3614
+        $resql = $this->db->query($sql);
3615 3615
         if ($resql)
3616 3616
         {
3617
-            while ($obj=$this->db->fetch_object($resql))
3617
+            while ($obj = $this->db->fetch_object($resql))
3618 3618
             {
3619
-                $this->nb["orders"]=$obj->nb;
3619
+                $this->nb["orders"] = $obj->nb;
3620 3620
             }
3621 3621
             $this->db->free($resql);
3622 3622
             return 1;
@@ -3624,7 +3624,7 @@  discard block
 block discarded – undo
3624 3624
         else
3625 3625
         {
3626 3626
             dol_print_error($this->db);
3627
-            $this->error=$this->db->error();
3627
+            $this->error = $this->db->error();
3628 3628
             return -1;
3629 3629
         }
3630 3630
     }
@@ -3649,19 +3649,19 @@  discard block
 block discarded – undo
3649 3649
 	 *  @param      int			$hideref        Hide ref
3650 3650
 	 *  @return     int         				0 if KO, 1 if OK
3651 3651
 	 */
3652
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
3652
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
3653 3653
 	{
3654
-		global $conf,$langs;
3654
+		global $conf, $langs;
3655 3655
 
3656 3656
 		$langs->load("orders");
3657 3657
 
3658
-		if (! dol_strlen($modele)) {
3658
+		if (!dol_strlen($modele)) {
3659 3659
 
3660 3660
 			$modele = 'einstein';
3661 3661
 
3662 3662
 			if ($this->modelpdf) {
3663 3663
 				$modele = $this->modelpdf;
3664
-			} elseif (! empty($conf->global->COMMANDE_ADDON_PDF)) {
3664
+			} elseif (!empty($conf->global->COMMANDE_ADDON_PDF)) {
3665 3665
 				$modele = $conf->global->COMMANDE_ADDON_PDF;
3666 3666
 			}
3667 3667
 		}
@@ -3698,8 +3698,8 @@  discard block
 block discarded – undo
3698 3698
     {
3699 3699
         global $conf;
3700 3700
 
3701
-        if (! ($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
3702
-            return false;   // Never late if not inside this status range
3701
+        if (!($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
3702
+            return false; // Never late if not inside this status range
3703 3703
         }
3704 3704
 
3705 3705
         $now = dol_now();
@@ -3716,9 +3716,9 @@  discard block
 block discarded – undo
3716 3716
     {
3717 3717
         global $conf, $langs;
3718 3718
 
3719
-        if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3720
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3721
-        $text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3719
+        if (empty($this->date_livraison)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3720
+        else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3721
+        $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3722 3722
 
3723 3723
         return $text;
3724 3724
     }
@@ -3730,8 +3730,8 @@  discard block
 block discarded – undo
3730 3730
  */
3731 3731
 class OrderLine extends CommonOrderLine
3732 3732
 {
3733
-	public $element='commandedet';
3734
-	public $table_element='commandedet';
3733
+	public $element = 'commandedet';
3734
+	public $table_element = 'commandedet';
3735 3735
 
3736 3736
     var $oldline;
3737 3737
 
@@ -3786,7 +3786,7 @@  discard block
 block discarded – undo
3786 3786
      */
3787 3787
     function __construct($db)
3788 3788
     {
3789
-        $this->db= $db;
3789
+        $this->db = $db;
3790 3790
     }
3791 3791
 
3792 3792
     /**
@@ -3798,15 +3798,15 @@  discard block
 block discarded – undo
3798 3798
     function fetch($rowid)
3799 3799
     {
3800 3800
         $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,';
3801
-        $sql.= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,';
3802
-        $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
3803
-	    $sql.= ' cd.fk_unit,';
3804
-		$sql.= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
3805
-        $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,';
3806
-        $sql.= ' cd.date_start, cd.date_end';
3807
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
3808
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3809
-        $sql.= ' WHERE cd.rowid = '.$rowid;
3801
+        $sql .= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,';
3802
+        $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
3803
+	    $sql .= ' cd.fk_unit,';
3804
+		$sql .= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
3805
+        $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,';
3806
+        $sql .= ' cd.date_start, cd.date_end';
3807
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
3808
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3809
+        $sql .= ' WHERE cd.rowid = '.$rowid;
3810 3810
         $result = $this->db->query($sql);
3811 3811
         if ($result)
3812 3812
         {
@@ -3829,24 +3829,24 @@  discard block
 block discarded – undo
3829 3829
             $this->fk_product       = $objp->fk_product;
3830 3830
             $this->product_type     = $objp->product_type;
3831 3831
             $this->info_bits        = $objp->info_bits;
3832
-			$this->special_code		= $objp->special_code;
3832
+			$this->special_code = $objp->special_code;
3833 3833
             $this->total_ht         = $objp->total_ht;
3834 3834
             $this->total_tva        = $objp->total_tva;
3835 3835
             $this->total_localtax1  = $objp->total_localtax1;
3836 3836
             $this->total_localtax2  = $objp->total_localtax2;
3837 3837
             $this->total_ttc        = $objp->total_ttc;
3838
-			$this->fk_fournprice	= $objp->fk_fournprice;
3838
+			$this->fk_fournprice = $objp->fk_fournprice;
3839 3839
 			$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
3840 3840
 			$this->pa_ht			= $marginInfos[0];
3841 3841
 			$this->marge_tx			= $marginInfos[1];
3842 3842
 			$this->marque_tx		= $marginInfos[2];
3843
-            $this->special_code		= $objp->special_code;
3844
-            $this->rang             = $objp->rang;
3843
+            $this->special_code = $objp->special_code;
3844
+            $this->rang = $objp->rang;
3845 3845
 
3846
-            $this->ref				= $objp->product_ref;      // deprecated
3847
-            $this->product_ref		= $objp->product_ref;
3848
-            $this->libelle			= $objp->product_libelle;  // deprecated
3849
-            $this->product_label	= $objp->product_libelle;
3846
+            $this->ref = $objp->product_ref; // deprecated
3847
+            $this->product_ref = $objp->product_ref;
3848
+            $this->libelle = $objp->product_libelle; // deprecated
3849
+            $this->product_label = $objp->product_libelle;
3850 3850
             $this->product_desc     = $objp->product_desc;
3851 3851
             $this->product_tobatch  = $objp->product_tobatch;
3852 3852
             $this->fk_unit          = $objp->fk_unit;
@@ -3854,8 +3854,8 @@  discard block
 block discarded – undo
3854 3854
             $this->date_start       = $this->db->jdate($objp->date_start);
3855 3855
             $this->date_end         = $this->db->jdate($objp->date_end);
3856 3856
 
3857
-			$this->fk_multicurrency			= $objp->fk_multicurrency;
3858
-			$this->multicurrency_code		= $objp->multicurrency_code;
3857
+			$this->fk_multicurrency = $objp->fk_multicurrency;
3858
+			$this->multicurrency_code = $objp->multicurrency_code;
3859 3859
 			$this->multicurrency_subprice	= $objp->multicurrency_subprice;
3860 3860
 			$this->multicurrency_total_ht	= $objp->multicurrency_total_ht;
3861 3861
 			$this->multicurrency_total_tva	= $objp->multicurrency_total_tva;
@@ -3879,25 +3879,25 @@  discard block
 block discarded – undo
3879 3879
 	 *  @param      int		$notrigger	    0=launch triggers after, 1=disable triggers
3880 3880
      *	@return	 int  <0 si ko, >0 si ok
3881 3881
      */
3882
-    function delete($user=null, $notrigger=0)
3882
+    function delete($user = null, $notrigger = 0)
3883 3883
     {
3884 3884
         global $conf, $user, $langs;
3885 3885
 
3886
-		$error=0;
3886
+		$error = 0;
3887 3887
 
3888 3888
 	    $this->db->begin();
3889 3889
 
3890 3890
         $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid=".$this->rowid;
3891 3891
 
3892 3892
         dol_syslog("OrderLine::delete", LOG_DEBUG);
3893
-        $resql=$this->db->query($sql);
3893
+        $resql = $this->db->query($sql);
3894 3894
         if ($resql)
3895 3895
         {
3896 3896
 			// Remove extrafields
3897
-			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3897
+			if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3898 3898
 			{
3899
-				$this->id=$this->rowid;
3900
-				$result=$this->deleteExtraFields();
3899
+				$this->id = $this->rowid;
3900
+				$result = $this->deleteExtraFields();
3901 3901
 				if ($result < 0)
3902 3902
 				{
3903 3903
 					$error++;
@@ -3905,10 +3905,10 @@  discard block
 block discarded – undo
3905 3905
 				}
3906 3906
 			}
3907 3907
 
3908
-			if (! $error && ! $notrigger)
3908
+			if (!$error && !$notrigger)
3909 3909
 			{
3910 3910
 	            // Call trigger
3911
-	            $result=$this->call_trigger('LINEORDER_DELETE',$user);
3911
+	            $result = $this->call_trigger('LINEORDER_DELETE', $user);
3912 3912
 	            if ($result < 0) $error++;
3913 3913
 	            // End call triggers
3914 3914
 			}
@@ -3918,17 +3918,17 @@  discard block
 block discarded – undo
3918 3918
 		        return 1;
3919 3919
 	        }
3920 3920
 
3921
-	        foreach($this->errors as $errmsg)
3921
+	        foreach ($this->errors as $errmsg)
3922 3922
 	        {
3923 3923
 		        dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3924
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
3924
+		        $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3925 3925
 	        }
3926 3926
 	        $this->db->rollback();
3927
-	        return -1*$error;
3927
+	        return -1 * $error;
3928 3928
         }
3929 3929
         else
3930 3930
         {
3931
-            $this->error=$this->db->lasterror();
3931
+            $this->error = $this->db->lasterror();
3932 3932
             return -1;
3933 3933
         }
3934 3934
     }
@@ -3940,31 +3940,31 @@  discard block
 block discarded – undo
3940 3940
      *	@param      int		$notrigger		1 = disable triggers
3941 3941
      *	@return		int						<0 if KO, >0 if OK
3942 3942
      */
3943
-    function insert($user=null, $notrigger=0)
3943
+    function insert($user = null, $notrigger = 0)
3944 3944
     {
3945 3945
         global $langs, $conf;
3946 3946
 
3947
-		$error=0;
3947
+		$error = 0;
3948 3948
 
3949 3949
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
3950 3950
 
3951 3951
         dol_syslog(get_class($this)."::insert rang=".$this->rang);
3952 3952
 
3953 3953
         // Clean parameters
3954
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3955
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3956
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3957
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3958
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3959
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3960
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3961
-        if (empty($this->rang)) $this->rang=0;
3962
-        if (empty($this->remise)) $this->remise=0;
3963
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3964
-        if (empty($this->info_bits)) $this->info_bits=0;
3965
-        if (empty($this->special_code)) $this->special_code=0;
3966
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3967
-		if (empty($this->pa_ht)) $this->pa_ht=0;
3954
+        if (empty($this->tva_tx)) $this->tva_tx = 0;
3955
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
3956
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
3957
+		if (empty($this->localtax1_type)) $this->localtax1_type = 0;
3958
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
3959
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
3960
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
3961
+        if (empty($this->rang)) $this->rang = 0;
3962
+        if (empty($this->remise)) $this->remise = 0;
3963
+        if (empty($this->remise_percent)) $this->remise_percent = 0;
3964
+        if (empty($this->info_bits)) $this->info_bits = 0;
3965
+        if (empty($this->special_code)) $this->special_code = 0;
3966
+        if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
3967
+		if (empty($this->pa_ht)) $this->pa_ht = 0;
3968 3968
 
3969 3969
 		// if buy price not defined, define buyprice as configured in margin admin
3970 3970
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3986,73 +3986,73 @@  discard block
 block discarded – undo
3986 3986
 
3987 3987
         // Insertion dans base de la ligne
3988 3988
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
3989
-        $sql.= ' (fk_commande, fk_parent_line, label, description, qty, ';
3990
-        $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3991
-        $sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
3992
-        $sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
3993
-        $sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
3994
-	    $sql.= ' fk_unit';
3995
-		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3996
-		$sql.= ')';
3997
-        $sql.= " VALUES (".$this->fk_commande.",";
3998
-        $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
3999
-        $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4000
-        $sql.= " '".$this->db->escape($this->desc)."',";
4001
-        $sql.= " '".price2num($this->qty)."',";
4002
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4003
-        $sql.= " '".price2num($this->tva_tx)."',";
4004
-        $sql.= " '".price2num($this->localtax1_tx)."',";
4005
-        $sql.= " '".price2num($this->localtax2_tx)."',";
4006
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
4007
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
4008
-        $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
4009
-        $sql.= " '".$this->db->escape($this->product_type)."',";
4010
-        $sql.= " '".price2num($this->remise_percent)."',";
4011
-        $sql.= " ".($this->subprice!=''?"'".price2num($this->subprice)."'":"null").",";
4012
-        $sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").",";
4013
-        $sql.= " '".price2num($this->remise)."',";
4014
-        $sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
4015
-        $sql.= ' '.$this->special_code.',';
4016
-        $sql.= ' '.$this->rang.',';
4017
-		$sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
4018
-		$sql.= ' '.price2num($this->pa_ht).',';
4019
-        $sql.= " '".$this->db->escape($this->info_bits)."',";
4020
-        $sql.= " '".price2num($this->total_ht)."',";
4021
-        $sql.= " '".price2num($this->total_tva)."',";
4022
-        $sql.= " '".price2num($this->total_localtax1)."',";
4023
-        $sql.= " '".price2num($this->total_localtax2)."',";
4024
-        $sql.= " '".price2num($this->total_ttc)."',";
4025
-        $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
4026
-        $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").',';
4027
-	    $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4028
-		$sql.= ", ".$this->fk_multicurrency;
4029
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
4030
-		$sql.= ", ".$this->multicurrency_subprice;
4031
-		$sql.= ", ".$this->multicurrency_total_ht;
4032
-		$sql.= ", ".$this->multicurrency_total_tva;
4033
-		$sql.= ", ".$this->multicurrency_total_ttc;
4034
-        $sql.= ')';
3989
+        $sql .= ' (fk_commande, fk_parent_line, label, description, qty, ';
3990
+        $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3991
+        $sql .= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
3992
+        $sql .= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
3993
+        $sql .= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
3994
+	    $sql .= ' fk_unit';
3995
+		$sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3996
+		$sql .= ')';
3997
+        $sql .= " VALUES (".$this->fk_commande.",";
3998
+        $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
3999
+        $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
4000
+        $sql .= " '".$this->db->escape($this->desc)."',";
4001
+        $sql .= " '".price2num($this->qty)."',";
4002
+        $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
4003
+        $sql .= " '".price2num($this->tva_tx)."',";
4004
+        $sql .= " '".price2num($this->localtax1_tx)."',";
4005
+        $sql .= " '".price2num($this->localtax2_tx)."',";
4006
+		$sql .= " '".$this->db->escape($this->localtax1_type)."',";
4007
+		$sql .= " '".$this->db->escape($this->localtax2_type)."',";
4008
+        $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").',';
4009
+        $sql .= " '".$this->db->escape($this->product_type)."',";
4010
+        $sql .= " '".price2num($this->remise_percent)."',";
4011
+        $sql .= " ".($this->subprice != '' ? "'".price2num($this->subprice)."'" : "null").",";
4012
+        $sql .= " ".($this->price != '' ? "'".price2num($this->price)."'" : "null").",";
4013
+        $sql .= " '".price2num($this->remise)."',";
4014
+        $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
4015
+        $sql .= ' '.$this->special_code.',';
4016
+        $sql .= ' '.$this->rang.',';
4017
+		$sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
4018
+		$sql .= ' '.price2num($this->pa_ht).',';
4019
+        $sql .= " '".$this->db->escape($this->info_bits)."',";
4020
+        $sql .= " '".price2num($this->total_ht)."',";
4021
+        $sql .= " '".price2num($this->total_tva)."',";
4022
+        $sql .= " '".price2num($this->total_localtax1)."',";
4023
+        $sql .= " '".price2num($this->total_localtax2)."',";
4024
+        $sql .= " '".price2num($this->total_ttc)."',";
4025
+        $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
4026
+        $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").',';
4027
+	    $sql .= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4028
+		$sql .= ", ".$this->fk_multicurrency;
4029
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
4030
+		$sql .= ", ".$this->multicurrency_subprice;
4031
+		$sql .= ", ".$this->multicurrency_total_ht;
4032
+		$sql .= ", ".$this->multicurrency_total_tva;
4033
+		$sql .= ", ".$this->multicurrency_total_ttc;
4034
+        $sql .= ')';
4035 4035
 
4036 4036
         dol_syslog(get_class($this)."::insert", LOG_DEBUG);
4037
-        $resql=$this->db->query($sql);
4037
+        $resql = $this->db->query($sql);
4038 4038
         if ($resql)
4039 4039
         {
4040
-            $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4040
+            $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4041 4041
 
4042 4042
 			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4043 4043
 			{
4044
-				$this->id=$this->rowid;
4045
-				$result=$this->insertExtraFields();
4044
+				$this->id = $this->rowid;
4045
+				$result = $this->insertExtraFields();
4046 4046
 				if ($result < 0)
4047 4047
 				{
4048 4048
 					$error++;
4049 4049
 				}
4050 4050
 			}
4051 4051
 
4052
-            if (! $error && ! $notrigger)
4052
+            if (!$error && !$notrigger)
4053 4053
             {
4054 4054
 	            // Call trigger
4055
-	            $result=$this->call_trigger('LINEORDER_INSERT',$user);
4055
+	            $result = $this->call_trigger('LINEORDER_INSERT', $user);
4056 4056
 	            if ($result < 0) $error++;
4057 4057
 	            // End call triggers
4058 4058
             }
@@ -4062,17 +4062,17 @@  discard block
 block discarded – undo
4062 4062
 		        return 1;
4063 4063
 	        }
4064 4064
 
4065
-	        foreach($this->errors as $errmsg)
4065
+	        foreach ($this->errors as $errmsg)
4066 4066
 	        {
4067 4067
 		        dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4068
-		        $this->error.=($this->error?', '.$errmsg:$errmsg);
4068
+		        $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4069 4069
 	        }
4070 4070
 	        $this->db->rollback();
4071
-	        return -1*$error;
4071
+	        return -1 * $error;
4072 4072
         }
4073 4073
         else
4074 4074
         {
4075
-            $this->error=$this->db->error();
4075
+            $this->error = $this->db->error();
4076 4076
             $this->db->rollback();
4077 4077
             return -2;
4078 4078
         }
@@ -4085,32 +4085,32 @@  discard block
 block discarded – undo
4085 4085
 	 *	@param      int		$notrigger		1 = disable triggers
4086 4086
      *	@return		int		<0 si ko, >0 si ok
4087 4087
      */
4088
-	function update($user=null, $notrigger=0)
4088
+	function update($user = null, $notrigger = 0)
4089 4089
 	{
4090
-		global $conf,$langs;
4090
+		global $conf, $langs;
4091 4091
 
4092
-		$error=0;
4092
+		$error = 0;
4093 4093
 
4094 4094
 		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4095 4095
 
4096 4096
 		// Clean parameters
4097
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4098
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4099
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4100
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4101
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4102
-		if (empty($this->qty)) $this->qty=0;
4103
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4104
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4105
-		if (empty($this->marque_tx)) $this->marque_tx=0;
4106
-		if (empty($this->marge_tx)) $this->marge_tx=0;
4107
-		if (empty($this->remise)) $this->remise=0;
4108
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4109
-		if (empty($this->info_bits)) $this->info_bits=0;
4110
-        if (empty($this->special_code)) $this->special_code=0;
4111
-		if (empty($this->product_type)) $this->product_type=0;
4112
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4113
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4097
+		if (empty($this->tva_tx)) $this->tva_tx = 0;
4098
+		if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
4099
+		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
4100
+		if (empty($this->localtax1_type)) $this->localtax1_type = 0;
4101
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
4102
+		if (empty($this->qty)) $this->qty = 0;
4103
+		if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4104
+		if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4105
+		if (empty($this->marque_tx)) $this->marque_tx = 0;
4106
+		if (empty($this->marge_tx)) $this->marge_tx = 0;
4107
+		if (empty($this->remise)) $this->remise = 0;
4108
+		if (empty($this->remise_percent)) $this->remise_percent = 0;
4109
+		if (empty($this->info_bits)) $this->info_bits = 0;
4110
+        if (empty($this->special_code)) $this->special_code = 0;
4111
+		if (empty($this->product_type)) $this->product_type = 0;
4112
+		if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
4113
+		if (empty($this->pa_ht)) $this->pa_ht = 0;
4114 4114
 
4115 4115
 		// if buy price not defined, define buyprice as configured in margin admin
4116 4116
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -4129,64 +4129,64 @@  discard block
 block discarded – undo
4129 4129
 
4130 4130
 		// Mise a jour ligne en base
4131 4131
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4132
-		$sql.= " description='".$this->db->escape($this->desc)."'";
4133
-		$sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4134
-		$sql.= " , vat_src_code=".(! empty($this->vat_src_code)?"'".$this->db->escape($this->vat_src_code)."'":"''");
4135
-		$sql.= " , tva_tx=".price2num($this->tva_tx);
4136
-		$sql.= " , localtax1_tx=".price2num($this->localtax1_tx);
4137
-		$sql.= " , localtax2_tx=".price2num($this->localtax2_tx);
4138
-		$sql.= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4139
-		$sql.= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4140
-		$sql.= " , qty=".price2num($this->qty);
4141
-		$sql.= " , subprice=".price2num($this->subprice)."";
4142
-		$sql.= " , remise_percent=".price2num($this->remise_percent)."";
4143
-		$sql.= " , price=".price2num($this->price)."";					// TODO A virer
4144
-		$sql.= " , remise=".price2num($this->remise)."";				// TODO A virer
4132
+		$sql .= " description='".$this->db->escape($this->desc)."'";
4133
+		$sql .= " , label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
4134
+		$sql .= " , vat_src_code=".(!empty($this->vat_src_code) ? "'".$this->db->escape($this->vat_src_code)."'" : "''");
4135
+		$sql .= " , tva_tx=".price2num($this->tva_tx);
4136
+		$sql .= " , localtax1_tx=".price2num($this->localtax1_tx);
4137
+		$sql .= " , localtax2_tx=".price2num($this->localtax2_tx);
4138
+		$sql .= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4139
+		$sql .= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4140
+		$sql .= " , qty=".price2num($this->qty);
4141
+		$sql .= " , subprice=".price2num($this->subprice)."";
4142
+		$sql .= " , remise_percent=".price2num($this->remise_percent)."";
4143
+		$sql .= " , price=".price2num($this->price).""; // TODO A virer
4144
+		$sql .= " , remise=".price2num($this->remise).""; // TODO A virer
4145 4145
 		if (empty($this->skip_update_total))
4146 4146
 		{
4147
-			$sql.= " , total_ht=".price2num($this->total_ht)."";
4148
-			$sql.= " , total_tva=".price2num($this->total_tva)."";
4149
-			$sql.= " , total_ttc=".price2num($this->total_ttc)."";
4150
-			$sql.= " , total_localtax1=".price2num($this->total_localtax1);
4151
-			$sql.= " , total_localtax2=".price2num($this->total_localtax2);
4147
+			$sql .= " , total_ht=".price2num($this->total_ht)."";
4148
+			$sql .= " , total_tva=".price2num($this->total_tva)."";
4149
+			$sql .= " , total_ttc=".price2num($this->total_ttc)."";
4150
+			$sql .= " , total_localtax1=".price2num($this->total_localtax1);
4151
+			$sql .= " , total_localtax2=".price2num($this->total_localtax2);
4152 4152
 		}
4153
-		$sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?$this->fk_fournprice:"null");
4154
-		$sql.= " , buy_price_ht='".price2num($this->pa_ht)."'";
4155
-		$sql.= " , info_bits=".$this->info_bits;
4156
-        $sql.= " , special_code=".$this->special_code;
4157
-		$sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4158
-		$sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4159
-		$sql.= " , product_type=".$this->product_type;
4160
-		$sql.= " , fk_parent_line=".(! empty($this->fk_parent_line)?$this->fk_parent_line:"null");
4161
-		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
4162
-		$sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4153
+		$sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null");
4154
+		$sql .= " , buy_price_ht='".price2num($this->pa_ht)."'";
4155
+		$sql .= " , info_bits=".$this->info_bits;
4156
+        $sql .= " , special_code=".$this->special_code;
4157
+		$sql .= " , date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
4158
+		$sql .= " , date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
4159
+		$sql .= " , product_type=".$this->product_type;
4160
+		$sql .= " , fk_parent_line=".(!empty($this->fk_parent_line) ? $this->fk_parent_line : "null");
4161
+		if (!empty($this->rang)) $sql .= ", rang=".$this->rang;
4162
+		$sql .= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4163 4163
 
4164 4164
 		// Multicurrency
4165
-		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4166
-        $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4167
-        $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4168
-        $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4165
+		$sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4166
+        $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4167
+        $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4168
+        $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4169 4169
 
4170
-		$sql.= " WHERE rowid = ".$this->rowid;
4170
+		$sql .= " WHERE rowid = ".$this->rowid;
4171 4171
 
4172 4172
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
4173
-		$resql=$this->db->query($sql);
4173
+		$resql = $this->db->query($sql);
4174 4174
 		if ($resql)
4175 4175
 		{
4176 4176
 			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4177 4177
 			{
4178
-				$this->id=$this->rowid;
4179
-				$result=$this->insertExtraFields();
4178
+				$this->id = $this->rowid;
4179
+				$result = $this->insertExtraFields();
4180 4180
 				if ($result < 0)
4181 4181
 				{
4182 4182
 					$error++;
4183 4183
 				}
4184 4184
 			}
4185 4185
 
4186
-			if (! $notrigger)
4186
+			if (!$notrigger)
4187 4187
 			{
4188 4188
 	            // Call trigger
4189
-	            $result=$this->call_trigger('LINEORDER_UPDATE',$user);
4189
+	            $result = $this->call_trigger('LINEORDER_UPDATE', $user);
4190 4190
 	            if ($result < 0) $error++;
4191 4191
 	            // End call triggers
4192 4192
 			}
@@ -4196,17 +4196,17 @@  discard block
 block discarded – undo
4196 4196
 				return 1;
4197 4197
 			}
4198 4198
 
4199
-			foreach($this->errors as $errmsg)
4199
+			foreach ($this->errors as $errmsg)
4200 4200
 			{
4201 4201
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
4202
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
4202
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4203 4203
 			}
4204 4204
 			$this->db->rollback();
4205
-			return -1*$error;
4205
+			return -1 * $error;
4206 4206
 		}
4207 4207
 		else
4208 4208
 		{
4209
-			$this->error=$this->db->error();
4209
+			$this->error = $this->db->error();
4210 4210
 			$this->db->rollback();
4211 4211
 			return -2;
4212 4212
 		}
@@ -4222,21 +4222,21 @@  discard block
 block discarded – undo
4222 4222
         $this->db->begin();
4223 4223
 
4224 4224
         // Clean parameters
4225
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
4226
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
4225
+        if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4226
+        if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4227 4227
 
4228 4228
         // Mise a jour ligne en base
4229 4229
         $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4230
-        $sql.= " total_ht='".price2num($this->total_ht)."'";
4231
-        $sql.= ",total_tva='".price2num($this->total_tva)."'";
4232
-        $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
4233
-        $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
4234
-        $sql.= ",total_ttc='".price2num($this->total_ttc)."'";
4235
-        $sql.= " WHERE rowid = ".$this->rowid;
4230
+        $sql .= " total_ht='".price2num($this->total_ht)."'";
4231
+        $sql .= ",total_tva='".price2num($this->total_tva)."'";
4232
+        $sql .= ",total_localtax1='".price2num($this->total_localtax1)."'";
4233
+        $sql .= ",total_localtax2='".price2num($this->total_localtax2)."'";
4234
+        $sql .= ",total_ttc='".price2num($this->total_ttc)."'";
4235
+        $sql .= " WHERE rowid = ".$this->rowid;
4236 4236
 
4237 4237
         dol_syslog("OrderLine::update_total", LOG_DEBUG);
4238 4238
 
4239
-        $resql=$this->db->query($sql);
4239
+        $resql = $this->db->query($sql);
4240 4240
         if ($resql)
4241 4241
         {
4242 4242
             $this->db->commit();
@@ -4244,7 +4244,7 @@  discard block
 block discarded – undo
4244 4244
         }
4245 4245
         else
4246 4246
         {
4247
-            $this->error=$this->db->error();
4247
+            $this->error = $this->db->error();
4248 4248
             $this->db->rollback();
4249 4249
             return -2;
4250 4250
         }
Please login to merge, or discard this patch.
Braces   +649 added lines, -345 removed lines patch added patch discarded remove patch
@@ -238,15 +238,13 @@  discard block
 block discarded – undo
238 238
             if ($numref != "")
239 239
             {
240 240
             	return $numref;
241
-            }
242
-            else
241
+            } else
243 242
 			{
244 243
 				$this->error=$obj->error;
245 244
             	//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
246 245
             	return "";
247 246
             }
248
-        }
249
-        else
247
+        } else
250 248
         {
251 249
             print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
252 250
             return "";
@@ -296,11 +294,12 @@  discard block
 block discarded – undo
296 294
         $result=$soc->set_as_client();
297 295
 
298 296
         // Define new ref
299
-        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
297
+        if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) {
298
+        	// empty should not happened, but when it occurs, the test save life
300 299
         {
301 300
             $num = $this->getNextNumRef($soc);
302 301
         }
303
-        else
302
+        } else
304 303
 		{
305 304
             $num = $this->ref;
306 305
         }
@@ -347,7 +346,9 @@  discard block
 block discarded – undo
347 346
                         	$this->error=$mouvP->error;
348 347
                         }
349 348
                     }
350
-                    if ($error) break;
349
+                    if ($error) {
350
+                    	break;
351
+                    }
351 352
                 }
352 353
             }
353 354
         }
@@ -356,7 +357,9 @@  discard block
 block discarded – undo
356 357
         {
357 358
             // Call trigger
358 359
             $result=$this->call_trigger('ORDER_VALIDATE',$user);
359
-            if ($result < 0) $error++;
360
+            if ($result < 0) {
361
+            	$error++;
362
+            }
360 363
             // End call triggers
361 364
         }
362 365
 
@@ -406,8 +409,7 @@  discard block
 block discarded – undo
406 409
         {
407 410
             $this->db->commit();
408 411
             return 1;
409
-        }
410
-        else
412
+        } else
411 413
 		{
412 414
             $this->db->rollback();
413 415
             return -1;
@@ -474,19 +476,20 @@  discard block
 block discarded – undo
474 476
             if (!$error) {
475 477
             	// Call trigger
476 478
             	$result=$this->call_trigger('ORDER_UNVALIDATE',$user);
477
-            	if ($result < 0) $error++;
479
+            	if ($result < 0) {
480
+            		$error++;
481
+            	}
478 482
             }
479 483
 
480 484
             if (!$error) {
481 485
            		$this->statut=self::STATUS_DRAFT;
482 486
             	$this->db->commit();
483 487
             	return 1;
484
-            }else {
488
+            } else {
485 489
             	$this->db->rollback();
486 490
             	return -1;
487 491
             }
488
-        }
489
-        else
492
+        } else
490 493
         {
491 494
             $this->error=$this->db->error();
492 495
             $this->db->rollback();
@@ -524,10 +527,11 @@  discard block
 block discarded – undo
524 527
         {
525 528
             // Call trigger
526 529
             $result=$this->call_trigger('ORDER_REOPEN',$user);
527
-            if ($result < 0) $error++;
530
+            if ($result < 0) {
531
+            	$error++;
532
+            }
528 533
             // End call triggers
529
-        }
530
-        else
534
+        } else
531 535
         {
532 536
             $error++;
533 537
             $this->error=$this->db->lasterror();
@@ -542,8 +546,7 @@  discard block
 block discarded – undo
542 546
 
543 547
             $this->db->commit();
544 548
             return 1;
545
-        }
546
-        else
549
+        } else
547 550
         {
548 551
 	        foreach($this->errors as $errmsg)
549 552
 	        {
@@ -584,7 +587,9 @@  discard block
 block discarded – undo
584 587
             {
585 588
 	            // Call trigger
586 589
 	            $result=$this->call_trigger('ORDER_CLOSE',$user);
587
-	            if ($result < 0) $error++;
590
+	            if ($result < 0) {
591
+	            	$error++;
592
+	            }
588 593
 	            // End call triggers
589 594
 
590 595
                 if (! $error)
@@ -593,14 +598,12 @@  discard block
 block discarded – undo
593 598
 
594 599
                     $this->db->commit();
595 600
                     return 1;
596
-                }
597
-                else
601
+                } else
598 602
                 {
599 603
                     $this->db->rollback();
600 604
                     return -1;
601 605
                 }
602
-            }
603
-            else
606
+            } else
604 607
             {
605 608
                 $this->error=$this->db->lasterror();
606 609
 
@@ -661,7 +664,9 @@  discard block
 block discarded – undo
661 664
 			{
662 665
 	            // Call trigger
663 666
 	            $result=$this->call_trigger('ORDER_CANCEL',$user);
664
-	            if ($result < 0) $error++;
667
+	            if ($result < 0) {
668
+	            	$error++;
669
+	            }
665 670
 	            // End call triggers
666 671
 			}
667 672
 
@@ -670,8 +675,7 @@  discard block
 block discarded – undo
670 675
 				$this->statut=self::STATUS_CANCELED;
671 676
 				$this->db->commit();
672 677
 				return 1;
673
-			}
674
-			else
678
+			} else
675 679
 			{
676 680
 				foreach($this->errors as $errmsg)
677 681
 				{
@@ -681,8 +685,7 @@  discard block
 block discarded – undo
681 685
 				$this->db->rollback();
682 686
 				return -1*$error;
683 687
 			}
684
-		}
685
-		else
688
+		} else
686 689
 		{
687 690
 			$this->error=$this->db->error();
688 691
 			$this->db->rollback();
@@ -710,8 +713,11 @@  discard block
 block discarded – undo
710 713
         $date = ($this->date_commande ? $this->date_commande : $this->date);
711 714
 
712 715
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
713
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
714
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
716
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
717
+			list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
718
+		} else {
719
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
720
+		}
715 721
 		if (empty($this->fk_multicurrency))
716 722
 		{
717 723
 			$this->multicurrency_code = $conf->currency;
@@ -722,9 +728,12 @@  discard block
 block discarded – undo
722 728
         dol_syslog(get_class($this)."::create user=".$user->id);
723 729
 
724 730
         // Check parameters
725
-    	if (! empty($this->ref))	// We check that ref is not already used
731
+    	if (! empty($this->ref)) {
732
+    		// We check that ref is not already used
726 733
     	{
727
-    		$result=self::isExistingObject($this->element, 0, $this->ref);	// Check ref is not yet used
734
+    		$result=self::isExistingObject($this->element, 0, $this->ref);
735
+    	}
736
+    	// Check ref is not yet used
728 737
     		if ($result > 0)
729 738
     		{
730 739
     			$this->error='ErrorRefAlreadyExists';
@@ -814,7 +823,9 @@  discard block
 block discarded – undo
814 823
 
815 824
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
816 825
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
817
-                	if (! is_object($line)) $line = (object) $line;
826
+                	if (! is_object($line)) {
827
+                		$line = (object) $line;
828
+                	}
818 829
 
819 830
                     // Reset fk_parent_line for no child products and special product
820 831
                     if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
@@ -866,7 +877,9 @@  discard block
 block discarded – undo
866 877
 
867 878
                 // update ref
868 879
                 $initialref='(PROV'.$this->id.')';
869
-                if (! empty($this->ref)) $initialref=$this->ref;
880
+                if (! empty($this->ref)) {
881
+                	$initialref=$this->ref;
882
+                }
870 883
 
871 884
                 $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
872 885
                 if ($this->db->query($sql))
@@ -880,19 +893,20 @@  discard block
 block discarded – undo
880 893
                         {
881 894
                         	foreach($this->linked_objects as $origin => $tmp_origin_id)
882 895
                         	{
883
-                        	    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
896
+                        	    if (is_array($tmp_origin_id)) {
897
+                        	    	// New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
884 898
                         	    {
885 899
                         	        foreach($tmp_origin_id as $origin_id)
886 900
                         	        {
887 901
                         	            $ret = $this->add_object_linked($origin, $origin_id);
902
+                        	    }
888 903
                         	            if (! $ret)
889 904
                         	            {
890 905
                         	                dol_print_error($this->db);
891 906
                         	                $error++;
892 907
                         	            }
893 908
                         	        }
894
-                        	    }
895
-                        	    else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
909
+                        	    } else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
896 910
                         	    {
897 911
                         	        $origin_id = $tmp_origin_id;
898 912
                         	        $ret = $this->add_object_linked($origin, $origin_id);
@@ -905,13 +919,17 @@  discard block
 block discarded – undo
905 919
                         	}
906 920
                         }
907 921
 
908
-            			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
922
+            			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) {
923
+            				// Get contact from origin object
909 924
             			{
910 925
             				$originforcontact = $this->origin;
926
+            			}
911 927
             				$originidforcontact = $this->origin_id;
912
-                		    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
928
+                		    if ($originforcontact == 'shipping') {
929
+                		    	// shipment and order share the same contacts. If creating from shipment we take data of order
913 930
                 		    {
914 931
                 		        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
932
+                		    }
915 933
                 		        $exp = new Expedition($db);
916 934
                 		        $exp->fetch($this->origin_id);
917 935
                 		        $exp->fetchObjectLinked();
@@ -920,8 +938,11 @@  discard block
 block discarded – undo
920 938
                 		            foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
921 939
                 		            {
922 940
                 		                $originforcontact = 'commande';
923
-							            if (is_object($value)) $originidforcontact = $value->id;
924
-							            else $originidforcontact = $value;
941
+							            if (is_object($value)) {
942
+							            	$originidforcontact = $value->id;
943
+							            } else {
944
+							            	$originidforcontact = $value;
945
+							            }
925 946
                 		                break; // We take first one
926 947
                 		            }
927 948
                 		        }
@@ -938,22 +959,27 @@  discard block
 block discarded – undo
938 959
         					        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
939 960
                 		            $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
940 961
                 		        }
962
+                		    } else {
963
+                		    	dol_print_error($resqlcontact);
941 964
                 		    }
942
-                		    else dol_print_error($resqlcontact);
943 965
                 		}
944 966
                     }
945 967
 
946 968
                     if (! $error)
947 969
                     {
948 970
                    		$result=$this->insertExtraFields();
949
-                   		if ($result < 0) $error++;
971
+                   		if ($result < 0) {
972
+                   			$error++;
973
+                   		}
950 974
                     }
951 975
 
952 976
                     if (! $error && ! $notrigger)
953 977
                     {
954 978
 			            // Call trigger
955 979
 			            $result=$this->call_trigger('ORDER_CREATE',$user);
956
-			            if ($result < 0) $error++;
980
+			            if ($result < 0) {
981
+			            	$error++;
982
+			            }
957 983
 			            // End call triggers
958 984
                     }
959 985
 
@@ -961,22 +987,19 @@  discard block
 block discarded – undo
961 987
 	                {
962 988
 		                $this->db->commit();
963 989
 		                return $this->id;
964
-	                }
965
-	                else
990
+	                } else
966 991
 					{
967 992
 	                	$this->db->rollback();
968 993
 	                	return -1*$error;
969 994
 					}
970
-                }
971
-                else
995
+                } else
972 996
 				{
973 997
 					$this->error=$this->db->lasterror();
974 998
                     $this->db->rollback();
975 999
                     return -1;
976 1000
                 }
977 1001
             }
978
-        }
979
-        else
1002
+        } else
980 1003
 		{
981 1004
             dol_print_error($this->db);
982 1005
             $this->db->rollback();
@@ -1002,8 +1025,9 @@  discard block
 block discarded – undo
1002 1025
         $this->db->begin();
1003 1026
 
1004 1027
 		// get lines so they will be clone
1005
-		foreach($this->lines as $line)
1006
-			$line->fetch_optionals($line->rowid);
1028
+		foreach($this->lines as $line) {
1029
+					$line->fetch_optionals($line->rowid);
1030
+		}
1007 1031
 
1008 1032
         // Load source object
1009 1033
         $objFrom = clone $this;
@@ -1040,7 +1064,9 @@  discard block
 block discarded – undo
1040 1064
 
1041 1065
         // Create clone
1042 1066
         $result=$this->create($user);
1043
-        if ($result < 0) $error++;
1067
+        if ($result < 0) {
1068
+        	$error++;
1069
+        }
1044 1070
 
1045 1071
         if (! $error)
1046 1072
         {
@@ -1050,12 +1076,16 @@  discard block
 block discarded – undo
1050 1076
                 $parameters=array('objFrom'=>$objFrom);
1051 1077
                 $action='';
1052 1078
                 $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1053
-                if ($reshook < 0) $error++;
1079
+                if ($reshook < 0) {
1080
+                	$error++;
1081
+                }
1054 1082
             }
1055 1083
 
1056 1084
             // Call trigger
1057 1085
             $result=$this->call_trigger('ORDER_CLONE',$user);
1058
-            if ($result < 0) $error++;
1086
+            if ($result < 0) {
1087
+            	$error++;
1088
+            }
1059 1089
             // End call triggers
1060 1090
         }
1061 1091
 
@@ -1066,8 +1096,7 @@  discard block
 block discarded – undo
1066 1096
         {
1067 1097
             $this->db->commit();
1068 1098
             return $this->id;
1069
-        }
1070
-        else
1099
+        } else
1071 1100
         {
1072 1101
             $this->db->rollback();
1073 1102
             return -1;
@@ -1129,8 +1158,9 @@  discard block
 block discarded – undo
1129 1158
 
1130 1159
             // get extrafields from original line
1131 1160
 			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
1132
-			foreach($object->lines[$i]->array_options as $options_key => $value)
1133
-				$line->array_options[$options_key] = $value;
1161
+			foreach($object->lines[$i]->array_options as $options_key => $value) {
1162
+							$line->array_options[$options_key] = $value;
1163
+			}
1134 1164
 
1135 1165
 			$this->lines[$i] = $line;
1136 1166
         }
@@ -1182,7 +1212,9 @@  discard block
 block discarded – undo
1182 1212
             $parameters=array('objFrom'=>$object);
1183 1213
             $action='';
1184 1214
             $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1185
-            if ($reshook < 0) $error++;
1215
+            if ($reshook < 0) {
1216
+            	$error++;
1217
+            }
1186 1218
 
1187 1219
             if (! $error)
1188 1220
             {
@@ -1193,10 +1225,12 @@  discard block
 block discarded – undo
1193 1225
                     $this->valid($user);
1194 1226
                 }
1195 1227
                 return $ret;
1228
+            } else {
1229
+            	return -1;
1196 1230
             }
1197
-            else return -1;
1231
+        } else {
1232
+        	return -1;
1198 1233
         }
1199
-        else return -1;
1200 1234
     }
1201 1235
 
1202 1236
 
@@ -1247,15 +1281,33 @@  discard block
 block discarded – undo
1247 1281
         include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1248 1282
 
1249 1283
         // Clean parameters
1250
-        if (empty($remise_percent)) $remise_percent=0;
1251
-        if (empty($qty)) $qty=0;
1252
-        if (empty($info_bits)) $info_bits=0;
1253
-        if (empty($rang)) $rang=0;
1254
-        if (empty($txtva)) $txtva=0;
1255
-        if (empty($txlocaltax1)) $txlocaltax1=0;
1256
-        if (empty($txlocaltax2)) $txlocaltax2=0;
1257
-        if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
1258
-        if (empty($this->fk_multicurrency)) $this->fk_multicurrency=0;
1284
+        if (empty($remise_percent)) {
1285
+        	$remise_percent=0;
1286
+        }
1287
+        if (empty($qty)) {
1288
+        	$qty=0;
1289
+        }
1290
+        if (empty($info_bits)) {
1291
+        	$info_bits=0;
1292
+        }
1293
+        if (empty($rang)) {
1294
+        	$rang=0;
1295
+        }
1296
+        if (empty($txtva)) {
1297
+        	$txtva=0;
1298
+        }
1299
+        if (empty($txlocaltax1)) {
1300
+        	$txlocaltax1=0;
1301
+        }
1302
+        if (empty($txlocaltax2)) {
1303
+        	$txlocaltax2=0;
1304
+        }
1305
+        if (empty($fk_parent_line) || $fk_parent_line < 0) {
1306
+        	$fk_parent_line=0;
1307
+        }
1308
+        if (empty($this->fk_multicurrency)) {
1309
+        	$this->fk_multicurrency=0;
1310
+        }
1259 1311
 
1260 1312
         $remise_percent=price2num($remise_percent);
1261 1313
         $qty=price2num($qty);
@@ -1268,8 +1320,7 @@  discard block
 block discarded – undo
1268 1320
         if ($price_base_type=='HT')
1269 1321
         {
1270 1322
             $pu=$pu_ht;
1271
-        }
1272
-        else
1323
+        } else
1273 1324
         {
1274 1325
             $pu=$pu_ttc;
1275 1326
         }
@@ -1277,7 +1328,9 @@  discard block
 block discarded – undo
1277 1328
         $desc=trim($desc);
1278 1329
 
1279 1330
         // Check parameters
1280
-        if ($type < 0) return -1;
1331
+        if ($type < 0) {
1332
+        	return -1;
1333
+        }
1281 1334
 
1282 1335
         if ($this->statut == self::STATUS_DRAFT)
1283 1336
         {
@@ -1408,7 +1461,9 @@  discard block
 block discarded – undo
1408 1461
             if ($result > 0)
1409 1462
             {
1410 1463
                 // Reorder if child line
1411
-                if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1464
+                if (! empty($fk_parent_line)) {
1465
+                	$this->line_order(true,'DESC');
1466
+                }
1412 1467
 
1413 1468
                 // Mise a jour informations denormalisees au niveau de la commande meme
1414 1469
                 $result=$this->update_price(1,'auto',0,$mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
@@ -1416,22 +1471,19 @@  discard block
 block discarded – undo
1416 1471
                 {
1417 1472
                     $this->db->commit();
1418 1473
                     return $this->line->rowid;
1419
-                }
1420
-                else
1474
+                } else
1421 1475
                 {
1422 1476
                     $this->db->rollback();
1423 1477
                     return -1;
1424 1478
                 }
1425
-            }
1426
-            else
1479
+            } else
1427 1480
             {
1428 1481
                 $this->error=$this->line->error;
1429 1482
                 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1430 1483
                 $this->db->rollback();
1431 1484
                 return -2;
1432 1485
             }
1433
-        }
1434
-        else
1486
+        } else
1435 1487
         {
1436 1488
             dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1437 1489
             return -3;
@@ -1457,7 +1509,9 @@  discard block
 block discarded – undo
1457 1509
     {
1458 1510
         global $conf, $mysoc;
1459 1511
 
1460
-        if (! $qty) $qty = 1;
1512
+        if (! $qty) {
1513
+        	$qty = 1;
1514
+        }
1461 1515
 
1462 1516
         if ($idproduct > 0)
1463 1517
         {
@@ -1466,17 +1520,20 @@  discard block
 block discarded – undo
1466 1520
 
1467 1521
             $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
1468 1522
             $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
1469
-            if (empty($tva_tx)) $tva_npr=0;
1523
+            if (empty($tva_tx)) {
1524
+            	$tva_npr=0;
1525
+            }
1470 1526
             $vat_src_code = '';     // May be defined into tva_tx
1471 1527
 
1472 1528
             $localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
1473 1529
             $localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
1474 1530
 
1475 1531
             // multiprix
1476
-            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level)
1477
-            $price = $prod->multiprices[$this->thirdparty->price_level];
1478
-            else
1479
-            $price = $prod->price;
1532
+            if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
1533
+                        $price = $prod->multiprices[$this->thirdparty->price_level];
1534
+            } else {
1535
+                        $price = $prod->price;
1536
+            }
1480 1537
 
1481 1538
             $line=new OrderLine($this->db);
1482 1539
 
@@ -1540,7 +1597,9 @@  discard block
 block discarded – undo
1540 1597
     {
1541 1598
 
1542 1599
         // Check parameters
1543
-        if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1600
+        if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) {
1601
+        	return -1;
1602
+        }
1544 1603
 
1545 1604
         $sql = 'SELECT c.rowid, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
1546 1605
         $sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
@@ -1565,10 +1624,18 @@  discard block
 block discarded – undo
1565 1624
         $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1566 1625
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1567 1626
         $sql.= " WHERE c.entity IN (".getEntity('commande').")";
1568
-        if ($id)   	  $sql.= " AND c.rowid=".$id;
1569
-        if ($ref)     $sql.= " AND c.ref='".$this->db->escape($ref)."'";
1570
-        if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1571
-        if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1627
+        if ($id) {
1628
+        	$sql.= " AND c.rowid=".$id;
1629
+        }
1630
+        if ($ref) {
1631
+        	$sql.= " AND c.ref='".$this->db->escape($ref)."'";
1632
+        }
1633
+        if ($ref_ext) {
1634
+        	$sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1635
+        }
1636
+        if ($ref_int) {
1637
+        	$sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1638
+        }
1572 1639
 
1573 1640
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1574 1641
         $result = $this->db->query($sql);
@@ -1640,7 +1707,9 @@  discard block
 block discarded – undo
1640 1707
 
1641 1708
                 $this->lines				= array();
1642 1709
 
1643
-                if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
1710
+                if ($this->statut == self::STATUS_DRAFT) {
1711
+                	$this->brouillon = 1;
1712
+                }
1644 1713
 
1645 1714
                 // Retrieve all extrafields for invoice
1646 1715
                 // fetch optionals attributes and labels
@@ -1660,14 +1729,12 @@  discard block
 block discarded – undo
1660 1729
                     return -3;
1661 1730
                 }
1662 1731
                 return 1;
1663
-            }
1664
-            else
1732
+            } else
1665 1733
             {
1666 1734
                 $this->error='Order with id '.$id.' not found sql='.$sql;
1667 1735
                 return 0;
1668 1736
             }
1669
-        }
1670
-        else
1737
+        } else
1671 1738
         {
1672 1739
             $this->error=$this->db->error();
1673 1740
             return -1;
@@ -1695,9 +1762,11 @@  discard block
 block discarded – undo
1695 1762
 
1696 1763
         if ($result > 0)
1697 1764
         {
1698
-            if ($remise->fk_facture)	// Protection against multiple submission
1765
+            if ($remise->fk_facture) {
1766
+            	// Protection against multiple submission
1699 1767
             {
1700 1768
                 $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1769
+            }
1701 1770
                 $this->db->rollback();
1702 1771
                 return -5;
1703 1772
             }
@@ -1730,21 +1799,18 @@  discard block
 block discarded – undo
1730 1799
                 {
1731 1800
                     $this->db->commit();
1732 1801
                     return 1;
1733
-                }
1734
-                else
1802
+                } else
1735 1803
                 {
1736 1804
                     $this->db->rollback();
1737 1805
                     return -1;
1738 1806
                 }
1739
-            }
1740
-            else
1807
+            } else
1741 1808
             {
1742 1809
                 $this->error=$line->error;
1743 1810
                 $this->db->rollback();
1744 1811
                 return -2;
1745 1812
             }
1746
-        }
1747
-        else
1813
+        } else
1748 1814
         {
1749 1815
             $this->db->rollback();
1750 1816
             return -2;
@@ -1772,7 +1838,9 @@  discard block
 block discarded – undo
1772 1838
         $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1773 1839
         $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1774 1840
         $sql.= ' WHERE l.fk_commande = '.$this->id;
1775
-        if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1841
+        if ($only_product) {
1842
+        	$sql .= ' AND p.fk_product_type = 0';
1843
+        }
1776 1844
         $sql .= ' ORDER BY l.rang, l.rowid';
1777 1845
 
1778 1846
         dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
@@ -1857,8 +1925,7 @@  discard block
 block discarded – undo
1857 1925
             $this->db->free($result);
1858 1926
 
1859 1927
             return 1;
1860
-        }
1861
-        else
1928
+        } else
1862 1929
         {
1863 1930
             $this->error=$this->db->error();
1864 1931
             return -3;
@@ -1876,7 +1943,9 @@  discard block
 block discarded – undo
1876 1943
         $nb=0;
1877 1944
         foreach($this->lines as $line)
1878 1945
         {
1879
-            if ($line->product_type == 0) $nb++;
1946
+            if ($line->product_type == 0) {
1947
+            	$nb++;
1948
+            }
1880 1949
         }
1881 1950
         return $nb;
1882 1951
     }
@@ -1891,7 +1960,9 @@  discard block
 block discarded – undo
1891 1960
         $nb=0;
1892 1961
         foreach($this->lines as $line)
1893 1962
         {
1894
-            if ($line->product_type == 1) $nb++;
1963
+            if ($line->product_type == 1) {
1964
+            	$nb++;
1965
+            }
1895 1966
         }
1896 1967
         return $nb;
1897 1968
     }
@@ -1910,14 +1981,22 @@  discard block
 block discarded – undo
1910 1981
         $sql = 'SELECT cd.rowid, cd.fk_product,';
1911 1982
         $sql.= ' sum(ed.qty) as qty';
1912 1983
         $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
1913
-        if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
1984
+        if ($filtre_statut >= 0) {
1985
+        	$sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
1986
+        }
1914 1987
         $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
1915 1988
         $sql.= ' WHERE';
1916
-        if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND';
1989
+        if ($filtre_statut >= 0) {
1990
+        	$sql.= ' ed.fk_expedition = e.rowid AND';
1991
+        }
1917 1992
         $sql.= ' ed.fk_origin_line = cd.rowid';
1918 1993
         $sql.= ' AND cd.fk_commande =' .$this->id;
1919
-        if ($this->fk_product > 0) $sql.= ' AND cd.fk_product = '.$this->fk_product;
1920
-        if ($filtre_statut >= 0) $sql.=' AND e.fk_statut >= '.$filtre_statut;
1994
+        if ($this->fk_product > 0) {
1995
+        	$sql.= ' AND cd.fk_product = '.$this->fk_product;
1996
+        }
1997
+        if ($filtre_statut >= 0) {
1998
+        	$sql.=' AND e.fk_statut >= '.$filtre_statut;
1999
+        }
1921 2000
         $sql.= ' GROUP BY cd.rowid, cd.fk_product';
1922 2001
         //print $sql;
1923 2002
 
@@ -1935,8 +2014,7 @@  discard block
 block discarded – undo
1935 2014
             }
1936 2015
             $this->db->free();
1937 2016
             return $num;
1938
-        }
1939
-        else
2017
+        } else
1940 2018
         {
1941 2019
             $this->error=$this->db->lasterror();
1942 2020
             return -1;
@@ -1965,8 +2043,9 @@  discard block
 block discarded – undo
1965 2043
         {
1966 2044
             $row = $this->db->fetch_row($resql);
1967 2045
             return $row[0];
2046
+        } else {
2047
+        	dol_print_error($this->db);
1968 2048
         }
1969
-        else dol_print_error($this->db);
1970 2049
     }
1971 2050
 
1972 2051
     /**
@@ -2051,35 +2130,30 @@  discard block
 block discarded – undo
2051 2130
                         {
2052 2131
                             $this->db->commit();
2053 2132
                             return 1;
2054
-                        }
2055
-                        else
2133
+                        } else
2056 2134
                         {
2057 2135
                             $this->db->rollback();
2058 2136
                             $this->error=$this->db->lasterror();
2059 2137
                             return -1;
2060 2138
                         }
2061
-                    }
2062
-                    else
2139
+                    } else
2063 2140
                     {
2064 2141
                         $this->db->rollback();
2065 2142
                         $this->error=$line->error;
2066 2143
                         return -1;
2067 2144
                     }
2068
-                }
2069
-                else
2145
+                } else
2070 2146
                 {
2071 2147
                     $this->db->rollback();
2072 2148
                     return 0;
2073 2149
                 }
2074
-            }
2075
-            else
2150
+            } else
2076 2151
             {
2077 2152
                 $this->db->rollback();
2078 2153
                 $this->error=$this->db->lasterror();
2079 2154
                 return -1;
2080 2155
             }
2081
-        }
2082
-        else
2156
+        } else
2083 2157
         {
2084 2158
             return -1;
2085 2159
         }
@@ -2128,7 +2202,9 @@  discard block
 block discarded – undo
2128 2202
             {
2129 2203
             	// Call trigger
2130 2204
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2131
-            	if ($result < 0) $error++;
2205
+            	if ($result < 0) {
2206
+            		$error++;
2207
+            	}
2132 2208
             	// End call triggers
2133 2209
             }
2134 2210
 
@@ -2136,8 +2212,7 @@  discard block
 block discarded – undo
2136 2212
             {
2137 2213
             	$this->db->commit();
2138 2214
             	return 1;
2139
-            }
2140
-            else
2215
+            } else
2141 2216
             {
2142 2217
             	foreach($this->errors as $errmsg)
2143 2218
             	{
@@ -2194,7 +2269,9 @@  discard block
 block discarded – undo
2194 2269
             {
2195 2270
             	// Call trigger
2196 2271
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2197
-            	if ($result < 0) $error++;
2272
+            	if ($result < 0) {
2273
+            		$error++;
2274
+            	}
2198 2275
             	// End call triggers
2199 2276
             }
2200 2277
 
@@ -2202,8 +2279,7 @@  discard block
 block discarded – undo
2202 2279
             {
2203 2280
             	$this->db->commit();
2204 2281
             	return 1;
2205
-            }
2206
-            else
2282
+            } else
2207 2283
             {
2208 2284
             	foreach($this->errors as $errmsg)
2209 2285
             	{
@@ -2255,7 +2331,9 @@  discard block
 block discarded – undo
2255 2331
             {
2256 2332
             	// Call trigger
2257 2333
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2258
-            	if ($result < 0) $error++;
2334
+            	if ($result < 0) {
2335
+            		$error++;
2336
+            	}
2259 2337
             	// End call triggers
2260 2338
             }
2261 2339
 
@@ -2263,8 +2341,7 @@  discard block
 block discarded – undo
2263 2341
             {
2264 2342
             	$this->db->commit();
2265 2343
             	return 1;
2266
-            }
2267
-            else
2344
+            } else
2268 2345
             {
2269 2346
             	foreach($this->errors as $errmsg)
2270 2347
             	{
@@ -2274,8 +2351,7 @@  discard block
 block discarded – undo
2274 2351
             	$this->db->rollback();
2275 2352
             	return -1*$error;
2276 2353
             }
2277
-        }
2278
-        else
2354
+        } else
2279 2355
         {
2280 2356
             return -2;
2281 2357
         }
@@ -2319,7 +2395,9 @@  discard block
 block discarded – undo
2319 2395
             {
2320 2396
             	// Call trigger
2321 2397
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2322
-            	if ($result < 0) $error++;
2398
+            	if ($result < 0) {
2399
+            		$error++;
2400
+            	}
2323 2401
             	// End call triggers
2324 2402
             }
2325 2403
 
@@ -2327,8 +2405,7 @@  discard block
 block discarded – undo
2327 2405
             {
2328 2406
             	$this->db->commit();
2329 2407
             	return 1;
2330
-            }
2331
-            else
2408
+            } else
2332 2409
             {
2333 2410
             	foreach($this->errors as $errmsg)
2334 2411
             	{
@@ -2338,8 +2415,7 @@  discard block
 block discarded – undo
2338 2415
             	$this->db->rollback();
2339 2416
             	return -1*$error;
2340 2417
             }
2341
-        }
2342
-        else
2418
+        } else
2343 2419
         {
2344 2420
             return -2;
2345 2421
         }
@@ -2366,18 +2442,30 @@  discard block
 block discarded – undo
2366 2442
 
2367 2443
         $sql = "SELECT s.rowid, s.nom as name, s.client,";
2368 2444
         $sql.= " c.rowid as cid, c.ref";
2369
-        if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2445
+        if (! $user->rights->societe->client->voir && ! $socid) {
2446
+        	$sql .= ", sc.fk_soc, sc.fk_user";
2447
+        }
2370 2448
         $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2371
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2449
+		if (! $user->rights->societe->client->voir && ! $socid) {
2450
+			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2451
+		}
2372 2452
         $sql.= " WHERE c.entity IN (".getEntity('commande').")";
2373 2453
         $sql.= " AND c.fk_soc = s.rowid";
2374
-        if (! $user->rights->societe->client->voir && ! $socid) //restriction
2454
+        if (! $user->rights->societe->client->voir && ! $socid) {
2455
+        	//restriction
2375 2456
         {
2376 2457
         	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2377 2458
         }
2378
-        if ($socid) $sql.= " AND s.rowid = ".$socid;
2379
-        if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2380
-        if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id;
2459
+        }
2460
+        if ($socid) {
2461
+        	$sql.= " AND s.rowid = ".$socid;
2462
+        }
2463
+        if ($draft) {
2464
+        	$sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2465
+        }
2466
+        if (is_object($excluser)) {
2467
+        	$sql.= " AND c.fk_user_author <> ".$excluser->id;
2468
+        }
2381 2469
         $sql.= $this->db->order($sortfield,$sortorder);
2382 2470
         $sql.= $this->db->plimit($limit,$offset);
2383 2471
 
@@ -2395,12 +2483,10 @@  discard block
 block discarded – undo
2395 2483
                     if ($shortlist == 1)
2396 2484
                     {
2397 2485
                     	$ga[$obj->cid] = $obj->ref;
2398
-                    }
2399
-                    else if ($shortlist == 2)
2486
+                    } else if ($shortlist == 2)
2400 2487
                     {
2401 2488
                     	$ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2402
-                    }
2403
-                    else
2489
+                    } else
2404 2490
 					{
2405 2491
                     	$ga[$i]['id']	= $obj->cid;
2406 2492
                     	$ga[$i]['ref'] 	= $obj->ref;
@@ -2410,8 +2496,7 @@  discard block
 block discarded – undo
2410 2496
                 }
2411 2497
             }
2412 2498
             return $ga;
2413
-        }
2414
-        else
2499
+        } else
2415 2500
         {
2416 2501
             dol_print_error($this->db);
2417 2502
             return -1;
@@ -2458,7 +2543,9 @@  discard block
 block discarded – undo
2458 2543
             {
2459 2544
             	// Call trigger
2460 2545
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2461
-            	if ($result < 0) $error++;
2546
+            	if ($result < 0) {
2547
+            		$error++;
2548
+            	}
2462 2549
             	// End call triggers
2463 2550
             }
2464 2551
 
@@ -2466,8 +2553,7 @@  discard block
 block discarded – undo
2466 2553
             {
2467 2554
             	$this->db->commit();
2468 2555
             	return 1;
2469
-            }
2470
-            else
2556
+            } else
2471 2557
             {
2472 2558
             	foreach($this->errors as $errmsg)
2473 2559
             	{
@@ -2477,8 +2563,7 @@  discard block
 block discarded – undo
2477 2563
             	$this->db->rollback();
2478 2564
             	return -1*$error;
2479 2565
             }
2480
-        }
2481
-        else
2566
+        } else
2482 2567
         {
2483 2568
         	$error_str='Command status do not meet requirement '.$this->statut;
2484 2569
             dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -2528,7 +2613,9 @@  discard block
 block discarded – undo
2528 2613
             {
2529 2614
             	// Call trigger
2530 2615
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2531
-            	if ($result < 0) $error++;
2616
+            	if ($result < 0) {
2617
+            		$error++;
2618
+            	}
2532 2619
             	// End call triggers
2533 2620
             }
2534 2621
 
@@ -2536,8 +2623,7 @@  discard block
 block discarded – undo
2536 2623
             {
2537 2624
             	$this->db->commit();
2538 2625
             	return 1;
2539
-            }
2540
-            else
2626
+            } else
2541 2627
             {
2542 2628
             	foreach($this->errors as $errmsg)
2543 2629
             	{
@@ -2547,8 +2633,7 @@  discard block
 block discarded – undo
2547 2633
             	$this->db->rollback();
2548 2634
             	return -1*$error;
2549 2635
             }
2550
-        }
2551
-        else
2636
+        } else
2552 2637
         {
2553 2638
         	$error_str='order status do not meet requirement '.$this->statut;
2554 2639
         	dol_syslog(__METHOD__.$error_str, LOG_ERR);
@@ -2596,15 +2681,16 @@  discard block
 block discarded – undo
2596 2681
             {
2597 2682
             	// Call trigger
2598 2683
             	$result=$this->call_trigger('ORDER_MODIFY',$user);
2599
-            	if ($result < 0) $error++;
2684
+            	if ($result < 0) {
2685
+            		$error++;
2686
+            	}
2600 2687
             	// End call triggers
2601 2688
             }
2602 2689
             if (! $error)
2603 2690
             {
2604 2691
             	$this->db->commit();
2605 2692
             	return 1;
2606
-            }
2607
-            else
2693
+            } else
2608 2694
             {
2609 2695
             	foreach($this->errors as $errmsg)
2610 2696
             	{
@@ -2614,8 +2700,7 @@  discard block
 block discarded – undo
2614 2700
             	$this->db->rollback();
2615 2701
             	return -1*$error;
2616 2702
             }
2617
-        }
2618
-        else
2703
+        } else
2619 2704
         {
2620 2705
             return -1;
2621 2706
         }
@@ -2652,7 +2737,9 @@  discard block
 block discarded – undo
2652 2737
 			{
2653 2738
             	// Call trigger
2654 2739
             	$result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user);
2655
-            	if ($result < 0) $error++;
2740
+            	if ($result < 0) {
2741
+            		$error++;
2742
+            	}
2656 2743
             	// End call triggers
2657 2744
 			}
2658 2745
 
@@ -2660,8 +2747,7 @@  discard block
 block discarded – undo
2660 2747
 			{
2661 2748
 				$this->db->commit();
2662 2749
 				return 1;
2663
-			}
2664
-			else
2750
+			} else
2665 2751
 			{
2666 2752
 				foreach($this->errors as $errmsg)
2667 2753
 				{
@@ -2671,8 +2757,7 @@  discard block
 block discarded – undo
2671 2757
 				$this->db->rollback();
2672 2758
 				return -1*$error;
2673 2759
 			}
2674
-		}
2675
-		else
2760
+		} else
2676 2761
 		{
2677 2762
 			$this->error=$this->db->error();
2678 2763
             $this->db->rollback();
@@ -2722,7 +2807,9 @@  discard block
 block discarded – undo
2722 2807
 
2723 2808
 	        // Call trigger
2724 2809
 	        $result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED',$user);
2725
-	        if ($result < 0) $error++;
2810
+	        if ($result < 0) {
2811
+	        	$error++;
2812
+	        }
2726 2813
 	        // End call triggers
2727 2814
 
2728 2815
 	        if (! $error)
@@ -2732,8 +2819,7 @@  discard block
 block discarded – undo
2732 2819
 
2733 2820
 	            $this->db->commit();
2734 2821
 	            return 1;
2735
-	        }
2736
-	        else
2822
+	        } else
2737 2823
 	        {
2738 2824
 	            foreach($this->errors as $errmsg)
2739 2825
 	            {
@@ -2743,8 +2829,7 @@  discard block
 block discarded – undo
2743 2829
 	            $this->db->rollback();
2744 2830
 	            return -1*$error;
2745 2831
 	        }
2746
-	    }
2747
-	    else
2832
+	    } else
2748 2833
 	    {
2749 2834
 	        $this->error=$this->db->error();
2750 2835
 	        $this->db->rollback();
@@ -2793,14 +2878,30 @@  discard block
 block discarded – undo
2793 2878
             $this->db->begin();
2794 2879
 
2795 2880
             // Clean parameters
2796
-            if (empty($qty)) $qty=0;
2797
-            if (empty($info_bits)) $info_bits=0;
2798
-            if (empty($txtva)) $txtva=0;
2799
-            if (empty($txlocaltax1)) $txlocaltax1=0;
2800
-            if (empty($txlocaltax2)) $txlocaltax2=0;
2801
-            if (empty($remise)) $remise=0;
2802
-            if (empty($remise_percent)) $remise_percent=0;
2803
-            if (empty($special_code) || $special_code == 3) $special_code=0;
2881
+            if (empty($qty)) {
2882
+            	$qty=0;
2883
+            }
2884
+            if (empty($info_bits)) {
2885
+            	$info_bits=0;
2886
+            }
2887
+            if (empty($txtva)) {
2888
+            	$txtva=0;
2889
+            }
2890
+            if (empty($txlocaltax1)) {
2891
+            	$txlocaltax1=0;
2892
+            }
2893
+            if (empty($txlocaltax2)) {
2894
+            	$txlocaltax2=0;
2895
+            }
2896
+            if (empty($remise)) {
2897
+            	$remise=0;
2898
+            }
2899
+            if (empty($remise_percent)) {
2900
+            	$remise_percent=0;
2901
+            }
2902
+            if (empty($special_code) || $special_code == 3) {
2903
+            	$special_code=0;
2904
+            }
2804 2905
 
2805 2906
             $remise_percent=price2num($remise_percent);
2806 2907
             $qty=price2num($qty);
@@ -2847,8 +2948,7 @@  discard block
 block discarded – undo
2847 2948
 			if ($price_base_type == 'TTC')
2848 2949
 			{
2849 2950
 				$subprice = $pu_ttc;
2850
-			}
2851
-			else
2951
+			} else
2852 2952
 			{
2853 2953
 				$subprice = $pu_ht;
2854 2954
 			}
@@ -2940,23 +3040,23 @@  discard block
 block discarded – undo
2940 3040
             if ($result > 0)
2941 3041
             {
2942 3042
             	// Reorder if child line
2943
-            	if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
3043
+            	if (! empty($fk_parent_line)) {
3044
+            		$this->line_order(true,'DESC');
3045
+            	}
2944 3046
 
2945 3047
                 // Mise a jour info denormalisees
2946 3048
                 $this->update_price(1);
2947 3049
 
2948 3050
                 $this->db->commit();
2949 3051
                 return $result;
2950
-            }
2951
-            else
3052
+            } else
2952 3053
             {
2953 3054
 	            $this->error=$this->line->error;
2954 3055
 
2955 3056
 	            $this->db->rollback();
2956 3057
 	            return -1;
2957 3058
             }
2958
-        }
2959
-        else
3059
+        } else
2960 3060
         {
2961 3061
             $this->error=get_class($this)."::updateline Order status makes operation forbidden";
2962 3062
         	$this->errors=array('OrderStatusMakeOperationForbidden');
@@ -2976,12 +3076,24 @@  discard block
 block discarded – undo
2976 3076
 		$error=0;
2977 3077
 
2978 3078
 		// Clean parameters
2979
-		if (isset($this->ref)) $this->ref=trim($this->ref);
2980
-		if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
2981
-		if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2982
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
2983
-		if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
2984
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
3079
+		if (isset($this->ref)) {
3080
+			$this->ref=trim($this->ref);
3081
+		}
3082
+		if (isset($this->ref_client)) {
3083
+			$this->ref_client=trim($this->ref_client);
3084
+		}
3085
+		if (isset($this->note) || isset($this->note_private)) {
3086
+			$this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
3087
+		}
3088
+		if (isset($this->note_public)) {
3089
+			$this->note_public=trim($this->note_public);
3090
+		}
3091
+		if (isset($this->modelpdf)) {
3092
+			$this->modelpdf=trim($this->modelpdf);
3093
+		}
3094
+		if (isset($this->import_key)) {
3095
+			$this->import_key=trim($this->import_key);
3096
+		}
2985 3097
 
2986 3098
 		// Check parameters
2987 3099
 		// Put here code to add control on parameters values
@@ -3027,7 +3139,9 @@  discard block
 block discarded – undo
3027 3139
 			{
3028 3140
 	            // Call trigger
3029 3141
 	            $result=$this->call_trigger('ORDER_MODIFY',$user);
3030
-	            if ($result < 0) $error++;
3142
+	            if ($result < 0) {
3143
+	            	$error++;
3144
+	            }
3031 3145
 	            // End call triggers
3032 3146
 			}
3033 3147
 		}
@@ -3042,8 +3156,7 @@  discard block
 block discarded – undo
3042 3156
 			}
3043 3157
 			$this->db->rollback();
3044 3158
 			return -1*$error;
3045
-		}
3046
-		else
3159
+		} else
3047 3160
 		{
3048 3161
 			$this->db->commit();
3049 3162
 			return 1;
@@ -3070,22 +3183,24 @@  discard block
 block discarded – undo
3070 3183
     	$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3071 3184
     	if (empty($reshook))
3072 3185
     	{
3073
-    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3186
+    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
3187
+    			// For avoid conflicts if trigger used
3074 3188
     		{
3075 3189
     			$result=$this->insertExtraFields();
3190
+    		}
3076 3191
     			if ($result < 0)
3077 3192
     			{
3078 3193
     				$error++;
3079 3194
     			}
3080 3195
     		}
3196
+    	} else if ($reshook < 0) {
3197
+    		$error++;
3081 3198
     	}
3082
-    	else if ($reshook < 0) $error++;
3083 3199
 
3084 3200
     	if (!$error)
3085 3201
     	{
3086 3202
     		return 1;
3087
-    	}
3088
-    	else
3203
+    	} else
3089 3204
     	{
3090 3205
     		return -1;
3091 3206
     	}
@@ -3114,7 +3229,9 @@  discard block
 block discarded – undo
3114 3229
         {
3115 3230
             // Call trigger
3116 3231
             $result=$this->call_trigger('ORDER_DELETE',$user);
3117
-            if ($result < 0) $error++;
3232
+            if ($result < 0) {
3233
+            	$error++;
3234
+            }
3118 3235
             // End call triggers
3119 3236
         }
3120 3237
 
@@ -3139,16 +3256,22 @@  discard block
 block discarded – undo
3139 3256
 
3140 3257
         	// Delete linked object
3141 3258
         	$res = $this->deleteObjectLinked();
3142
-        	if ($res < 0) $error++;
3259
+        	if ($res < 0) {
3260
+        		$error++;
3261
+        	}
3143 3262
 
3144 3263
         	// Delete linked contacts
3145 3264
         	$res = $this->delete_linked_contact();
3146
-        	if ($res < 0) $error++;
3265
+        	if ($res < 0) {
3266
+        		$error++;
3267
+        	}
3147 3268
 
3148 3269
         	// Remove extrafields
3149
-        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3270
+        	if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
3271
+        		// For avoid conflicts if trigger used
3150 3272
         	{
3151 3273
         		$result=$this->deleteExtraFields();
3274
+        	}
3152 3275
         		if ($result < 0)
3153 3276
         		{
3154 3277
         			$error++;
@@ -3162,13 +3285,17 @@  discard block
 block discarded – undo
3162 3285
         	{
3163 3286
         		$dir = $conf->commande->dir_output . "/" . $comref ;
3164 3287
         		$file = $conf->commande->dir_output . "/" . $comref . "/" . $comref . ".pdf";
3165
-        		if (file_exists($file))	// We must delete all files before deleting directory
3288
+        		if (file_exists($file)) {
3289
+        			// We must delete all files before deleting directory
3166 3290
         		{
3167 3291
         			dol_delete_preview($this);
3292
+        		}
3168 3293
 
3169
-        			if (! dol_delete_file($file,0,0,0,$this)) // For triggers
3294
+        			if (! dol_delete_file($file,0,0,0,$this)) {
3295
+        				// For triggers
3170 3296
         			{
3171 3297
         				$this->db->rollback();
3298
+        			}
3172 3299
         				return 0;
3173 3300
         			}
3174 3301
         		}
@@ -3190,8 +3317,7 @@  discard block
 block discarded – undo
3190 3317
         {
3191 3318
         	$this->db->commit();
3192 3319
         	return 1;
3193
-        }
3194
-        else
3320
+        } else
3195 3321
         {
3196 3322
 	        foreach($this->errors as $errmsg)
3197 3323
 	        {
@@ -3226,7 +3352,9 @@  discard block
 block discarded – undo
3226 3352
         $sql.= $clause." c.entity IN (".getEntity('commande').")";
3227 3353
         //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3228 3354
         $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))";    // If status is 2 and facture=1, it must be selected
3229
-        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
3355
+        if ($user->societe_id) {
3356
+        	$sql.=" AND c.fk_soc = ".$user->societe_id;
3357
+        }
3230 3358
 
3231 3359
         $resql=$this->db->query($sql);
3232 3360
         if ($resql)
@@ -3253,8 +3381,7 @@  discard block
 block discarded – undo
3253 3381
             }
3254 3382
 
3255 3383
             return $response;
3256
-        }
3257
-        else
3384
+        } else
3258 3385
         {
3259 3386
             $this->error=$this->db->error();
3260 3387
             return -1;
@@ -3272,7 +3399,9 @@  discard block
 block discarded – undo
3272 3399
 
3273 3400
         $label=$langs->trans('OrderSource'.$this->source);
3274 3401
 
3275
-        if ($label == 'OrderSource') return '';
3402
+        if ($label == 'OrderSource') {
3403
+        	return '';
3404
+        }
3276 3405
         return $label;
3277 3406
     }
3278 3407
 
@@ -3284,7 +3413,10 @@  discard block
 block discarded – undo
3284 3413
      */
3285 3414
     function getLibStatut($mode)
3286 3415
     {
3287
-        if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility
3416
+        if ($this->facturee && empty($this->billed)) {
3417
+        	$this->billed=$this->facturee;
3418
+        }
3419
+        // For backward compatibility
3288 3420
         return $this->LibStatut($this->statut,$this->billed,$mode);
3289 3421
     }
3290 3422
 
@@ -3302,68 +3434,149 @@  discard block
 block discarded – undo
3302 3434
         global $langs, $conf;
3303 3435
 
3304 3436
         $billedtext = '';
3305
-        if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3437
+        if (empty($donotshowbilled)) {
3438
+        	$billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3439
+        }
3306 3440
 
3307 3441
         //print 'x'.$statut.'-'.$billed;
3308 3442
         if ($mode == 0)
3309 3443
         {
3310
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3311
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3312
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3313
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3314
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3315
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3316
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3317
-        }
3318
-        elseif ($mode == 1)
3444
+            if ($statut==self::STATUS_CANCELED) {
3445
+            	return $langs->trans('StatusOrderCanceled');
3446
+            }
3447
+            if ($statut==self::STATUS_DRAFT) {
3448
+            	return $langs->trans('StatusOrderDraft');
3449
+            }
3450
+            if ($statut==self::STATUS_VALIDATED) {
3451
+            	return $langs->trans('StatusOrderValidated').$billedtext;
3452
+            }
3453
+            if ($statut==self::STATUS_ACCEPTED) {
3454
+            	return $langs->trans('StatusOrderSentShort').$billedtext;
3455
+            }
3456
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3457
+            	return $langs->trans('StatusOrderToBill');
3458
+            }
3459
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3460
+            	return $langs->trans('StatusOrderProcessed').$billedtext;
3461
+            }
3462
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3463
+            	return $langs->trans('StatusOrderDelivered');
3464
+            }
3465
+        } elseif ($mode == 1)
3319 3466
         {
3320
-            if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3321
-            if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3322
-            if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3323
-            if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext;
3324
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3325
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3326
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3327
-        }
3328
-        elseif ($mode == 2)
3467
+            if ($statut==self::STATUS_CANCELED) {
3468
+            	return $langs->trans('StatusOrderCanceledShort');
3469
+            }
3470
+            if ($statut==self::STATUS_DRAFT) {
3471
+            	return $langs->trans('StatusOrderDraftShort');
3472
+            }
3473
+            if ($statut==self::STATUS_VALIDATED) {
3474
+            	return $langs->trans('StatusOrderValidatedShort').$billedtext;
3475
+            }
3476
+            if ($statut==self::STATUS_ACCEPTED) {
3477
+            	return $langs->trans('StatusOrderSentShort').$billedtext;
3478
+            }
3479
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3480
+            	return $langs->trans('StatusOrderToBillShort');
3481
+            }
3482
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3483
+            	return $langs->trans('StatusOrderProcessed').$billedtext;
3484
+            }
3485
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3486
+            	return $langs->trans('StatusOrderDelivered');
3487
+            }
3488
+        } elseif ($mode == 2)
3329 3489
         {
3330
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3331
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3332
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3333
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3334
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3335
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3336
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3337
-        }
3338
-        elseif ($mode == 3)
3490
+            if ($statut==self::STATUS_CANCELED) {
3491
+            	return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3492
+            }
3493
+            if ($statut==self::STATUS_DRAFT) {
3494
+            	return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3495
+            }
3496
+            if ($statut==self::STATUS_VALIDATED) {
3497
+            	return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3498
+            }
3499
+            if ($statut==self::STATUS_ACCEPTED) {
3500
+            	return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3501
+            }
3502
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3503
+            	return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3504
+            }
3505
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3506
+            	return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3507
+            }
3508
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3509
+            	return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3510
+            }
3511
+        } elseif ($mode == 3)
3339 3512
         {
3340
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3341
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3342
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3343
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3344
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3345
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3346
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3347
-        }
3348
-        elseif ($mode == 4)
3513
+            if ($statut==self::STATUS_CANCELED) {
3514
+            	return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3515
+            }
3516
+            if ($statut==self::STATUS_DRAFT) {
3517
+            	return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3518
+            }
3519
+            if ($statut==self::STATUS_VALIDATED) {
3520
+            	return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3521
+            }
3522
+            if ($statut==self::STATUS_ACCEPTED) {
3523
+            	return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3524
+            }
3525
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3526
+            	return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3527
+            }
3528
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3529
+            	return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3530
+            }
3531
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3532
+            	return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3533
+            }
3534
+        } elseif ($mode == 4)
3349 3535
         {
3350
-            if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3351
-            if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3352
-            if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3353
-            if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3354
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3355
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3356
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3357
-        }
3358
-        elseif ($mode == 5)
3536
+            if ($statut==self::STATUS_CANCELED) {
3537
+            	return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3538
+            }
3539
+            if ($statut==self::STATUS_DRAFT) {
3540
+            	return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3541
+            }
3542
+            if ($statut==self::STATUS_VALIDATED) {
3543
+            	return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3544
+            }
3545
+            if ($statut==self::STATUS_ACCEPTED) {
3546
+            	return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3547
+            }
3548
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3549
+            	return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3550
+            }
3551
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3552
+            	return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3553
+            }
3554
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3555
+            	return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3556
+            }
3557
+        } elseif ($mode == 5)
3359 3558
         {
3360
-            if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3361
-            if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3362
-            if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3363
-            if ($statut==self::STATUS_ACCEPTED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3364
-            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3365
-            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3366
-            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3559
+            if ($statut==self::STATUS_CANCELED) {
3560
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3561
+            }
3562
+            if ($statut==self::STATUS_DRAFT) {
3563
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3564
+            }
3565
+            if ($statut==self::STATUS_VALIDATED) {
3566
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3567
+            }
3568
+            if ($statut==self::STATUS_ACCEPTED) {
3569
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3570
+            }
3571
+            if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3572
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3573
+            }
3574
+            if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3575
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3576
+            }
3577
+            if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
3578
+            	return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3579
+            }
3367 3580
         }
3368 3581
     }
3369 3582
 
@@ -3383,22 +3596,34 @@  discard block
 block discarded – undo
3383 3596
     {
3384 3597
         global $conf, $langs, $user;
3385 3598
 
3386
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
3599
+        if (! empty($conf->dol_no_mouse_hover)) {
3600
+        	$notooltip=1;
3601
+        }
3602
+        // Force disable tooltips
3387 3603
 
3388 3604
         $result='';
3389 3605
 
3390
-        if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3391
-        else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3606
+        if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) {
3607
+        	$url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3608
+        } else {
3609
+        	$url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3610
+        }
3392 3611
 
3393 3612
         if ($option !== 'nolink')
3394 3613
         {
3395 3614
             // Add param to save lastsearch_values or not
3396 3615
             $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3397
-            if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3398
-            if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3616
+            if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
3617
+            	$add_save_lastsearch_values=1;
3618
+            }
3619
+            if ($add_save_lastsearch_values) {
3620
+            	$url.='&save_lastsearch_values=1';
3621
+            }
3399 3622
         }
3400 3623
 
3401
-        if ($short) return $url;
3624
+        if ($short) {
3625
+        	return $url;
3626
+        }
3402 3627
 
3403 3628
         $picto = 'order';
3404 3629
         $label = '';
@@ -3434,8 +3659,12 @@  discard block
 block discarded – undo
3434 3659
         $linkstart.=$linkclose.'>';
3435 3660
         $linkend='</a>';
3436 3661
 
3437
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3438
-        if ($withpicto && $withpicto != 2) $result.=' ';
3662
+        if ($withpicto) {
3663
+        	$result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
3664
+        }
3665
+        if ($withpicto && $withpicto != 2) {
3666
+        	$result.=' ';
3667
+        }
3439 3668
         $result.=$linkstart.$this->ref.$linkend;
3440 3669
         return $result;
3441 3670
     }
@@ -3491,8 +3720,7 @@  discard block
 block discarded – undo
3491 3720
 
3492 3721
             $this->db->free($result);
3493 3722
 
3494
-        }
3495
-        else
3723
+        } else
3496 3724
         {
3497 3725
             dol_print_error($this->db);
3498 3726
         }
@@ -3562,8 +3790,7 @@  discard block
 block discarded – undo
3562 3790
                 $line->total_ttc=60;
3563 3791
                 $line->total_tva=10;
3564 3792
                 $line->remise_percent=50;
3565
-            }
3566
-            else
3793
+            } else
3567 3794
             {
3568 3795
                 $line->total_ht=100;
3569 3796
                 $line->total_ttc=120;
@@ -3620,8 +3847,7 @@  discard block
 block discarded – undo
3620 3847
             }
3621 3848
             $this->db->free($resql);
3622 3849
             return 1;
3623
-        }
3624
-        else
3850
+        } else
3625 3851
         {
3626 3852
             dol_print_error($this->db);
3627 3853
             $this->error=$this->db->error();
@@ -3716,8 +3942,11 @@  discard block
 block discarded – undo
3716 3942
     {
3717 3943
         global $conf, $langs;
3718 3944
 
3719
-        if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3720
-        else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3945
+        if (empty($this->date_livraison)) {
3946
+        	$text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3947
+        } else {
3948
+        	$text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3949
+        }
3721 3950
         $text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3722 3951
 
3723 3952
         return $text;
@@ -3864,8 +4093,7 @@  discard block
 block discarded – undo
3864 4093
             $this->db->free($result);
3865 4094
 
3866 4095
             return 1;
3867
-        }
3868
-        else
4096
+        } else
3869 4097
         {
3870 4098
             $this->error = $this->db->lasterror();
3871 4099
             return -1;
@@ -3894,9 +4122,11 @@  discard block
 block discarded – undo
3894 4122
         if ($resql)
3895 4123
         {
3896 4124
 			// Remove extrafields
3897
-			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
4125
+			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
4126
+				// For avoid conflicts if trigger used
3898 4127
 			{
3899 4128
 				$this->id=$this->rowid;
4129
+			}
3900 4130
 				$result=$this->deleteExtraFields();
3901 4131
 				if ($result < 0)
3902 4132
 				{
@@ -3909,7 +4139,9 @@  discard block
 block discarded – undo
3909 4139
 			{
3910 4140
 	            // Call trigger
3911 4141
 	            $result=$this->call_trigger('LINEORDER_DELETE',$user);
3912
-	            if ($result < 0) $error++;
4142
+	            if ($result < 0) {
4143
+	            	$error++;
4144
+	            }
3913 4145
 	            // End call triggers
3914 4146
 			}
3915 4147
 
@@ -3925,8 +4157,7 @@  discard block
 block discarded – undo
3925 4157
 	        }
3926 4158
 	        $this->db->rollback();
3927 4159
 	        return -1*$error;
3928
-        }
3929
-        else
4160
+        } else
3930 4161
         {
3931 4162
             $this->error=$this->db->lasterror();
3932 4163
             return -1;
@@ -3951,20 +4182,48 @@  discard block
 block discarded – undo
3951 4182
         dol_syslog(get_class($this)."::insert rang=".$this->rang);
3952 4183
 
3953 4184
         // Clean parameters
3954
-        if (empty($this->tva_tx)) $this->tva_tx=0;
3955
-        if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3956
-        if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3957
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
3958
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
3959
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
3960
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
3961
-        if (empty($this->rang)) $this->rang=0;
3962
-        if (empty($this->remise)) $this->remise=0;
3963
-        if (empty($this->remise_percent)) $this->remise_percent=0;
3964
-        if (empty($this->info_bits)) $this->info_bits=0;
3965
-        if (empty($this->special_code)) $this->special_code=0;
3966
-        if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3967
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4185
+        if (empty($this->tva_tx)) {
4186
+        	$this->tva_tx=0;
4187
+        }
4188
+        if (empty($this->localtax1_tx)) {
4189
+        	$this->localtax1_tx=0;
4190
+        }
4191
+        if (empty($this->localtax2_tx)) {
4192
+        	$this->localtax2_tx=0;
4193
+        }
4194
+		if (empty($this->localtax1_type)) {
4195
+			$this->localtax1_type=0;
4196
+		}
4197
+		if (empty($this->localtax2_type)) {
4198
+			$this->localtax2_type=0;
4199
+		}
4200
+        if (empty($this->total_localtax1)) {
4201
+        	$this->total_localtax1=0;
4202
+        }
4203
+        if (empty($this->total_localtax2)) {
4204
+        	$this->total_localtax2=0;
4205
+        }
4206
+        if (empty($this->rang)) {
4207
+        	$this->rang=0;
4208
+        }
4209
+        if (empty($this->remise)) {
4210
+        	$this->remise=0;
4211
+        }
4212
+        if (empty($this->remise_percent)) {
4213
+        	$this->remise_percent=0;
4214
+        }
4215
+        if (empty($this->info_bits)) {
4216
+        	$this->info_bits=0;
4217
+        }
4218
+        if (empty($this->special_code)) {
4219
+        	$this->special_code=0;
4220
+        }
4221
+        if (empty($this->fk_parent_line)) {
4222
+        	$this->fk_parent_line=0;
4223
+        }
4224
+		if (empty($this->pa_ht)) {
4225
+			$this->pa_ht=0;
4226
+		}
3968 4227
 
3969 4228
 		// if buy price not defined, define buyprice as configured in margin admin
3970 4229
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -3972,15 +4231,16 @@  discard block
 block discarded – undo
3972 4231
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
3973 4232
 			{
3974 4233
 				return $result;
3975
-			}
3976
-			else
4234
+			} else
3977 4235
 			{
3978 4236
 				$this->pa_ht = $result;
3979 4237
 			}
3980 4238
 		}
3981 4239
 
3982 4240
         // Check parameters
3983
-        if ($this->product_type < 0) return -1;
4241
+        if ($this->product_type < 0) {
4242
+        	return -1;
4243
+        }
3984 4244
 
3985 4245
         $this->db->begin();
3986 4246
 
@@ -4039,9 +4299,11 @@  discard block
 block discarded – undo
4039 4299
         {
4040 4300
             $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4041 4301
 
4042
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4302
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
4303
+				// For avoid conflicts if trigger used
4043 4304
 			{
4044 4305
 				$this->id=$this->rowid;
4306
+			}
4045 4307
 				$result=$this->insertExtraFields();
4046 4308
 				if ($result < 0)
4047 4309
 				{
@@ -4053,7 +4315,9 @@  discard block
 block discarded – undo
4053 4315
             {
4054 4316
 	            // Call trigger
4055 4317
 	            $result=$this->call_trigger('LINEORDER_INSERT',$user);
4056
-	            if ($result < 0) $error++;
4318
+	            if ($result < 0) {
4319
+	            	$error++;
4320
+	            }
4057 4321
 	            // End call triggers
4058 4322
             }
4059 4323
 
@@ -4069,8 +4333,7 @@  discard block
 block discarded – undo
4069 4333
 	        }
4070 4334
 	        $this->db->rollback();
4071 4335
 	        return -1*$error;
4072
-        }
4073
-        else
4336
+        } else
4074 4337
         {
4075 4338
             $this->error=$this->db->error();
4076 4339
             $this->db->rollback();
@@ -4094,23 +4357,57 @@  discard block
 block discarded – undo
4094 4357
 		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4095 4358
 
4096 4359
 		// Clean parameters
4097
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4098
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4099
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4100
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4101
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4102
-		if (empty($this->qty)) $this->qty=0;
4103
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4104
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4105
-		if (empty($this->marque_tx)) $this->marque_tx=0;
4106
-		if (empty($this->marge_tx)) $this->marge_tx=0;
4107
-		if (empty($this->remise)) $this->remise=0;
4108
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4109
-		if (empty($this->info_bits)) $this->info_bits=0;
4110
-        if (empty($this->special_code)) $this->special_code=0;
4111
-		if (empty($this->product_type)) $this->product_type=0;
4112
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4113
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4360
+		if (empty($this->tva_tx)) {
4361
+			$this->tva_tx=0;
4362
+		}
4363
+		if (empty($this->localtax1_tx)) {
4364
+			$this->localtax1_tx=0;
4365
+		}
4366
+		if (empty($this->localtax2_tx)) {
4367
+			$this->localtax2_tx=0;
4368
+		}
4369
+		if (empty($this->localtax1_type)) {
4370
+			$this->localtax1_type=0;
4371
+		}
4372
+		if (empty($this->localtax2_type)) {
4373
+			$this->localtax2_type=0;
4374
+		}
4375
+		if (empty($this->qty)) {
4376
+			$this->qty=0;
4377
+		}
4378
+		if (empty($this->total_localtax1)) {
4379
+			$this->total_localtax1=0;
4380
+		}
4381
+		if (empty($this->total_localtax2)) {
4382
+			$this->total_localtax2=0;
4383
+		}
4384
+		if (empty($this->marque_tx)) {
4385
+			$this->marque_tx=0;
4386
+		}
4387
+		if (empty($this->marge_tx)) {
4388
+			$this->marge_tx=0;
4389
+		}
4390
+		if (empty($this->remise)) {
4391
+			$this->remise=0;
4392
+		}
4393
+		if (empty($this->remise_percent)) {
4394
+			$this->remise_percent=0;
4395
+		}
4396
+		if (empty($this->info_bits)) {
4397
+			$this->info_bits=0;
4398
+		}
4399
+        if (empty($this->special_code)) {
4400
+        	$this->special_code=0;
4401
+        }
4402
+		if (empty($this->product_type)) {
4403
+			$this->product_type=0;
4404
+		}
4405
+		if (empty($this->fk_parent_line)) {
4406
+			$this->fk_parent_line=0;
4407
+		}
4408
+		if (empty($this->pa_ht)) {
4409
+			$this->pa_ht=0;
4410
+		}
4114 4411
 
4115 4412
 		// if buy price not defined, define buyprice as configured in margin admin
4116 4413
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -4118,8 +4415,7 @@  discard block
 block discarded – undo
4118 4415
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4119 4416
 			{
4120 4417
 				return $result;
4121
-			}
4122
-			else
4418
+			} else
4123 4419
 			{
4124 4420
 				$this->pa_ht = $result;
4125 4421
 			}
@@ -4158,7 +4454,9 @@  discard block
 block discarded – undo
4158 4454
 		$sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4159 4455
 		$sql.= " , product_type=".$this->product_type;
4160 4456
 		$sql.= " , fk_parent_line=".(! empty($this->fk_parent_line)?$this->fk_parent_line:"null");
4161
-		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
4457
+		if (! empty($this->rang)) {
4458
+			$sql.= ", rang=".$this->rang;
4459
+		}
4162 4460
 		$sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4163 4461
 
4164 4462
 		// Multicurrency
@@ -4173,9 +4471,11 @@  discard block
 block discarded – undo
4173 4471
 		$resql=$this->db->query($sql);
4174 4472
 		if ($resql)
4175 4473
 		{
4176
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4474
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
4475
+				// For avoid conflicts if trigger used
4177 4476
 			{
4178 4477
 				$this->id=$this->rowid;
4478
+			}
4179 4479
 				$result=$this->insertExtraFields();
4180 4480
 				if ($result < 0)
4181 4481
 				{
@@ -4187,7 +4487,9 @@  discard block
 block discarded – undo
4187 4487
 			{
4188 4488
 	            // Call trigger
4189 4489
 	            $result=$this->call_trigger('LINEORDER_UPDATE',$user);
4190
-	            if ($result < 0) $error++;
4490
+	            if ($result < 0) {
4491
+	            	$error++;
4492
+	            }
4191 4493
 	            // End call triggers
4192 4494
 			}
4193 4495
 
@@ -4203,8 +4505,7 @@  discard block
 block discarded – undo
4203 4505
 			}
4204 4506
 			$this->db->rollback();
4205 4507
 			return -1*$error;
4206
-		}
4207
-		else
4508
+		} else
4208 4509
 		{
4209 4510
 			$this->error=$this->db->error();
4210 4511
 			$this->db->rollback();
@@ -4222,8 +4523,12 @@  discard block
 block discarded – undo
4222 4523
         $this->db->begin();
4223 4524
 
4224 4525
         // Clean parameters
4225
-        if (empty($this->total_localtax1)) $this->total_localtax1=0;
4226
-        if (empty($this->total_localtax2)) $this->total_localtax2=0;
4526
+        if (empty($this->total_localtax1)) {
4527
+        	$this->total_localtax1=0;
4528
+        }
4529
+        if (empty($this->total_localtax2)) {
4530
+        	$this->total_localtax2=0;
4531
+        }
4227 4532
 
4228 4533
         // Mise a jour ligne en base
4229 4534
         $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
@@ -4241,8 +4546,7 @@  discard block
 block discarded – undo
4241 4546
         {
4242 4547
             $this->db->commit();
4243 4548
             return 1;
4244
-        }
4245
-        else
4549
+        } else
4246 4550
         {
4247 4551
             $this->error=$this->db->error();
4248 4552
             $this->db->rollback();
Please login to merge, or discard this patch.
htdocs/compta/facture/class/facture.class.php 4 patches
Doc Comments   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -2408,17 +2408,17 @@  discard block
 block discarded – undo
2408 2408
 	 * 		@param    	double		$pu_ht              Unit price without tax (> 0 even for credit note)
2409 2409
 	 * 		@param    	double		$qty             	Quantity
2410 2410
 	 * 		@param    	double		$txtva           	Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
2411
-	 * 		@param		double		$txlocaltax1		Local tax 1 rate (deprecated)
2412
-	 *  	@param		double		$txlocaltax2		Local tax 2 rate (deprecated)
2411
+	 * 		@param		integer		$txlocaltax1		Local tax 1 rate (deprecated)
2412
+	 *  	@param		integer		$txlocaltax2		Local tax 2 rate (deprecated)
2413 2413
 	 *		@param    	int			$fk_product      	Id of predefined product/service
2414
-	 * 		@param    	double		$remise_percent  	Percent of discount on line
2414
+	 * 		@param    	integer		$remise_percent  	Percent of discount on line
2415 2415
 	 * 		@param    	int	$date_start      	Date start of service
2416 2416
 	 * 		@param    	int	$date_end        	Date end of service
2417 2417
 	 * 		@param    	int			$ventil          	Code of dispatching into accountancy
2418 2418
 	 * 		@param    	int			$info_bits			Bits de type de lignes
2419 2419
 	 *		@param    	int			$fk_remise_except	Id discount used
2420 2420
 	 *		@param		string		$price_base_type	'HT' or 'TTC'
2421
-	 * 		@param    	double		$pu_ttc             Unit price with tax (> 0 even for credit note)
2421
+	 * 		@param    	integer		$pu_ttc             Unit price with tax (> 0 even for credit note)
2422 2422
 	 * 		@param		int			$type				Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
2423 2423
 	 *      @param      int			$rang               Position of line
2424 2424
 	 *      @param		int			$special_code		Special code (also used by externals modules!)
@@ -2428,11 +2428,11 @@  discard block
 block discarded – undo
2428 2428
 	 * 		@param		int			$fk_fournprice		Supplier price id (to calculate margin) or ''
2429 2429
 	 * 		@param		int			$pa_ht				Buying price of line (to calculate margin) or ''
2430 2430
 	 * 		@param		string		$label				Label of the line (deprecated, do not use)
2431
-	 *		@param		array		$array_options		extrafields array
2431
+	 *		@param		integer		$array_options		extrafields array
2432 2432
 	 *      @param      int         $situation_percent  Situation advance percentage
2433 2433
 	 *      @param      int         $fk_prev_id         Previous situation line id reference
2434 2434
 	 * 		@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2435
-	 * 		@param		double		$pu_ht_devise		Unit price in currency
2435
+	 * 		@param		integer		$pu_ht_devise		Unit price in currency
2436 2436
 	 *    	@return    	int             				<0 if KO, Id of line if OK
2437 2437
 	 */
2438 2438
 	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0)
@@ -2637,8 +2637,8 @@  discard block
 block discarded – undo
2637 2637
 	 *  @param     	int		$date_start      	Date de debut de validite du service
2638 2638
 	 *  @param     	int		$date_end        	Date de fin de validite du service
2639 2639
 	 *  @param     	double		$txtva          	VAT Rate
2640
-	 * 	@param		double		$txlocaltax1		Local tax 1 rate
2641
-	 *  @param		double		$txlocaltax2		Local tax 2 rate
2640
+	 * 	@param		integer		$txlocaltax1		Local tax 1 rate
2641
+	 *  @param		integer		$txlocaltax2		Local tax 2 rate
2642 2642
 	 * 	@param     	string		$price_base_type 	HT or TTC
2643 2643
 	 * 	@param     	int			$info_bits 		    Miscellaneous informations
2644 2644
 	 * 	@param		int			$type				Type of line (0=product, 1=service)
@@ -2648,10 +2648,10 @@  discard block
 block discarded – undo
2648 2648
 	 * 	@param		int			$pa_ht				Price (without tax) of product when it was bought
2649 2649
 	 * 	@param		string		$label				Label of the line (deprecated, do not use)
2650 2650
 	 * 	@param		int			$special_code		Special code (also used by externals modules!)
2651
-     *  @param		array		$array_options		extrafields array
2651
+     *  @param		integer		$array_options		extrafields array
2652 2652
 	 * 	@param      int         $situation_percent  Situation advance percentage
2653 2653
 	 * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2654
-	 * 	@param		double		$pu_ht_devise		Unit price in currency
2654
+	 * 	@param		integer		$pu_ht_devise		Unit price in currency
2655 2655
 	 * 	@param		int			$notrigger			disable line update trigger
2656 2656
 	 *  @return    	int             				< 0 if KO, > 0 if OK
2657 2657
 	 */
@@ -3525,7 +3525,7 @@  discard block
 block discarded – undo
3525 3525
 	 *  Use the remain to pay excluding all existing open direct debit requests.
3526 3526
 	 *
3527 3527
 	 *	@param      User	$fuser      User asking the direct debit transfer
3528
-	 *  @param		float	$amount		Amount we request direct debit for
3528
+	 *  @param		integer	$amount		Amount we request direct debit for
3529 3529
 	 *	@return     int         		<0 if KO, >0 if OK
3530 3530
 	 */
3531 3531
 	function demande_prelevement($fuser, $amount=0)
Please login to merge, or discard this patch.
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -145,30 +145,30 @@  discard block
 block discarded – undo
145 145
 
146 146
 	public $oldcopy;
147 147
 
148
-    /**
149
-     * Standard invoice
150
-     */
151
-    const TYPE_STANDARD = 0;
152
-
153
-    /**
154
-     * Replacement invoice
155
-     */
156
-    const TYPE_REPLACEMENT = 1;
157
-
158
-    /**
159
-     * Credit note invoice
160
-     */
161
-    const TYPE_CREDIT_NOTE = 2;
162
-
163
-    /**
164
-     * Deposit invoice
165
-     */
166
-    const TYPE_DEPOSIT = 3;
167
-
168
-    /**
169
-     * Proforma invoice (should not be used. a proforma is an order)
170
-     */
171
-    const TYPE_PROFORMA = 4;
148
+	/**
149
+	 * Standard invoice
150
+	 */
151
+	const TYPE_STANDARD = 0;
152
+
153
+	/**
154
+	 * Replacement invoice
155
+	 */
156
+	const TYPE_REPLACEMENT = 1;
157
+
158
+	/**
159
+	 * Credit note invoice
160
+	 */
161
+	const TYPE_CREDIT_NOTE = 2;
162
+
163
+	/**
164
+	 * Deposit invoice
165
+	 */
166
+	const TYPE_DEPOSIT = 3;
167
+
168
+	/**
169
+	 * Proforma invoice (should not be used. a proforma is an order)
170
+	 */
171
+	const TYPE_PROFORMA = 4;
172 172
 
173 173
 	/**
174 174
 	 * Situation invoice
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 		if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
243 243
 		if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
244 244
 		$this->brouillon = 1;
245
-        if (empty($this->entity)) $this->entity = $conf->entity;
245
+		if (empty($this->entity)) $this->entity = $conf->entity;
246 246
 
247 247
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
248 248
 		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		// Create invoice from a template invoice
280 280
 		if ($this->fac_rec > 0)
281 281
 		{
282
-		    $this->fk_fac_rec_source = $this->fac_rec;
282
+			$this->fk_fac_rec_source = $this->fac_rec;
283 283
 
284 284
 			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
285 285
 			$_facrec = new FactureRec($this->db);
@@ -315,9 +315,9 @@  discard block
 block discarded – undo
315 315
 			$this->ref_client=trim($this->ref_client);
316 316
 			$this->note_public=trim($this->note_public);
317 317
 			$this->note_private=trim($this->note_private);
318
-		    $this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
318
+			$this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
319 319
 
320
-		    $this->array_options=$_facrec->array_options;
320
+			$this->array_options=$_facrec->array_options;
321 321
 
322 322
 			//if (! $this->remise) $this->remise = 0;
323 323
 			if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
@@ -330,12 +330,12 @@  discard block
 block discarded – undo
330 330
 			// For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
331 331
 			if ($_facrec->frequency > 0)
332 332
 			{
333
-			    dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
334
-			    if (empty($_facrec->date_when)) $_facrec->date_when = $now;
335
-                $next_date = $_facrec->getNextDate();   // Calculate next date
336
-                $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
337
-                //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1);		// Not required, +1 already included into setNextDate when second param is 1.
338
-                $result = $_facrec->setNextDate($next_date,1);
333
+				dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
334
+				if (empty($_facrec->date_when)) $_facrec->date_when = $now;
335
+				$next_date = $_facrec->getNextDate();   // Calculate next date
336
+				$result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
337
+				//$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1);		// Not required, +1 already included into setNextDate when second param is 1.
338
+				$result = $_facrec->setNextDate($next_date,1);
339 339
 			}
340 340
 
341 341
 			// Define lang of customer
@@ -346,23 +346,23 @@  discard block
 block discarded – undo
346 346
 			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang=$this->default_lang;                  // for thirdparty
347 347
 			if (! empty($newlang))
348 348
 			{
349
-			    $outputlangs = new Translate("",$conf);
350
-			    $outputlangs->setDefaultLang($newlang);
349
+				$outputlangs = new Translate("",$conf);
350
+				$outputlangs->setDefaultLang($newlang);
351 351
 			}
352 352
 
353 353
 			// Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
354 354
 			$substitutionarray=array(
355
-			    '__TOTAL_HT__' => price($this->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
356
-			    '__TOTAL_TTC__' => price($this->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
357
-			    '__INVOICE_PREVIOUS_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'),
358
-			    '__INVOICE_MONTH__' => dol_print_date($this->date, '%m'),
359
-			    '__INVOICE_NEXT_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'),
360
-			    '__INVOICE_PREVIOUS_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'),
361
-			    '__INVOICE_MONTH_TEXT__' => dol_print_date($this->date, '%B'),
362
-			    '__INVOICE_NEXT_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'),
363
-			    '__INVOICE_PREVIOUS_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'),
364
-			    '__INVOICE_YEAR__' => dol_print_date($this->date, '%Y'),
365
-			    '__INVOICE_NEXT_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'),
355
+				'__TOTAL_HT__' => price($this->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
356
+				'__TOTAL_TTC__' => price($this->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
357
+				'__INVOICE_PREVIOUS_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'),
358
+				'__INVOICE_MONTH__' => dol_print_date($this->date, '%m'),
359
+				'__INVOICE_NEXT_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'),
360
+				'__INVOICE_PREVIOUS_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'),
361
+				'__INVOICE_MONTH_TEXT__' => dol_print_date($this->date, '%B'),
362
+				'__INVOICE_NEXT_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'),
363
+				'__INVOICE_PREVIOUS_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'),
364
+				'__INVOICE_YEAR__' => dol_print_date($this->date, '%Y'),
365
+				'__INVOICE_NEXT_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'),
366 366
 				// Only for tempalte invoice
367 367
 				'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__' => dol_print_date($originaldatewhen, 'dayhour'),
368 368
 				'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__' => dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour')
@@ -397,14 +397,14 @@  discard block
 block discarded – undo
397 397
 		$sql.= ", note_private";
398 398
 		$sql.= ", note_public";
399 399
 		$sql.= ", ref_client, ref_int";
400
-        $sql.= ", fk_account";
400
+		$sql.= ", fk_account";
401 401
 		$sql.= ", fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
402 402
 		$sql.= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
403 403
 		$sql.= ", situation_cycle_ref, situation_counter, situation_final";
404 404
 		$sql.= ", fk_incoterms, location_incoterms";
405
-        $sql.= ", fk_multicurrency";
406
-        $sql.= ", multicurrency_code";
407
-        $sql.= ", multicurrency_tx";
405
+		$sql.= ", fk_multicurrency";
406
+		$sql.= ", multicurrency_code";
407
+		$sql.= ", multicurrency_tx";
408 408
 		$sql.= ")";
409 409
 		$sql.= " VALUES (";
410 410
 		$sql.= "'(PROV)'";
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 		$sql.= ", ".($this->situation_counter?"'".$this->db->escape($this->situation_counter)."'":"null");
434 434
 		$sql.= ", ".($this->situation_final?$this->situation_final:0);
435 435
 		$sql.= ", ".(int) $this->fk_incoterms;
436
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
436
+		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
437 437
 		$sql.= ", ".(int) $this->fk_multicurrency;
438 438
 		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
439 439
 		$sql.= ", ".(double) $this->multicurrency_tx;
@@ -456,28 +456,28 @@  discard block
 block discarded – undo
456 456
 			{
457 457
 				foreach($this->linked_objects as $origin => $tmp_origin_id)
458 458
 				{
459
-				    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
460
-				    {
461
-				        foreach($tmp_origin_id as $origin_id)
462
-				        {
463
-				            $ret = $this->add_object_linked($origin, $origin_id);
464
-				            if (! $ret)
465
-				            {
466
-				                dol_print_error($this->db);
467
-				                $error++;
468
-				            }
469
-				        }
470
-				    }
471
-				    else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
472
-				    {
473
-				        $origin_id = $tmp_origin_id;
474
-    					$ret = $this->add_object_linked($origin, $origin_id);
475
-    					if (! $ret)
476
-    					{
477
-    						dol_print_error($this->db);
478
-    						$error++;
479
-    					}
480
-				    }
459
+					if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
460
+					{
461
+						foreach($tmp_origin_id as $origin_id)
462
+						{
463
+							$ret = $this->add_object_linked($origin, $origin_id);
464
+							if (! $ret)
465
+							{
466
+								dol_print_error($this->db);
467
+								$error++;
468
+							}
469
+						}
470
+					}
471
+					else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
472
+					{
473
+						$origin_id = $tmp_origin_id;
474
+						$ret = $this->add_object_linked($origin, $origin_id);
475
+						if (! $ret)
476
+						{
477
+							dol_print_error($this->db);
478
+							$error++;
479
+						}
480
+					}
481 481
 				}
482 482
 			}
483 483
 
@@ -487,20 +487,20 @@  discard block
 block discarded – undo
487 487
 				$originidforcontact = $this->origin_id;
488 488
 				if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
489 489
 				{
490
-				    require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
491
-				    $exp = new Expedition($this->db);
492
-				    $exp->fetch($this->origin_id);
493
-				    $exp->fetchObjectLinked();
494
-				    if (count($exp->linkedObjectsIds['commande']) > 0)
495
-				    {
496
-				        foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
497
-				        {
498
-				            $originforcontact = 'commande';
499
-				            if (is_object($value)) $originidforcontact = $value->id;
500
-				            else $originidforcontact = $value;
501
-				            break; // We take first one
502
-				        }
503
-				    }
490
+					require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
491
+					$exp = new Expedition($this->db);
492
+					$exp->fetch($this->origin_id);
493
+					$exp->fetchObjectLinked();
494
+					if (count($exp->linkedObjectsIds['commande']) > 0)
495
+					{
496
+						foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
497
+						{
498
+							$originforcontact = 'commande';
499
+							if (is_object($value)) $originidforcontact = $value->id;
500
+							else $originidforcontact = $value;
501
+							break; // We take first one
502
+						}
503
+					}
504 504
 				}
505 505
 
506 506
 				$sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
@@ -509,11 +509,11 @@  discard block
 block discarded – undo
509 509
 				$resqlcontact = $this->db->query($sqlcontact);
510 510
 				if ($resqlcontact)
511 511
 				{
512
-				    while($objcontact = $this->db->fetch_object($resqlcontact))
513
-				    {
514
-				        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
515
-				        $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
516
-				    }
512
+					while($objcontact = $this->db->fetch_object($resqlcontact))
513
+					{
514
+						//print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
515
+						$this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
516
+					}
517 517
 				}
518 518
 				else dol_print_error($resqlcontact);
519 519
 			}
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
 
534 534
 					// TODO This seems not used. Here we put origin 'facture' but after,  we put an id of object !
535 535
 					$newinvoiceline->origin = $this->element;
536
-                    $newinvoiceline->origin_id = $this->lines[$i]->id;
536
+					$newinvoiceline->origin_id = $this->lines[$i]->id;
537 537
 
538 538
 					if ($result >= 0)
539 539
 					{
@@ -566,13 +566,13 @@  discard block
 block discarded – undo
566 566
 
567 567
 				foreach ($this->lines as $i => $val)
568 568
 				{
569
-                	$line = $this->lines[$i];
569
+					$line = $this->lines[$i];
570 570
 
571
-                	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
572
-				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
573
-                	if (! is_object($line)) $line = (object) $line;
571
+					// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
572
+					//if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
573
+					if (! is_object($line)) $line = (object) $line;
574 574
 
575
-				    if ($result >= 0)
575
+					if ($result >= 0)
576 576
 					{
577 577
 						// Reset fk_parent_line for no child products and special product
578 578
 						if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
@@ -598,8 +598,8 @@  discard block
 block discarded – undo
598 598
 							$line->product_type,
599 599
 							$line->rang,
600 600
 							$line->special_code,
601
-                            $this->element,
602
-                            $line->id,
601
+							$this->element,
602
+							$line->id,
603 603
 							$fk_parent_line,
604 604
 							$line->fk_fournprice,
605 605
 							$line->pa_ht,
@@ -697,17 +697,17 @@  discard block
 block discarded – undo
697 697
 						{*/
698 698
 					if (! $error)
699 699
 					{
700
-					    $result=$this->insertExtraFields();
701
-					    if ($result < 0) $error++;
700
+						$result=$this->insertExtraFields();
701
+						if ($result < 0) $error++;
702 702
 					}
703 703
 						/*}
704 704
 					}
705 705
 					else if ($reshook < 0) $error++;*/
706 706
 
707
-                    // Call trigger
708
-                    $result=$this->call_trigger('BILL_CREATE',$user);
709
-                    if ($result < 0) $error++;
710
-                    // End call triggers
707
+					// Call trigger
708
+					$result=$this->call_trigger('BILL_CREATE',$user);
709
+					if ($result < 0) $error++;
710
+					// End call triggers
711 711
 
712 712
 					if (! $error)
713 713
 					{
@@ -757,14 +757,14 @@  discard block
 block discarded – undo
757 757
 		// Charge facture source
758 758
 		$facture=new Facture($this->db);
759 759
 
760
-                $this->fetch_optionals();
761
-                if(!empty($this->array_options)){
762
-                    $facture->array_options = $this->array_options;
763
-                }
760
+				$this->fetch_optionals();
761
+				if(!empty($this->array_options)){
762
+					$facture->array_options = $this->array_options;
763
+				}
764 764
 
765
-                foreach($this->lines as &$line){
766
-                    $line->fetch_optionals();//fetch extrafields
767
-                }
765
+				foreach($this->lines as &$line){
766
+					$line->fetch_optionals();//fetch extrafields
767
+				}
768 768
 
769 769
 		$facture->fk_facture_source = $this->fk_facture_source;
770 770
 		$facture->type 			    = $this->type;
@@ -926,10 +926,10 @@  discard block
 block discarded – undo
926 926
 				if ($reshook < 0) $error++;
927 927
 			}
928 928
 
929
-            // Call trigger
930
-            $result=$this->call_trigger('BILL_CLONE',$user);
931
-            if ($result < 0) $error++;
932
-            // End call triggers
929
+			// Call trigger
930
+			$result=$this->call_trigger('BILL_CLONE',$user);
931
+			if ($result < 0) $error++;
932
+			// End call triggers
933 933
 		}
934 934
 
935 935
 		unset($this->context['createfromclone']);
@@ -994,7 +994,7 @@  discard block
 block discarded – undo
994 994
 			$marginInfos			= getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
995 995
 			$line->pa_ht			= $marginInfos[0];
996 996
 
997
-            // get extrafields from original line
997
+			// get extrafields from original line
998 998
 			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
999 999
 			foreach($object->lines[$i]->array_options as $options_key => $value)
1000 1000
 				$line->array_options[$options_key] = $value;
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 		$this->origin				= $object->element;
1019 1019
 		$this->origin_id			= $object->id;
1020 1020
 
1021
-        // get extrafields from original line
1021
+		// get extrafields from original line
1022 1022
 		$object->fetch_optionals($object->id);
1023 1023
 		foreach($object->array_options as $options_key => $value)
1024 1024
 			$this->array_options[$options_key] = $value;
@@ -1083,16 +1083,16 @@  discard block
 block discarded – undo
1083 1083
 	 *  @param  int		$max             			Maxlength of ref
1084 1084
 	 *  @param  int		$short           			1=Return just URL
1085 1085
 	 *  @param  string  $moretitle       			Add more text to title tooltip
1086
-     *  @param	int  	$notooltip		 			1=Disable tooltip
1087
-     *  @param  int     $addlinktonotes  			1=Add link to notes
1088
-     *  @param  int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1086
+	 *  @param	int  	$notooltip		 			1=Disable tooltip
1087
+	 *  @param  int     $addlinktonotes  			1=Add link to notes
1088
+	 *  @param  int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1089 1089
 	 *  @return string 			         			String with URL
1090 1090
 	 */
1091 1091
 	function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1)
1092 1092
 	{
1093 1093
 		global $langs, $conf, $user, $form;
1094 1094
 
1095
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1095
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1096 1096
 
1097 1097
 		$result='';
1098 1098
 
@@ -1113,59 +1113,59 @@  discard block
 block discarded – undo
1113 1113
 		if ($this->type == self::TYPE_REPLACEMENT) $picto.='r';	// Replacement invoice
1114 1114
 		if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a';	// Credit note
1115 1115
 		if ($this->type == self::TYPE_DEPOSIT) $picto.='d';	// Deposit invoice
1116
-        $label='';
1117
-
1118
-        if ($user->rights->facture->lire) {
1119
-            $label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
1120
-            if (! empty($this->ref))
1121
-                $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
1122
-            if (! empty($this->ref_client))
1123
-                $label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
1124
-            if (! empty($this->total_ht))
1125
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1126
-            if (! empty($this->total_tva))
1127
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1128
-            if (! empty($this->total_ttc))
1129
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1130
-    		if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1131
-    		if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1132
-    		if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1133
-    		if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1134
-    		if ($moretitle) $label.=' - '.$moretitle;
1135
-        }
1116
+		$label='';
1117
+
1118
+		if ($user->rights->facture->lire) {
1119
+			$label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
1120
+			if (! empty($this->ref))
1121
+				$label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
1122
+			if (! empty($this->ref_client))
1123
+				$label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
1124
+			if (! empty($this->total_ht))
1125
+				$label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1126
+			if (! empty($this->total_tva))
1127
+				$label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1128
+			if (! empty($this->total_ttc))
1129
+				$label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1130
+			if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1131
+			if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1132
+			if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1133
+			if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1134
+			if ($moretitle) $label.=' - '.$moretitle;
1135
+		}
1136 1136
 
1137 1137
 		$linkclose='';
1138 1138
 		if (empty($notooltip) && $user->rights->facture->lire)
1139 1139
 		{
1140
-		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1141
-		    {
1142
-		        $label=$langs->trans("ShowInvoice");
1143
-		        $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1144
-		    }
1145
-		    $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1146
-		    $linkclose.=' class="classfortooltip"';
1140
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1141
+			{
1142
+				$label=$langs->trans("ShowInvoice");
1143
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1144
+			}
1145
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1146
+			$linkclose.=' class="classfortooltip"';
1147 1147
 		}
1148 1148
 
1149
-        $linkstart='<a href="'.$url.'"';
1150
-        $linkstart.=$linkclose.'>';
1149
+		$linkstart='<a href="'.$url.'"';
1150
+		$linkstart.=$linkclose.'>';
1151 1151
 		$linkend='</a>';
1152 1152
 
1153
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
1153
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
1154 1154
 		if ($withpicto && $withpicto != 2) $result.=' ';
1155 1155
 		if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
1156 1156
 
1157 1157
 		if ($addlinktonotes)
1158 1158
 		{
1159
-		    $txttoshow=($user->societe_id>0?$this->note_public:$this->note_private);
1160
-		    if ($txttoshow)
1161
-		    {
1162
-                $notetoshow=$langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow,1);
1163
-    		    $result.=' <span class="note inline-block">';
1164
-    		    $result.='<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'.img_picto('','object_generic').'</a>';
1165
-    		    //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1166
-    		    //$result.='</a>';
1167
-    		    $result.='</span>';
1168
-		    }
1159
+			$txttoshow=($user->societe_id>0?$this->note_public:$this->note_private);
1160
+			if ($txttoshow)
1161
+			{
1162
+				$notetoshow=$langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow,1);
1163
+				$result.=' <span class="note inline-block">';
1164
+				$result.='<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'.img_picto('','object_generic').'</a>';
1165
+				//$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1166
+				//$result.='</a>';
1167
+				$result.='</span>';
1168
+			}
1169 1169
 		}
1170 1170
 
1171 1171
 		return $result;
@@ -1203,8 +1203,8 @@  discard block
 block discarded – undo
1203 1203
 		$sql.= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1204 1204
 		$sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1205 1205
 		$sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1206
-        $sql.= ', f.fk_incoterms, f.location_incoterms';
1207
-        $sql.= ", i.libelle as libelle_incoterms";
1206
+		$sql.= ', f.fk_incoterms, f.location_incoterms';
1207
+		$sql.= ", i.libelle as libelle_incoterms";
1208 1208
 		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1209 1209
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')';
1210 1210
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')';
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
 				$line->qty              = $objp->qty;
1376 1376
 				$line->subprice         = $objp->subprice;
1377 1377
 
1378
-                $line->vat_src_code     = $objp->vat_src_code;
1378
+				$line->vat_src_code     = $objp->vat_src_code;
1379 1379
 				$line->tva_tx           = $objp->tva_tx;
1380 1380
 				$line->localtax1_tx     = $objp->localtax1_tx;
1381 1381
 				$line->localtax2_tx     = $objp->localtax2_tx;
@@ -1551,10 +1551,10 @@  discard block
 block discarded – undo
1551 1551
 		{
1552 1552
 			if (! $notrigger)
1553 1553
 			{
1554
-	            // Call trigger
1555
-	            $result=$this->call_trigger('BILL_MODIFY',$user);
1556
-	            if ($result < 0) $error++;
1557
-	            // End call triggers
1554
+				// Call trigger
1555
+				$result=$this->call_trigger('BILL_MODIFY',$user);
1556
+				if ($result < 0) $error++;
1557
+				// End call triggers
1558 1558
 			}
1559 1559
 		}
1560 1560
 
@@ -1620,13 +1620,13 @@  discard block
 block discarded – undo
1620 1620
 			// Get buy/cost price of invoice that is source of discount
1621 1621
 			if ($remise->fk_facture_source > 0)
1622 1622
 			{
1623
-    			$srcinvoice=new Facture($this->db);
1624
-    			$srcinvoice->fetch($remise->fk_facture_source);
1625
-    			$totalcostpriceofinvoice=0;
1626
-    			include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';  // TODO Move this into commonobject
1627
-    			$formmargin=new FormMargin($this->db);
1628
-    			$arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false);
1629
-        		$facligne->pa_ht = $arraytmp['pa_total'];
1623
+				$srcinvoice=new Facture($this->db);
1624
+				$srcinvoice->fetch($remise->fk_facture_source);
1625
+				$totalcostpriceofinvoice=0;
1626
+				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';  // TODO Move this into commonobject
1627
+				$formmargin=new FormMargin($this->db);
1628
+				$arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false);
1629
+				$facligne->pa_ht = $arraytmp['pa_total'];
1630 1630
 			}
1631 1631
 
1632 1632
 			$facligne->total_ht  = -$remise->amount_ht;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
 	 */
1687 1687
 	function set_ref_client($ref_client, $notrigger=0)
1688 1688
 	{
1689
-	    global $user;
1689
+		global $user;
1690 1690
 
1691 1691
 		$error=0;
1692 1692
 
@@ -1768,10 +1768,10 @@  discard block
 block discarded – undo
1768 1768
 
1769 1769
 		if (! $error && ! $notrigger)
1770 1770
 		{
1771
-            // Call trigger
1772
-            $result=$this->call_trigger('BILL_DELETE',$user);
1773
-            if ($result < 0) $error++;
1774
-            // End call triggers
1771
+			// Call trigger
1772
+			$result=$this->call_trigger('BILL_DELETE',$user);
1773
+			if ($result < 0) $error++;
1774
+			// End call triggers
1775 1775
 		}
1776 1776
 
1777 1777
 		// Removed extrafields
@@ -1939,10 +1939,10 @@  discard block
 block discarded – undo
1939 1939
 			$resql = $this->db->query($sql);
1940 1940
 			if ($resql)
1941 1941
 			{
1942
-	            // Call trigger
1943
-	            $result=$this->call_trigger('BILL_PAYED',$user);
1944
-	            if ($result < 0) $error++;
1945
-	            // End call triggers
1942
+				// Call trigger
1943
+				$result=$this->call_trigger('BILL_PAYED',$user);
1944
+				if ($result < 0) $error++;
1945
+				// End call triggers
1946 1946
 			}
1947 1947
 			else
1948 1948
 			{
@@ -1990,10 +1990,10 @@  discard block
 block discarded – undo
1990 1990
 		$resql = $this->db->query($sql);
1991 1991
 		if ($resql)
1992 1992
 		{
1993
-            // Call trigger
1994
-            $result=$this->call_trigger('BILL_UNPAYED',$user);
1995
-            if ($result < 0) $error++;
1996
-            // End call triggers
1993
+			// Call trigger
1994
+			$result=$this->call_trigger('BILL_UNPAYED',$user);
1995
+			if ($result < 0) $error++;
1996
+			// End call triggers
1997 1997
 		}
1998 1998
 		else
1999 1999
 		{
@@ -2050,14 +2050,14 @@  discard block
 block discarded – undo
2050 2050
 			$resql=$this->db->query($sql);
2051 2051
 			if ($resql)
2052 2052
 			{
2053
-	            // Call trigger
2054
-	            $result=$this->call_trigger('BILL_CANCEL',$user);
2055
-	            if ($result < 0)
2056
-	            {
2053
+				// Call trigger
2054
+				$result=$this->call_trigger('BILL_CANCEL',$user);
2055
+				if ($result < 0)
2056
+				{
2057 2057
 					$this->db->rollback();
2058 2058
 					return -1;
2059 2059
 				}
2060
-	            // End call triggers
2060
+				// End call triggers
2061 2061
 
2062 2062
 				$this->db->commit();
2063 2063
 				return 1;
@@ -2085,7 +2085,7 @@  discard block
 block discarded – undo
2085 2085
 	 * @param   string	$force_number	Reference to force on invoice
2086 2086
 	 * @param	int		$idwarehouse	Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease)
2087 2087
 	 * @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2088
-     * @return	int						<0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK
2088
+	 * @return	int						<0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK
2089 2089
 	 */
2090 2090
 	function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
2091 2091
 	{
@@ -2109,12 +2109,12 @@  discard block
 block discarded – undo
2109 2109
 		}
2110 2110
 		if (count($this->lines) <= 0)
2111 2111
 		{
2112
-        	$langs->load("errors");
2112
+			$langs->load("errors");
2113 2113
 			$this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
2114 2114
 			return -1;
2115 2115
 		}
2116 2116
 		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
2117
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
2117
+	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
2118 2118
 		{
2119 2119
 			$this->error='Permission denied';
2120 2120
 			dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
@@ -2245,10 +2245,10 @@  discard block
 block discarded – undo
2245 2245
 			// Trigger calls
2246 2246
 			if (! $error && ! $notrigger)
2247 2247
 			{
2248
-	            // Call trigger
2249
-	            $result=$this->call_trigger('BILL_VALIDATE',$user);
2250
-	            if ($result < 0) $error++;
2251
-	            // End call triggers
2248
+				// Call trigger
2249
+				$result=$this->call_trigger('BILL_VALIDATE',$user);
2250
+				if ($result < 0) $error++;
2251
+				// End call triggers
2252 2252
 			}
2253 2253
 
2254 2254
 			if (! $error)
@@ -2271,16 +2271,16 @@  discard block
 block discarded – undo
2271 2271
 						if (@rename($dirsource, $dirdest))
2272 2272
 						{
2273 2273
 							dol_syslog("Rename ok");
2274
-	                        // Rename docs starting with $oldref with $newref
2275
-	                        $listoffiles=dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
2276
-	                        foreach($listoffiles as $fileentry)
2277
-	                        {
2278
-	                        	$dirsource=$fileentry['name'];
2279
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
2280
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
2281
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
2282
-	                        	@rename($dirsource, $dirdest);
2283
-	                        }
2274
+							// Rename docs starting with $oldref with $newref
2275
+							$listoffiles=dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
2276
+							foreach($listoffiles as $fileentry)
2277
+							{
2278
+								$dirsource=$fileentry['name'];
2279
+								$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
2280
+								$dirsource=$fileentry['path'].'/'.$dirsource;
2281
+								$dirdest=$fileentry['path'].'/'.$dirdest;
2282
+								@rename($dirsource, $dirdest);
2283
+							}
2284 2284
 						}
2285 2285
 					}
2286 2286
 				}
@@ -2304,18 +2304,18 @@  discard block
 block discarded – undo
2304 2304
 				$this->date_validation=$now;
2305 2305
 				$i = 0;
2306 2306
 
2307
-                if (!empty($conf->global->INVOICE_USE_SITUATION))
2308
-                {
2309
-    				$final = True;
2310
-    				$nboflines = count($this->lines);
2311
-    				while (($i < $nboflines) && $final) {
2312
-    					$final = ($this->lines[$i]->situation_percent == 100);
2313
-    					$i++;
2314
-    				}
2315
-    				if ($final) {
2316
-    					$this->setFinal($user);
2317
-    				}
2318
-                }
2307
+				if (!empty($conf->global->INVOICE_USE_SITUATION))
2308
+				{
2309
+					$final = True;
2310
+					$nboflines = count($this->lines);
2311
+					while (($i < $nboflines) && $final) {
2312
+						$final = ($this->lines[$i]->situation_percent == 100);
2313
+						$i++;
2314
+					}
2315
+					if ($final) {
2316
+						$this->setFinal($user);
2317
+					}
2318
+				}
2319 2319
 			}
2320 2320
 		}
2321 2321
 		else
@@ -2428,15 +2428,15 @@  discard block
 block discarded – undo
2428 2428
 				$old_statut=$this->statut;
2429 2429
 				$this->brouillon = 1;
2430 2430
 				$this->statut = self::STATUS_DRAFT;
2431
-	            // Call trigger
2432
-	            $result=$this->call_trigger('BILL_UNVALIDATE',$user);
2433
-	            if ($result < 0)
2431
+				// Call trigger
2432
+				$result=$this->call_trigger('BILL_UNVALIDATE',$user);
2433
+				if ($result < 0)
2434 2434
 				{
2435 2435
 					$error++;
2436 2436
 					$this->statut=$old_statut;
2437 2437
 					$this->brouillon=0;
2438 2438
 				}
2439
-	            // End call triggers
2439
+				// End call triggers
2440 2440
 			} else {
2441 2441
 				$this->db->rollback();
2442 2442
 				return -1;
@@ -2531,8 +2531,8 @@  discard block
 block discarded – undo
2531 2531
 		$vat_src_code='';
2532 2532
 		if (preg_match('/\((.*)\)/', $txtva, $reg))
2533 2533
 		{
2534
-		    $vat_src_code = $reg[1];
2535
-		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2534
+			$vat_src_code = $reg[1];
2535
+			$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2536 2536
 		}
2537 2537
 
2538 2538
 		$remise_percent=price2num($remise_percent);
@@ -2568,8 +2568,8 @@  discard block
 block discarded – undo
2568 2568
 				$product_type=$product->type;
2569 2569
 
2570 2570
 				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2571
-                    $langs->load("errors");
2572
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2571
+					$langs->load("errors");
2572
+					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2573 2573
 					$this->db->rollback();
2574 2574
 					return -3;
2575 2575
 				}
@@ -2591,8 +2591,8 @@  discard block
 block discarded – undo
2591 2591
 
2592 2592
 			// MultiCurrency
2593 2593
 			$multicurrency_total_ht  = $tabprice[16];
2594
-            $multicurrency_total_tva = $tabprice[17];
2595
-            $multicurrency_total_ttc = $tabprice[18];
2594
+			$multicurrency_total_tva = $tabprice[17];
2595
+			$multicurrency_total_ttc = $tabprice[18];
2596 2596
 			$pu_ht_devise = $tabprice[19];
2597 2597
 
2598 2598
 			// Rank to use
@@ -2655,8 +2655,8 @@  discard block
 block discarded – undo
2655 2655
 			$this->line->multicurrency_code			= $this->multicurrency_code;
2656 2656
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
2657 2657
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2658
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2659
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2658
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2659
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2660 2660
 
2661 2661
 			if (is_array($array_options) && count($array_options)>0) {
2662 2662
 				$this->line->array_options=$array_options;
@@ -2713,7 +2713,7 @@  discard block
 block discarded – undo
2713 2713
 	 * 	@param		int			$pa_ht				Price (without tax) of product when it was bought
2714 2714
 	 * 	@param		string		$label				Label of the line (deprecated, do not use)
2715 2715
 	 * 	@param		int			$special_code		Special code (also used by externals modules!)
2716
-     *  @param		array		$array_options		extrafields array
2716
+	 *  @param		array		$array_options		extrafields array
2717 2717
 	 * 	@param      int         $situation_percent  Situation advance percentage
2718 2718
 	 * 	@param 		string		$fk_unit 			Code of the unit to use. Null to use the default one
2719 2719
 	 * 	@param		double		$pu_ht_devise		Unit price in currency
@@ -2771,12 +2771,12 @@  discard block
 block discarded – undo
2771 2771
 			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
2772 2772
 
2773 2773
 			// Clean vat code
2774
-    		$vat_src_code='';
2775
-    		if (preg_match('/\((.*)\)/', $txtva, $reg))
2776
-    		{
2777
-    		    $vat_src_code = $reg[1];
2778
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2779
-    		}
2774
+			$vat_src_code='';
2775
+			if (preg_match('/\((.*)\)/', $txtva, $reg))
2776
+			{
2777
+				$vat_src_code = $reg[1];
2778
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2779
+			}
2780 2780
 
2781 2781
 			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
2782 2782
 
@@ -2791,8 +2791,8 @@  discard block
 block discarded – undo
2791 2791
 
2792 2792
 			// MultiCurrency
2793 2793
 			$multicurrency_total_ht  = $tabprice[16];
2794
-            $multicurrency_total_tva = $tabprice[17];
2795
-            $multicurrency_total_ttc = $tabprice[18];
2794
+			$multicurrency_total_tva = $tabprice[17];
2795
+			$multicurrency_total_ttc = $tabprice[18];
2796 2796
 			$pu_ht_devise = $tabprice[19];
2797 2797
 
2798 2798
 			// Old properties: $price, $remise (deprecated)
@@ -2816,8 +2816,8 @@  discard block
 block discarded – undo
2816 2816
 				$product_type=$product->type;
2817 2817
 
2818 2818
 				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2819
-                    $langs->load("errors");
2820
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2819
+					$langs->load("errors");
2820
+					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2821 2821
 					$this->db->rollback();
2822 2822
 					return -3;
2823 2823
 				}
@@ -2827,7 +2827,7 @@  discard block
 block discarded – undo
2827 2827
 
2828 2828
 			$line->oldline = $staticline;
2829 2829
 			$this->line = $line;
2830
-            $this->line->context = $this->context;
2830
+			$this->line->context = $this->context;
2831 2831
 
2832 2832
 			// Reorder if fk_parent_line change
2833 2833
 			if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
@@ -2871,8 +2871,8 @@  discard block
 block discarded – undo
2871 2871
 			// Multicurrency
2872 2872
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
2873 2873
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2874
-            $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2875
-            $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2874
+			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2875
+			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2876 2876
 
2877 2877
 			if (is_array($array_options) && count($array_options)>0) {
2878 2878
 				$this->line->array_options=$array_options;
@@ -2891,7 +2891,7 @@  discard block
 block discarded – undo
2891 2891
 			}
2892 2892
 			else
2893 2893
 			{
2894
-			    $this->error=$this->line->error;
2894
+				$this->error=$this->line->error;
2895 2895
 				$this->db->rollback();
2896 2896
 				return -1;
2897 2897
 			}
@@ -2939,7 +2939,7 @@  discard block
 block discarded – undo
2939 2939
 	 */
2940 2940
 	function update_percent($line, $percent)
2941 2941
 	{
2942
-	    global $mysoc,$user;
2942
+		global $mysoc,$user;
2943 2943
 
2944 2944
 		include_once(DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php');
2945 2945
 
@@ -2965,7 +2965,7 @@  discard block
 block discarded – undo
2965 2965
 	 */
2966 2966
 	function deleteline($rowid)
2967 2967
 	{
2968
-        global $user;
2968
+		global $user;
2969 2969
 
2970 2970
 		dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG);
2971 2971
 
@@ -2993,7 +2993,7 @@  discard block
 block discarded – undo
2993 2993
 
2994 2994
 		$line=new FactureLigne($this->db);
2995 2995
 
2996
-        $line->context = $this->context;
2996
+		$line->context = $this->context;
2997 2997
 
2998 2998
 		// For triggers
2999 2999
 		$result = $line->fetch($rowid);
@@ -3245,8 +3245,8 @@  discard block
 block discarded – undo
3245 3245
 				// Load file with numbering class (if found)
3246 3246
 				if (is_file($dir.$file) && is_readable($dir.$file))
3247 3247
 				{
3248
-                    $mybool |= include_once $dir . $file;
3249
-                }
3248
+					$mybool |= include_once $dir . $file;
3249
+				}
3250 3250
 			}
3251 3251
 
3252 3252
 			// For compatibility
@@ -3262,8 +3262,8 @@  discard block
 block discarded – undo
3262 3262
 
3263 3263
 					// Load file with numbering class (if found)
3264 3264
 					if (is_file($dir.$file) && is_readable($dir.$file)) {
3265
-                        $mybool |= include_once $dir . $file;
3266
-                    }
3265
+						$mybool |= include_once $dir . $file;
3266
+					}
3267 3267
 				}
3268 3268
 			}
3269 3269
 
@@ -3614,11 +3614,11 @@  discard block
 block discarded – undo
3614 3614
 
3615 3615
 		if ($this->statut > self::STATUS_DRAFT && $this->paye == 0)
3616 3616
 		{
3617
-	        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
3618
-	        $bac = new CompanyBankAccount($this->db);
3619
-	        $bac->fetch(0,$this->socid);
3617
+			require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
3618
+			$bac = new CompanyBankAccount($this->db);
3619
+			$bac->fetch(0,$this->socid);
3620 3620
 
3621
-        	$sql = 'SELECT count(*)';
3621
+			$sql = 'SELECT count(*)';
3622 3622
 			$sql.= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
3623 3623
 			$sql.= ' WHERE fk_facture = '.$this->id;
3624 3624
 			$sql.= ' AND traite = 0';
@@ -3632,15 +3632,15 @@  discard block
 block discarded – undo
3632 3632
 				{
3633 3633
 					$now=dol_now();
3634 3634
 
3635
-                    $totalpaye  = $this->getSommePaiement();
3636
-                    $totalcreditnotes = $this->getSumCreditNotesUsed();
3637
-                    $totaldeposits = $this->getSumDepositsUsed();
3638
-                    //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
3635
+					$totalpaye  = $this->getSommePaiement();
3636
+					$totalcreditnotes = $this->getSumCreditNotesUsed();
3637
+					$totaldeposits = $this->getSumDepositsUsed();
3638
+					//print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
3639 3639
 
3640
-                    // We can also use bcadd to avoid pb with floating points
3641
-                    // For example print 239.2 - 229.3 - 9.9; does not return 0.
3642
-                    //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
3643
-                    //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3640
+					// We can also use bcadd to avoid pb with floating points
3641
+					// For example print 239.2 - 229.3 - 9.9; does not return 0.
3642
+					//$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
3643
+					//$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3644 3644
 					if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
3645 3645
 
3646 3646
 					if (is_numeric($amount) && $amount != 0)
@@ -3660,52 +3660,52 @@  discard block
 block discarded – undo
3660 3660
 						$resql=$this->db->query($sql);
3661 3661
 						if (! $resql)
3662 3662
 						{
3663
-						    $this->error=$this->db->lasterror();
3664
-						    dol_syslog(get_class($this).'::demandeprelevement Erreur');
3665
-						    $error++;
3663
+							$this->error=$this->db->lasterror();
3664
+							dol_syslog(get_class($this).'::demandeprelevement Erreur');
3665
+							$error++;
3666 3666
 						}
3667 3667
 					}
3668 3668
 					else
3669 3669
 					{
3670 3670
 						$this->error='WithdrawRequestErrorNilAmount';
3671
-	                    dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
3672
-	                    $error++;
3671
+						dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
3672
+						$error++;
3673
+					}
3674
+
3675
+					if (! $error)
3676
+					{
3677
+						// Force payment mode of invoice to withdraw
3678
+						$payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1);
3679
+						if ($payment_mode_id > 0)
3680
+						{
3681
+							$result=$this->setPaymentMethods($payment_mode_id);
3682
+						}
3673 3683
 					}
3674 3684
 
3675
-        			if (! $error)
3676
-        			{
3677
-        				// Force payment mode of invoice to withdraw
3678
-        				$payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1);
3679
-        				if ($payment_mode_id > 0)
3680
-        				{
3681
-        					$result=$this->setPaymentMethods($payment_mode_id);
3682
-        				}
3683
-        			}
3684
-
3685
-                    if ($error) return -1;
3686
-                    return 1;
3687
-                }
3688
-                else
3689
-                {
3690
-                    $this->error="A request already exists";
3691
-                    dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
3692
-                    return 0;
3693
-                }
3694
-            }
3695
-            else
3696
-            {
3697
-                $this->error=$this->db->error();
3698
-                dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
3699
-                return -2;
3700
-            }
3701
-        }
3702
-        else
3703
-        {
3704
-            $this->error="Status of invoice does not allow this";
3705
-            dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
3706
-            return -3;
3707
-        }
3708
-    }
3685
+					if ($error) return -1;
3686
+					return 1;
3687
+				}
3688
+				else
3689
+				{
3690
+					$this->error="A request already exists";
3691
+					dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
3692
+					return 0;
3693
+				}
3694
+			}
3695
+			else
3696
+			{
3697
+				$this->error=$this->db->error();
3698
+				dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
3699
+				return -2;
3700
+			}
3701
+		}
3702
+		else
3703
+		{
3704
+			$this->error="Status of invoice does not allow this";
3705
+			dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
3706
+			return -3;
3707
+		}
3708
+	}
3709 3709
 
3710 3710
 	/**
3711 3711
 	 *  Supprime une demande de prelevement
@@ -3833,7 +3833,7 @@  discard block
 block discarded – undo
3833 3833
 		$arraynow=dol_getdate($now);
3834 3834
 		$nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
3835 3835
 
3836
-        // Load array of products prodids
3836
+		// Load array of products prodids
3837 3837
 		$num_prods = 0;
3838 3838
 		$prodids = array();
3839 3839
 		$sql = "SELECT rowid";
@@ -4006,7 +4006,7 @@  discard block
 block discarded – undo
4006 4006
 			{
4007 4007
 				$this->nb["invoices"]=$obj->nb;
4008 4008
 			}
4009
-            $this->db->free($resql);
4009
+			$this->db->free($resql);
4010 4010
 			return 1;
4011 4011
 		}
4012 4012
 		else
@@ -4024,7 +4024,7 @@  discard block
 block discarded – undo
4024 4024
 	 */
4025 4025
 	function getLinesArray()
4026 4026
 	{
4027
-	    return $this->fetch_lines();
4027
+		return $this->fetch_lines();
4028 4028
 	}
4029 4029
 
4030 4030
 	/**
@@ -4247,8 +4247,8 @@  discard block
 block discarded – undo
4247 4247
  */
4248 4248
 class FactureLigne extends CommonInvoiceLine
4249 4249
 {
4250
-    public $element='facturedet';
4251
-    public $table_element='facturedet';
4250
+	public $element='facturedet';
4251
+	public $table_element='facturedet';
4252 4252
 
4253 4253
 	var $oldline;
4254 4254
 
@@ -4410,7 +4410,7 @@  discard block
 block discarded – undo
4410 4410
 		}
4411 4411
 		else
4412 4412
 		{
4413
-		    $this->error = $this->db->lasterror();
4413
+			$this->error = $this->db->lasterror();
4414 4414
 			return -1;
4415 4415
 		}
4416 4416
 	}
@@ -4428,9 +4428,9 @@  discard block
 block discarded – undo
4428 4428
 
4429 4429
 		$error=0;
4430 4430
 
4431
-        $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4431
+		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4432 4432
 
4433
-        dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
4433
+		dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
4434 4434
 
4435 4435
 		// Clean parameters
4436 4436
 		$this->desc=trim($this->desc);
@@ -4505,7 +4505,7 @@  discard block
 block discarded – undo
4505 4505
 		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4506 4506
 		$sql.= " '".$this->db->escape($this->desc)."',";
4507 4507
 		$sql.= " ".price2num($this->qty).",";
4508
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4508
+		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4509 4509
 		$sql.= " ".price2num($this->tva_tx).",";
4510 4510
 		$sql.= " ".price2num($this->localtax1_tx).",";
4511 4511
 		$sql.= " ".price2num($this->localtax2_tx).",";
@@ -4548,15 +4548,15 @@  discard block
 block discarded – undo
4548 4548
 		{
4549 4549
 			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
4550 4550
 
4551
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4552
-            {
4553
-            	$this->id=$this->rowid;
4554
-            	$result=$this->insertExtraFields();
4555
-            	if ($result < 0)
4556
-            	{
4557
-            		$error++;
4558
-            	}
4559
-            }
4551
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4552
+			{
4553
+				$this->id=$this->rowid;
4554
+				$result=$this->insertExtraFields();
4555
+				if ($result < 0)
4556
+				{
4557
+					$error++;
4558
+				}
4559
+			}
4560 4560
 
4561 4561
 			// Si fk_remise_except defini, on lie la remise a la facture
4562 4562
 			// ce qui la flague comme "consommee".
@@ -4569,16 +4569,16 @@  discard block
 block discarded – undo
4569 4569
 					// Check if discount was found
4570 4570
 					if ($result > 0)
4571 4571
 					{
4572
-					    // Check if discount not already affected to another invoice
4572
+						// Check if discount not already affected to another invoice
4573 4573
 						if ($discount->fk_facture_line > 0)
4574 4574
 						{
4575
-						    if (empty($noerrorifdiscountalreadylinked))
4576
-						    {
4577
-    							$this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
4578
-    							dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4579
-    							$this->db->rollback();
4580
-    							return -3;
4581
-						    }
4575
+							if (empty($noerrorifdiscountalreadylinked))
4576
+							{
4577
+								$this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
4578
+								dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4579
+								$this->db->rollback();
4580
+								return -3;
4581
+							}
4582 4582
 						}
4583 4583
 						else
4584 4584
 						{
@@ -4611,14 +4611,14 @@  discard block
 block discarded – undo
4611 4611
 
4612 4612
 			if (! $notrigger)
4613 4613
 			{
4614
-                // Call trigger
4615
-                $result=$this->call_trigger('LINEBILL_INSERT',$user);
4616
-                if ($result < 0)
4617
-                {
4614
+				// Call trigger
4615
+				$result=$this->call_trigger('LINEBILL_INSERT',$user);
4616
+				if ($result < 0)
4617
+				{
4618 4618
 					$this->db->rollback();
4619 4619
 					return -2;
4620 4620
 				}
4621
-                // End call triggers
4621
+				// End call triggers
4622 4622
 			}
4623 4623
 
4624 4624
 			$this->db->commit();
@@ -4688,34 +4688,34 @@  discard block
 block discarded – undo
4688 4688
 
4689 4689
 		$this->db->begin();
4690 4690
 
4691
-        // Mise a jour ligne en base
4692
-        $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
4693
-        $sql.= " description='".$this->db->escape($this->desc)."'";
4694
-        $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4695
-        $sql.= ", subprice=".price2num($this->subprice)."";
4696
-        $sql.= ", remise_percent=".price2num($this->remise_percent)."";
4697
-        if ($this->fk_remise_except) $sql.= ", fk_remise_except=".$this->fk_remise_except;
4698
-        else $sql.= ", fk_remise_except=null";
4691
+		// Mise a jour ligne en base
4692
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
4693
+		$sql.= " description='".$this->db->escape($this->desc)."'";
4694
+		$sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4695
+		$sql.= ", subprice=".price2num($this->subprice)."";
4696
+		$sql.= ", remise_percent=".price2num($this->remise_percent)."";
4697
+		if ($this->fk_remise_except) $sql.= ", fk_remise_except=".$this->fk_remise_except;
4698
+		else $sql.= ", fk_remise_except=null";
4699 4699
 		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->db->escape($this->vat_src_code))."'";
4700
-        $sql.= ", tva_tx=".price2num($this->tva_tx)."";
4701
-        $sql.= ", localtax1_tx=".price2num($this->localtax1_tx)."";
4702
-        $sql.= ", localtax2_tx=".price2num($this->localtax2_tx)."";
4700
+		$sql.= ", tva_tx=".price2num($this->tva_tx)."";
4701
+		$sql.= ", localtax1_tx=".price2num($this->localtax1_tx)."";
4702
+		$sql.= ", localtax2_tx=".price2num($this->localtax2_tx)."";
4703 4703
 		$sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4704 4704
 		$sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4705
-        $sql.= ", qty=".price2num($this->qty);
4706
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4707
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4708
-        $sql.= ", product_type=".$this->product_type;
4709
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
4710
-        $sql.= ", special_code='".$this->db->escape($this->special_code)."'";
4711
-        if (empty($this->skip_update_total))
4712
-        {
4713
-        	$sql.= ", total_ht=".price2num($this->total_ht)."";
4714
-        	$sql.= ", total_tva=".price2num($this->total_tva)."";
4715
-        	$sql.= ", total_ttc=".price2num($this->total_ttc)."";
4716
-        	$sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
4717
-        	$sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
4718
-        }
4705
+		$sql.= ", qty=".price2num($this->qty);
4706
+		$sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4707
+		$sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4708
+		$sql.= ", product_type=".$this->product_type;
4709
+		$sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
4710
+		$sql.= ", special_code='".$this->db->escape($this->special_code)."'";
4711
+		if (empty($this->skip_update_total))
4712
+		{
4713
+			$sql.= ", total_ht=".price2num($this->total_ht)."";
4714
+			$sql.= ", total_tva=".price2num($this->total_tva)."";
4715
+			$sql.= ", total_ttc=".price2num($this->total_ttc)."";
4716
+			$sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
4717
+			$sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
4718
+		}
4719 4719
 		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
4720 4720
 		$sql.= ", buy_price_ht='".price2num($this->pa_ht)."'";
4721 4721
 		$sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
@@ -4726,9 +4726,9 @@  discard block
 block discarded – undo
4726 4726
 
4727 4727
 		// Multicurrency
4728 4728
 		$sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4729
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4730
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4731
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4729
+		$sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4730
+		$sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4731
+		$sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4732 4732
 
4733 4733
 		$sql.= " WHERE rowid = ".$this->rowid;
4734 4734
 
@@ -4736,26 +4736,26 @@  discard block
 block discarded – undo
4736 4736
 		$resql=$this->db->query($sql);
4737 4737
 		if ($resql)
4738 4738
 		{
4739
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4740
-        	{
4741
-        		$this->id=$this->rowid;
4742
-        		$result=$this->insertExtraFields();
4743
-        		if ($result < 0)
4744
-        		{
4745
-        			$error++;
4746
-        		}
4747
-        	}
4739
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4740
+			{
4741
+				$this->id=$this->rowid;
4742
+				$result=$this->insertExtraFields();
4743
+				if ($result < 0)
4744
+				{
4745
+					$error++;
4746
+				}
4747
+			}
4748 4748
 
4749 4749
 			if (! $notrigger)
4750 4750
 			{
4751
-                // Call trigger
4752
-                $result=$this->call_trigger('LINEBILL_UPDATE',$user);
4753
-                if ($result < 0)
4751
+				// Call trigger
4752
+				$result=$this->call_trigger('LINEBILL_UPDATE',$user);
4753
+				if ($result < 0)
4754 4754
  				{
4755 4755
 					$this->db->rollback();
4756 4756
 					return -2;
4757 4757
 				}
4758
-                // End call triggers
4758
+				// End call triggers
4759 4759
 			}
4760 4760
 			$this->db->commit();
4761 4761
 			return 1;
@@ -4771,7 +4771,7 @@  discard block
 block discarded – undo
4771 4771
 	/**
4772 4772
 	 * 	Delete line in database
4773 4773
 	 *  TODO Add param User $user and notrigger (see skeleton)
4774
-     *
4774
+	 *
4775 4775
 	 *	@return	    int		           <0 if KO, >0 if OK
4776 4776
 	 */
4777 4777
 	function delete()
@@ -4856,10 +4856,10 @@  discard block
 block discarded – undo
4856 4856
 		if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
4857 4857
 			return 0;
4858 4858
 		} else {
4859
-		    // If invoice is a not a situation invoice, this->fk_prev_id is used for something else
4860
-            $tmpinvoice=new Facture($this->db);
4861
-            $tmpinvoice->fetch($invoiceid);
4862
-            if ($tmpinvoice->type != Facture::TYPE_SITUATION) return 0;
4859
+			// If invoice is a not a situation invoice, this->fk_prev_id is used for something else
4860
+			$tmpinvoice=new Facture($this->db);
4861
+			$tmpinvoice->fetch($invoiceid);
4862
+			if ($tmpinvoice->type != Facture::TYPE_SITUATION) return 0;
4863 4863
 
4864 4864
 			$sql = 'SELECT situation_percent FROM ' . MAIN_DB_PREFIX . 'facturedet WHERE rowid=' . $this->fk_prev_id;
4865 4865
 			$resql = $this->db->query($sql);
Please login to merge, or discard this patch.
Spacing   +1202 added lines, -1202 removed lines patch added patch discarded remove patch
@@ -48,12 +48,12 @@  discard block
 block discarded – undo
48 48
  */
49 49
 class Facture extends CommonInvoice
50 50
 {
51
-	public $element='facture';
52
-	public $table_element='facture';
51
+	public $element = 'facture';
52
+	public $table_element = 'facture';
53 53
 	public $table_element_line = 'facturedet';
54 54
 	public $fk_element = 'fk_facture';
55
-	protected $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
56
-	public $picto='bill';
55
+	protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
56
+	public $picto = 'bill';
57 57
 
58 58
 	/**
59 59
 	 * {@inheritdoc}
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 	public $author;
66 66
 	public $fk_user_author;
67 67
 	public $fk_user_valid;
68
-	public $date;              // Date invoice
69
-	public $date_creation;		// Creation date
70
-	public $date_validation;	// Validation date
68
+	public $date; // Date invoice
69
+	public $date_creation; // Creation date
70
+	public $date_validation; // Validation date
71 71
 	public $datem;
72 72
 	public $ref_client;
73 73
 	public $ref_int;
@@ -77,9 +77,9 @@  discard block
 block discarded – undo
77 77
 	//var $amount;
78 78
 	public $remise_absolue;
79 79
 	public $remise_percent;
80
-	public $total_ht=0;
81
-	public $total_tva=0;
82
-	public $total_ttc=0;
80
+	public $total_ht = 0;
81
+	public $total_tva = 0;
82
+	public $total_ttc = 0;
83 83
 	public $revenuestamp;
84 84
 
85 85
 	//! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon
@@ -91,21 +91,21 @@  discard block
 block discarded – undo
91 91
 	public $paye;
92 92
 	//! id of source invoice if replacement invoice or credit note
93 93
 	public $fk_facture_source;
94
-	public $linked_objects=array();
94
+	public $linked_objects = array();
95 95
 	public $date_lim_reglement;
96
-	public $cond_reglement_code;		// Code in llx_c_paiement
97
-	public $mode_reglement_code;		// Code in llx_c_paiement
98
-	public $fk_bank;					// Field to store bank id to use when payment mode is withdraw
96
+	public $cond_reglement_code; // Code in llx_c_paiement
97
+	public $mode_reglement_code; // Code in llx_c_paiement
98
+	public $fk_bank; // Field to store bank id to use when payment mode is withdraw
99 99
 	/**
100 100
 	 * @deprecated
101 101
 	 */
102
-	public $products=array();
102
+	public $products = array();
103 103
 	/**
104 104
 	 * @var FactureLigne[]
105 105
 	 */
106
-	public $lines=array();
106
+	public $lines = array();
107 107
 	public $line;
108
-	public $extraparams=array();
108
+	public $extraparams = array();
109 109
 	public $specimen;
110 110
 
111 111
 	public $fac_rec;
@@ -136,12 +136,12 @@  discard block
 block discarded – undo
136 136
 	/**
137 137
 	 * @var array Table of previous situations
138 138
 	 */
139
-	public $tab_previous_situation_invoice=array();
139
+	public $tab_previous_situation_invoice = array();
140 140
 
141 141
 	/**
142 142
 	 * @var array Table of next situations
143 143
 	 */
144
-	public $tab_next_situation_invoice=array();
144
+	public $tab_next_situation_invoice = array();
145 145
 
146 146
 	public $oldcopy;
147 147
 
@@ -228,24 +228,24 @@  discard block
 block discarded – undo
228 228
 	 * 	@param	int		$forceduedate	1=Do not recalculate due date from payment condition but force it with value
229 229
 	 *	@return	int						<0 if KO, >0 if OK
230 230
 	 */
231
-	function create($user,$notrigger=0,$forceduedate=0)
231
+	function create($user, $notrigger = 0, $forceduedate = 0)
232 232
 	{
233
-		global $langs,$conf,$mysoc,$hookmanager;
234
-		$error=0;
233
+		global $langs, $conf, $mysoc, $hookmanager;
234
+		$error = 0;
235 235
 
236 236
 		// Clean parameters
237 237
 		if (empty($this->type)) $this->type = self::TYPE_STANDARD;
238
-		$this->ref_client=trim($this->ref_client);
239
-		$this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
240
-		$this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
241
-		$this->note_public=trim($this->note_public);
242
-		if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
243
-		if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
238
+		$this->ref_client = trim($this->ref_client);
239
+		$this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
240
+		$this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
241
+		$this->note_public = trim($this->note_public);
242
+		if (!$this->cond_reglement_id) $this->cond_reglement_id = 0;
243
+		if (!$this->mode_reglement_id) $this->mode_reglement_id = 0;
244 244
 		$this->brouillon = 1;
245 245
         if (empty($this->entity)) $this->entity = $conf->entity;
246 246
 
247 247
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
248
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
248
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
249 249
 		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
250 250
 		if (empty($this->fk_multicurrency))
251 251
 		{
@@ -259,20 +259,20 @@  discard block
 block discarded – undo
259 259
 		// Check parameters
260 260
 		if (empty($this->date) || empty($user->id))
261 261
 		{
262
-			$this->error="ErrorBadParameter";
262
+			$this->error = "ErrorBadParameter";
263 263
 			dol_syslog(get_class($this)."::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR);
264 264
 			return -3;
265 265
 		}
266 266
 		$soc = new Societe($this->db);
267
-		$result=$soc->fetch($this->socid);
267
+		$result = $soc->fetch($this->socid);
268 268
 		if ($result < 0)
269 269
 		{
270
-			$this->error="Failed to fetch company: ".$soc->error;
270
+			$this->error = "Failed to fetch company: ".$soc->error;
271 271
 			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
272 272
 			return -2;
273 273
 		}
274 274
 
275
-		$now=dol_now();
275
+		$now = dol_now();
276 276
 
277 277
 		$this->db->begin();
278 278
 
@@ -283,18 +283,18 @@  discard block
 block discarded – undo
283 283
 
284 284
 			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
285 285
 			$_facrec = new FactureRec($this->db);
286
-			$result=$_facrec->fetch($this->fac_rec);
287
-			$result=$_facrec->fetchObjectLinked();       // This load $_facrec->linkedObjectsIds
286
+			$result = $_facrec->fetch($this->fac_rec);
287
+			$result = $_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds
288 288
 
289 289
 			$originaldatewhen = $_facrec->date_when;
290 290
 
291
-			$this->socid 		     = $_facrec->socid;  // Invoice created on same thirdparty than template
291
+			$this->socid = $_facrec->socid; // Invoice created on same thirdparty than template
292 292
 			$this->entity            = $_facrec->entity; // Invoice created in same entity than template
293 293
 
294 294
 			// Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI
295
-			$this->fk_project        = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project;
296
-			$this->note_public       = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public;
297
-			$this->note_private      = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private;
295
+			$this->fk_project        = GETPOST('projectid', 'int') > 0 ? GETPOST('projectid', 'int') : $_facrec->fk_project;
296
+			$this->note_public       = GETPOST('note_public', 'none') ? GETPOST('note_public', 'none') : $_facrec->note_public;
297
+			$this->note_private      = GETPOST('note_private', 'none') ? GETPOST('note_private', 'none') : $_facrec->note_private;
298 298
 			$this->modelpdf          = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf;
299 299
 			$this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id;
300 300
 			$this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id;
@@ -307,20 +307,20 @@  discard block
 block discarded – undo
307 307
 			// Fields always coming from template
308 308
 			$this->remise_absolue    = $_facrec->remise_absolue;
309 309
 			$this->remise_percent    = $_facrec->remise_percent;
310
-			$this->fk_incoterms		 = $_facrec->fk_incoterms;
311
-			$this->location_incoterms= $_facrec->location_incoterms;
310
+			$this->fk_incoterms = $_facrec->fk_incoterms;
311
+			$this->location_incoterms = $_facrec->location_incoterms;
312 312
 
313 313
 			// Clean parameters
314
-			if (! $this->type) $this->type = self::TYPE_STANDARD;
315
-			$this->ref_client=trim($this->ref_client);
316
-			$this->note_public=trim($this->note_public);
317
-			$this->note_private=trim($this->note_private);
318
-		    $this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
314
+			if (!$this->type) $this->type = self::TYPE_STANDARD;
315
+			$this->ref_client = trim($this->ref_client);
316
+			$this->note_public = trim($this->note_public);
317
+			$this->note_private = trim($this->note_private);
318
+		    $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
319 319
 
320
-		    $this->array_options=$_facrec->array_options;
320
+		    $this->array_options = $_facrec->array_options;
321 321
 
322 322
 			//if (! $this->remise) $this->remise = 0;
323
-			if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
323
+			if (!$this->mode_reglement_id) $this->mode_reglement_id = 0;
324 324
 			$this->brouillon = 1;
325 325
 
326 326
 			$this->linked_objects = $_facrec->linkedObjectsIds;
@@ -332,26 +332,26 @@  discard block
 block discarded – undo
332 332
 			{
333 333
 			    dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
334 334
 			    if (empty($_facrec->date_when)) $_facrec->date_when = $now;
335
-                $next_date = $_facrec->getNextDate();   // Calculate next date
335
+                $next_date = $_facrec->getNextDate(); // Calculate next date
336 336
                 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
337 337
                 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1);		// Not required, +1 already included into setNextDate when second param is 1.
338
-                $result = $_facrec->setNextDate($next_date,1);
338
+                $result = $_facrec->setNextDate($next_date, 1);
339 339
 			}
340 340
 
341 341
 			// Define lang of customer
342 342
 			$outputlangs = $langs;
343
-			$newlang='';
343
+			$newlang = '';
344 344
 
345
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) $newlang=$this->thirdparty->default_lang;  // for proposal, order, invoice, ...
346
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang=$this->default_lang;                  // for thirdparty
347
-			if (! empty($newlang))
345
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
346
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty
347
+			if (!empty($newlang))
348 348
 			{
349
-			    $outputlangs = new Translate("",$conf);
349
+			    $outputlangs = new Translate("", $conf);
350 350
 			    $outputlangs->setDefaultLang($newlang);
351 351
 			}
352 352
 
353 353
 			// Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
354
-			$substitutionarray=array(
354
+			$substitutionarray = array(
355 355
 			    '__TOTAL_HT__' => price($this->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
356 356
 			    '__TOTAL_TTC__' => price($this->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code),
357 357
 			    '__INVOICE_PREVIOUS_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'),
@@ -370,98 +370,98 @@  discard block
 block discarded – undo
370 370
 
371 371
 			//var_dump($substitutionarray);exit;
372 372
 
373
-			$substitutionisok=true;
373
+			$substitutionisok = true;
374 374
 			complete_substitutions_array($substitutionarray, $outputlangs);
375 375
 
376
-			$this->note_public=make_substitutions($this->note_public,$substitutionarray);
377
-			$this->note_private=make_substitutions($this->note_private,$substitutionarray);
376
+			$this->note_public = make_substitutions($this->note_public, $substitutionarray);
377
+			$this->note_private = make_substitutions($this->note_private, $substitutionarray);
378 378
 		}
379 379
 
380 380
 		// Define due date if not already defined
381
-		$datelim=(empty($forceduedate)?$this->calculate_date_lim_reglement():$forceduedate);
381
+		$datelim = (empty($forceduedate) ? $this->calculate_date_lim_reglement() : $forceduedate);
382 382
 
383 383
 		// Insert into database
384 384
 		$socid  = $this->socid;
385 385
 
386 386
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
387
-		$sql.= " facnumber";
388
-		$sql.= ", entity";
389
-		$sql.= ", ref_ext";
390
-		$sql.= ", type";
391
-		$sql.= ", fk_soc";
392
-		$sql.= ", datec";
393
-		$sql.= ", remise_absolue";
394
-		$sql.= ", remise_percent";
395
-		$sql.= ", datef";
396
-		$sql.= ", date_pointoftax";
397
-		$sql.= ", note_private";
398
-		$sql.= ", note_public";
399
-		$sql.= ", ref_client, ref_int";
400
-        $sql.= ", fk_account";
401
-		$sql.= ", fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
402
-		$sql.= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
403
-		$sql.= ", situation_cycle_ref, situation_counter, situation_final";
404
-		$sql.= ", fk_incoterms, location_incoterms";
405
-        $sql.= ", fk_multicurrency";
406
-        $sql.= ", multicurrency_code";
407
-        $sql.= ", multicurrency_tx";
408
-		$sql.= ")";
409
-		$sql.= " VALUES (";
410
-		$sql.= "'(PROV)'";
411
-		$sql.= ", ".$this->entity;
412
-		$sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
413
-		$sql.= ", '".$this->db->escape($this->type)."'";
414
-		$sql.= ", '".$socid."'";
415
-		$sql.= ", '".$this->db->idate($now)."'";
416
-		$sql.= ", ".($this->remise_absolue>0?$this->remise_absolue:'NULL');
417
-		$sql.= ", ".($this->remise_percent>0?$this->remise_percent:'NULL');
418
-		$sql.= ", '".$this->db->idate($this->date)."'";
419
-		$sql.= ", ".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null');
420
-		$sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
421
-		$sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
422
-		$sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
423
-		$sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
424
-		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
425
-		$sql.= ", ".($this->fk_fac_rec_source?"'".$this->db->escape($this->fk_fac_rec_source)."'":"null");
426
-		$sql.= ", ".($this->fk_facture_source?"'".$this->db->escape($this->fk_facture_source)."'":"null");
427
-		$sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null");
428
-		$sql.= ", ".($this->fk_project?$this->fk_project:"null");
429
-		$sql.= ", ".$this->cond_reglement_id;
430
-		$sql.= ", ".$this->mode_reglement_id;
431
-		$sql.= ", '".$this->db->idate($datelim)."', '".$this->db->escape($this->modelpdf)."'";
432
-		$sql.= ", ".($this->situation_cycle_ref?"'".$this->db->escape($this->situation_cycle_ref)."'":"null");
433
-		$sql.= ", ".($this->situation_counter?"'".$this->db->escape($this->situation_counter)."'":"null");
434
-		$sql.= ", ".($this->situation_final?$this->situation_final:0);
435
-		$sql.= ", ".(int) $this->fk_incoterms;
436
-        $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
437
-		$sql.= ", ".(int) $this->fk_multicurrency;
438
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
439
-		$sql.= ", ".(double) $this->multicurrency_tx;
440
-		$sql.=")";
441
-
442
-		$resql=$this->db->query($sql);
387
+		$sql .= " facnumber";
388
+		$sql .= ", entity";
389
+		$sql .= ", ref_ext";
390
+		$sql .= ", type";
391
+		$sql .= ", fk_soc";
392
+		$sql .= ", datec";
393
+		$sql .= ", remise_absolue";
394
+		$sql .= ", remise_percent";
395
+		$sql .= ", datef";
396
+		$sql .= ", date_pointoftax";
397
+		$sql .= ", note_private";
398
+		$sql .= ", note_public";
399
+		$sql .= ", ref_client, ref_int";
400
+        $sql .= ", fk_account";
401
+		$sql .= ", fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
402
+		$sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
403
+		$sql .= ", situation_cycle_ref, situation_counter, situation_final";
404
+		$sql .= ", fk_incoterms, location_incoterms";
405
+        $sql .= ", fk_multicurrency";
406
+        $sql .= ", multicurrency_code";
407
+        $sql .= ", multicurrency_tx";
408
+		$sql .= ")";
409
+		$sql .= " VALUES (";
410
+		$sql .= "'(PROV)'";
411
+		$sql .= ", ".$this->entity;
412
+		$sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
413
+		$sql .= ", '".$this->db->escape($this->type)."'";
414
+		$sql .= ", '".$socid."'";
415
+		$sql .= ", '".$this->db->idate($now)."'";
416
+		$sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
417
+		$sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
418
+		$sql .= ", '".$this->db->idate($this->date)."'";
419
+		$sql .= ", ".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null');
420
+		$sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
421
+		$sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
422
+		$sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
423
+		$sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
424
+		$sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
425
+		$sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
426
+		$sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
427
+		$sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null");
428
+		$sql .= ", ".($this->fk_project ? $this->fk_project : "null");
429
+		$sql .= ", ".$this->cond_reglement_id;
430
+		$sql .= ", ".$this->mode_reglement_id;
431
+		$sql .= ", '".$this->db->idate($datelim)."', '".$this->db->escape($this->modelpdf)."'";
432
+		$sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
433
+		$sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
434
+		$sql .= ", ".($this->situation_final ? $this->situation_final : 0);
435
+		$sql .= ", ".(int) $this->fk_incoterms;
436
+        $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
437
+		$sql .= ", ".(int) $this->fk_multicurrency;
438
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
439
+		$sql .= ", ".(double) $this->multicurrency_tx;
440
+		$sql .= ")";
441
+
442
+		$resql = $this->db->query($sql);
443 443
 		if ($resql)
444 444
 		{
445 445
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
446 446
 
447 447
 			// Update ref with new one
448
-			$this->ref='(PROV'.$this->id.')';
448
+			$this->ref = '(PROV'.$this->id.')';
449 449
 			$sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET facnumber='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
450 450
 
451
-			$resql=$this->db->query($sql);
452
-			if (! $resql) $error++;
451
+			$resql = $this->db->query($sql);
452
+			if (!$resql) $error++;
453 453
 
454 454
 			// Add object linked
455
-			if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
455
+			if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects))
456 456
 			{
457
-				foreach($this->linked_objects as $origin => $tmp_origin_id)
457
+				foreach ($this->linked_objects as $origin => $tmp_origin_id)
458 458
 				{
459 459
 				    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
460 460
 				    {
461
-				        foreach($tmp_origin_id as $origin_id)
461
+				        foreach ($tmp_origin_id as $origin_id)
462 462
 				        {
463 463
 				            $ret = $this->add_object_linked($origin, $origin_id);
464
-				            if (! $ret)
464
+				            if (!$ret)
465 465
 				            {
466 466
 				                dol_print_error($this->db);
467 467
 				                $error++;
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 				    {
473 473
 				        $origin_id = $tmp_origin_id;
474 474
     					$ret = $this->add_object_linked($origin, $origin_id);
475
-    					if (! $ret)
475
+    					if (!$ret)
476 476
     					{
477 477
     						dol_print_error($this->db);
478 478
     						$error++;
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
 				}
482 482
 			}
483 483
 
484
-			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
484
+			if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id))   // Get contact from origin object
485 485
 			{
486 486
 				$originforcontact = $this->origin;
487 487
 				$originidforcontact = $this->origin_id;
488 488
 				if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
489 489
 				{
490
-				    require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
490
+				    require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
491 491
 				    $exp = new Expedition($this->db);
492 492
 				    $exp->fetch($this->origin_id);
493 493
 				    $exp->fetchObjectLinked();
@@ -504,15 +504,15 @@  discard block
 block discarded – undo
504 504
 				}
505 505
 
506 506
 				$sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
507
-				$sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
507
+				$sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
508 508
 
509 509
 				$resqlcontact = $this->db->query($sqlcontact);
510 510
 				if ($resqlcontact)
511 511
 				{
512
-				    while($objcontact = $this->db->fetch_object($resqlcontact))
512
+				    while ($objcontact = $this->db->fetch_object($resqlcontact))
513 513
 				    {
514 514
 				        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
515
-				        $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
515
+				        $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
516 516
 				    }
517 517
 				}
518 518
 				else dol_print_error($resqlcontact);
@@ -528,8 +528,8 @@  discard block
 block discarded – undo
528 528
 				dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
529 529
 				foreach ($this->lines as $i => $val)
530 530
 				{
531
-					$newinvoiceline=$this->lines[$i];
532
-					$newinvoiceline->fk_facture=$this->id;
531
+					$newinvoiceline = $this->lines[$i];
532
+					$newinvoiceline->fk_facture = $this->id;
533 533
 
534 534
 					// TODO This seems not used. Here we put origin 'facture' but after,  we put an id of object !
535 535
 					$newinvoiceline->origin = $this->element;
@@ -542,8 +542,8 @@  discard block
 block discarded – undo
542 542
 							$fk_parent_line = 0;
543 543
 						}
544 544
 
545
-						$newinvoiceline->fk_parent_line=$fk_parent_line;
546
-						$result=$newinvoiceline->insert();
545
+						$newinvoiceline->fk_parent_line = $fk_parent_line;
546
+						$result = $newinvoiceline->insert();
547 547
 
548 548
 						// Defined the new fk_parent_line
549 549
 						if ($result > 0 && $newinvoiceline->product_type == 9) {
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
 					}
553 553
 					if ($result < 0)
554 554
 					{
555
-						$this->error=$newinvoiceline->error;
555
+						$this->error = $newinvoiceline->error;
556 556
 						$error++;
557 557
 						break;
558 558
 					}
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 
571 571
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
572 572
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
573
-                	if (! is_object($line)) $line = (object) $line;
573
+                	if (!is_object($line)) $line = (object) $line;
574 574
 
575 575
 				    if ($result >= 0)
576 576
 					{
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 						);
612 612
 						if ($result < 0)
613 613
 						{
614
-							$this->error=$this->db->lasterror();
614
+							$this->error = $this->db->lasterror();
615 615
 							dol_print_error($this->db);
616 616
 							$this->db->rollback();
617 617
 							return -1;
@@ -628,20 +628,20 @@  discard block
 block discarded – undo
628 628
 			/*
629 629
 			 * Insert lines of predefined invoices
630 630
 			 */
631
-			if (! $error && $this->fac_rec > 0)
631
+			if (!$error && $this->fac_rec > 0)
632 632
 			{
633 633
 				foreach ($_facrec->lines as $i => $val)
634 634
 				{
635 635
 					if ($_facrec->lines[$i]->fk_product)
636 636
 					{
637 637
 						$prod = new Product($this->db);
638
-						$res=$prod->fetch($_facrec->lines[$i]->fk_product);
638
+						$res = $prod->fetch($_facrec->lines[$i]->fk_product);
639 639
 					}
640
-					$tva_tx = get_default_tva($mysoc,$soc,$prod->id);
641
-					$tva_npr = get_default_npr($mysoc,$soc,$prod->id);
642
-					if (empty($tva_tx)) $tva_npr=0;
643
-					$localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
644
-					$localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
640
+					$tva_tx = get_default_tva($mysoc, $soc, $prod->id);
641
+					$tva_npr = get_default_npr($mysoc, $soc, $prod->id);
642
+					if (empty($tva_tx)) $tva_npr = 0;
643
+					$localtax1_tx = get_localtax($tva_tx, 1, $soc, $mysoc, $tva_npr);
644
+					$localtax2_tx = get_localtax($tva_tx, 2, $soc, $mysoc, $tva_npr);
645 645
 
646 646
 					$result_insert = $this->addline(
647 647
 						$_facrec->lines[$i]->desc,
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 						$localtax2_tx,
653 653
 						$_facrec->lines[$i]->fk_product,
654 654
 						$_facrec->lines[$i]->remise_percent,
655
-						'','',0,$tva_npr,'','HT',0,
655
+						'', '', 0, $tva_npr, '', 'HT', 0,
656 656
 						$_facrec->lines[$i]->product_type,
657 657
 						$_facrec->lines[$i]->rang,
658 658
 						$_facrec->lines[$i]->special_code,
@@ -662,28 +662,28 @@  discard block
 block discarded – undo
662 662
 						null,
663 663
 						0,
664 664
 						$_facrec->lines[$i]->label,
665
-						empty($_facrec->lines[$i]->array_options)?null:$_facrec->lines[$i]->array_options,
665
+						empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
666 666
 						$_facrec->lines[$i]->situation_percent,
667 667
 						'',
668 668
 						$_facrec->lines[$i]->fk_unit
669 669
 					);
670 670
 
671
-					if ( $result_insert < 0)
671
+					if ($result_insert < 0)
672 672
 					{
673 673
 						$error++;
674
-						$this->error=$this->db->error();
674
+						$this->error = $this->db->error();
675 675
 						break;
676 676
 					}
677 677
 				}
678 678
 			}
679 679
 
680
-			if (! $error)
680
+			if (!$error)
681 681
 			{
682 682
 
683
-				$result=$this->update_price(1);
683
+				$result = $this->update_price(1);
684 684
 				if ($result > 0)
685 685
 				{
686
-					$action='create';
686
+					$action = 'create';
687 687
 
688 688
 					// Actions on extra fields (by external module or standard code)
689 689
 					// TODO le hook fait double emploi avec le trigger !!
@@ -695,9 +695,9 @@  discard block
 block discarded – undo
695 695
 					{
696 696
 						if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
697 697
 						{*/
698
-					if (! $error)
698
+					if (!$error)
699 699
 					{
700
-					    $result=$this->insertExtraFields();
700
+					    $result = $this->insertExtraFields();
701 701
 					    if ($result < 0) $error++;
702 702
 					}
703 703
 						/*}
@@ -705,11 +705,11 @@  discard block
 block discarded – undo
705 705
 					else if ($reshook < 0) $error++;*/
706 706
 
707 707
                     // Call trigger
708
-                    $result=$this->call_trigger('BILL_CREATE',$user);
708
+                    $result = $this->call_trigger('BILL_CREATE', $user);
709 709
                     if ($result < 0) $error++;
710 710
                     // End call triggers
711 711
 
712
-					if (! $error)
712
+					if (!$error)
713 713
 					{
714 714
 						$this->db->commit();
715 715
 						return $this->id;
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
 				}
723 723
 				else
724 724
 				{
725
-					$this->error=$langs->trans('FailedToUpdatePrice');
725
+					$this->error = $langs->trans('FailedToUpdatePrice');
726 726
 					$this->db->rollback();
727 727
 					return -3;
728 728
 				}
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
 		}
737 737
 		else
738 738
 		{
739
-			$this->error=$this->db->error();
739
+			$this->error = $this->db->error();
740 740
 			$this->db->rollback();
741 741
 			return -1;
742 742
 		}
@@ -750,20 +750,20 @@  discard block
 block discarded – undo
750 750
 	 *	@param		int		$invertdetail	Reverse sign of amounts for lines
751 751
 	 *	@return		int						<0 if KO, >0 if OK
752 752
 	 */
753
-	function createFromCurrent($user,$invertdetail=0)
753
+	function createFromCurrent($user, $invertdetail = 0)
754 754
 	{
755 755
 		global $conf;
756 756
 
757 757
 		// Charge facture source
758
-		$facture=new Facture($this->db);
758
+		$facture = new Facture($this->db);
759 759
 
760 760
                 $this->fetch_optionals();
761
-                if(!empty($this->array_options)){
761
+                if (!empty($this->array_options)) {
762 762
                     $facture->array_options = $this->array_options;
763 763
                 }
764 764
 
765
-                foreach($this->lines as &$line){
766
-                    $line->fetch_optionals();//fetch extrafields
765
+                foreach ($this->lines as &$line) {
766
+                    $line->fetch_optionals(); //fetch extrafields
767 767
                 }
768 768
 
769 769
 		$facture->fk_facture_source = $this->fk_facture_source;
@@ -784,14 +784,14 @@  discard block
 block discarded – undo
784 784
 		$facture->origin                        = $this->origin;
785 785
 		$facture->origin_id                     = $this->origin_id;
786 786
 
787
-		$facture->lines		    	= $this->lines;	// Tableau des lignes de factures
788
-		$facture->products		    = $this->lines;	// Tant que products encore utilise
787
+		$facture->lines = $this->lines; // Tableau des lignes de factures
788
+		$facture->products = $this->lines; // Tant que products encore utilise
789 789
 		$facture->situation_counter = $this->situation_counter;
790
-		$facture->situation_cycle_ref=$this->situation_cycle_ref;
791
-		$facture->situation_final  = $this->situation_final;
790
+		$facture->situation_cycle_ref = $this->situation_cycle_ref;
791
+		$facture->situation_final = $this->situation_final;
792 792
 
793 793
 		// Loop on each line of new invoice
794
-		foreach($facture->lines as $i => $tmpline)
794
+		foreach ($facture->lines as $i => $tmpline)
795 795
 		{
796 796
 			$facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
797 797
 			if ($invertdetail)
@@ -810,8 +810,8 @@  discard block
 block discarded – undo
810 810
 		$facid = $facture->create($user);
811 811
 		if ($facid <= 0)
812 812
 		{
813
-			$this->error=$facture->error;
814
-			$this->errors=$facture->errors;
813
+			$this->error = $facture->error;
814
+			$this->errors = $facture->errors;
815 815
 		}
816 816
 		elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
817 817
 		{
@@ -838,18 +838,18 @@  discard block
 block discarded – undo
838 838
 	 *		@param		int				$socid			Id of thirdparty
839 839
 	 * 	 	@return		int								New id of clone
840 840
 	 */
841
-	function createFromClone($socid=0)
841
+	function createFromClone($socid = 0)
842 842
 	{
843
-		global $user,$hookmanager;
843
+		global $user, $hookmanager;
844 844
 
845
-		$error=0;
845
+		$error = 0;
846 846
 
847 847
 		$this->context['createfromclone'] = 'createfromclone';
848 848
 
849 849
 		$this->db->begin();
850 850
 
851 851
 		// get extrafields so they will be clone
852
-		foreach($this->lines as $line)
852
+		foreach ($this->lines as $line)
853 853
 			$line->fetch_optionals($line->rowid);
854 854
 
855 855
 		// Load source object
@@ -858,27 +858,27 @@  discard block
 block discarded – undo
858 858
 
859 859
 
860 860
 		// Change socid if needed
861
-		if (! empty($socid) && $socid != $this->socid)
861
+		if (!empty($socid) && $socid != $this->socid)
862 862
 		{
863 863
 			$objsoc = new Societe($this->db);
864 864
 
865
-			if ($objsoc->fetch($socid)>0)
865
+			if ($objsoc->fetch($socid) > 0)
866 866
 			{
867
-				$this->socid 				= $objsoc->id;
868
-				$this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
869
-				$this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
870
-				$this->fk_project			= '';
871
-				$this->fk_delivery_address	= '';
867
+				$this->socid = $objsoc->id;
868
+				$this->cond_reglement_id	= (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
869
+				$this->mode_reglement_id	= (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
870
+				$this->fk_project = '';
871
+				$this->fk_delivery_address = '';
872 872
 			}
873 873
 
874 874
 			// TODO Change product price if multi-prices
875 875
 		}
876 876
 
877
-		$this->id=0;
878
-		$this->statut= self::STATUS_DRAFT;
877
+		$this->id = 0;
878
+		$this->statut = self::STATUS_DRAFT;
879 879
 
880 880
 		// Clear fields
881
-		$this->date               = dol_now();	// Date of invoice is set to current date when cloning. // TODO Best is to ask date into confirm box
881
+		$this->date               = dol_now(); // Date of invoice is set to current date when cloning. // TODO Best is to ask date into confirm box
882 882
 		$this->user_author        = $user->id;
883 883
 		$this->user_valid         = '';
884 884
 		$this->fk_facture_source  = 0;
@@ -887,20 +887,20 @@  discard block
 block discarded – undo
887 887
 		$this->ref_client         = '';
888 888
 		$this->close_code         = '';
889 889
 		$this->close_note         = '';
890
-		$this->products = $this->lines;	// Tant que products encore utilise
890
+		$this->products = $this->lines; // Tant que products encore utilise
891 891
 
892 892
 		// Loop on each line of new invoice
893
-		foreach($this->lines as $i => $line)
893
+		foreach ($this->lines as $i => $line)
894 894
 		{
895 895
 			if (($this->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
896 896
 			{
897 897
 				unset($this->lines[$i]);
898
-				unset($this->products[$i]);	// Tant que products encore utilise
898
+				unset($this->products[$i]); // Tant que products encore utilise
899 899
 			}
900 900
 		}
901 901
 
902 902
 		// Create clone
903
-		$result=$this->create($user);
903
+		$result = $this->create($user);
904 904
 		if ($result < 0) $error++;
905 905
 		else {
906 906
 			// copy internal contacts
@@ -915,19 +915,19 @@  discard block
 block discarded – undo
915 915
 			}
916 916
 		}
917 917
 
918
-		if (! $error)
918
+		if (!$error)
919 919
 		{
920 920
 			// Hook of thirdparty module
921 921
 			if (is_object($hookmanager))
922 922
 			{
923
-				$parameters=array('objFrom'=>$objFrom);
924
-				$action='';
925
-				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
923
+				$parameters = array('objFrom'=>$objFrom);
924
+				$action = '';
925
+				$reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
926 926
 				if ($reshook < 0) $error++;
927 927
 			}
928 928
 
929 929
             // Call trigger
930
-            $result=$this->call_trigger('BILL_CLONE',$user);
930
+            $result = $this->call_trigger('BILL_CLONE', $user);
931 931
             if ($result < 0) $error++;
932 932
             // End call triggers
933 933
 		}
@@ -935,7 +935,7 @@  discard block
 block discarded – undo
935 935
 		unset($this->context['createfromclone']);
936 936
 
937 937
 		// End
938
-		if (! $error)
938
+		if (!$error)
939 939
 		{
940 940
 			$this->db->commit();
941 941
 			return $this->id;
@@ -955,48 +955,48 @@  discard block
 block discarded – undo
955 955
 	 */
956 956
 	function createFromOrder($object)
957 957
 	{
958
-		global $user,$hookmanager;
958
+		global $user, $hookmanager;
959 959
 
960
-		$error=0;
960
+		$error = 0;
961 961
 
962 962
 		// Closed order
963 963
 		$this->date = dol_now();
964 964
 		$this->source = 0;
965 965
 
966
-		$num=count($object->lines);
966
+		$num = count($object->lines);
967 967
 		for ($i = 0; $i < $num; $i++)
968 968
 		{
969 969
 			$line = new FactureLigne($this->db);
970 970
 
971
-			$line->libelle			= $object->lines[$i]->libelle;
971
+			$line->libelle = $object->lines[$i]->libelle;
972 972
 			$line->label			= $object->lines[$i]->label;
973 973
 			$line->desc				= $object->lines[$i]->desc;
974 974
 			$line->subprice			= $object->lines[$i]->subprice;
975 975
 			$line->total_ht			= $object->lines[$i]->total_ht;
976 976
 			$line->total_tva		= $object->lines[$i]->total_tva;
977 977
 			$line->total_ttc		= $object->lines[$i]->total_ttc;
978
-			$line->vat_src_code  	= $object->lines[$i]->vat_src_code;
979
-			$line->tva_tx			= $object->lines[$i]->tva_tx;
978
+			$line->vat_src_code = $object->lines[$i]->vat_src_code;
979
+			$line->tva_tx = $object->lines[$i]->tva_tx;
980 980
 			$line->localtax1_tx		= $object->lines[$i]->localtax1_tx;
981 981
 			$line->localtax2_tx		= $object->lines[$i]->localtax2_tx;
982
-			$line->qty				= $object->lines[$i]->qty;
983
-			$line->fk_remise_except	= $object->lines[$i]->fk_remise_except;
984
-			$line->remise_percent	= $object->lines[$i]->remise_percent;
985
-			$line->fk_product		= $object->lines[$i]->fk_product;
986
-			$line->info_bits		= $object->lines[$i]->info_bits;
982
+			$line->qty = $object->lines[$i]->qty;
983
+			$line->fk_remise_except = $object->lines[$i]->fk_remise_except;
984
+			$line->remise_percent = $object->lines[$i]->remise_percent;
985
+			$line->fk_product = $object->lines[$i]->fk_product;
986
+			$line->info_bits = $object->lines[$i]->info_bits;
987 987
 			$line->product_type		= $object->lines[$i]->product_type;
988
-			$line->rang				= $object->lines[$i]->rang;
988
+			$line->rang = $object->lines[$i]->rang;
989 989
 			$line->special_code		= $object->lines[$i]->special_code;
990
-			$line->fk_parent_line	= $object->lines[$i]->fk_parent_line;
991
-			$line->fk_unit			= $object->lines[$i]->fk_unit;
990
+			$line->fk_parent_line = $object->lines[$i]->fk_parent_line;
991
+			$line->fk_unit = $object->lines[$i]->fk_unit;
992 992
 
993
-			$line->fk_fournprice	= $object->lines[$i]->fk_fournprice;
993
+			$line->fk_fournprice = $object->lines[$i]->fk_fournprice;
994 994
 			$marginInfos			= getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
995 995
 			$line->pa_ht			= $marginInfos[0];
996 996
 
997 997
             // get extrafields from original line
998 998
 			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
999
-			foreach($object->lines[$i]->array_options as $options_key => $value)
999
+			foreach ($object->lines[$i]->array_options as $options_key => $value)
1000 1000
 				$line->array_options[$options_key] = $value;
1001 1001
 
1002 1002
 			$this->lines[$i] = $line;
@@ -1015,17 +1015,17 @@  discard block
 block discarded – undo
1015 1015
 		$this->note_private         = $object->note_private;
1016 1016
 		$this->note_public          = $object->note_public;
1017 1017
 
1018
-		$this->origin				= $object->element;
1019
-		$this->origin_id			= $object->id;
1018
+		$this->origin = $object->element;
1019
+		$this->origin_id = $object->id;
1020 1020
 
1021 1021
         // get extrafields from original line
1022 1022
 		$object->fetch_optionals($object->id);
1023
-		foreach($object->array_options as $options_key => $value)
1023
+		foreach ($object->array_options as $options_key => $value)
1024 1024
 			$this->array_options[$options_key] = $value;
1025 1025
 
1026 1026
 		// Possibility to add external linked objects with hooks
1027 1027
 		$this->linked_objects[$this->origin] = $this->origin_id;
1028
-		if (! empty($object->other_linked_objects) && is_array($object->other_linked_objects))
1028
+		if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects))
1029 1029
 		{
1030 1030
 			$this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1031 1031
 		}
@@ -1037,12 +1037,12 @@  discard block
 block discarded – undo
1037 1037
 			// Actions hooked (by external module)
1038 1038
 			$hookmanager->initHooks(array('invoicedao'));
1039 1039
 
1040
-			$parameters=array('objFrom'=>$object);
1041
-			$action='';
1042
-			$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1040
+			$parameters = array('objFrom'=>$object);
1041
+			$action = '';
1042
+			$reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1043 1043
 			if ($reshook < 0) $error++;
1044 1044
 
1045
-			if (! $error)
1045
+			if (!$error)
1046 1046
 			{
1047 1047
 				return 1;
1048 1048
 			}
@@ -1057,21 +1057,21 @@  discard block
 block discarded – undo
1057 1057
 	 * @param	int				$withpicto			Add download picto into link
1058 1058
 	 * @return	string			HTML link to file
1059 1059
 	 */
1060
-	function getDirectExternalLink($withpicto=0)
1060
+	function getDirectExternalLink($withpicto = 0)
1061 1061
 	{
1062 1062
 		global $dolibarr_main_url_root;
1063 1063
 
1064 1064
 		// Define $urlwithroot
1065
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
1066
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
1065
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1066
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1067 1067
 		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
1068 1068
 
1069 1069
 		// TODO Read into ecmfile table to get entry and hash exists (PS: If not found, add it)
1070 1070
 		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1071
-		$ecmfile=new EcmFiles($this->db);
1071
+		$ecmfile = new EcmFiles($this->db);
1072 1072
 		//$result = $ecmfile->get();
1073 1073
 
1074
-		$hashp='todo';
1074
+		$hashp = 'todo';
1075 1075
 		return '<a href="'.$urlwithroot.'/document.php?modulepart=invoice&hashp='.$hashp.'" target="_download" rel="noindex, nofollow">'.$this->ref.'</a>';
1076 1076
 	}
1077 1077
 
@@ -1088,13 +1088,13 @@  discard block
 block discarded – undo
1088 1088
      *  @param  int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1089 1089
 	 *  @return string 			         			String with URL
1090 1090
 	 */
1091
-	function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1)
1091
+	function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1)
1092 1092
 	{
1093 1093
 		global $langs, $conf, $user, $form;
1094 1094
 
1095
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1095
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1096 1096
 
1097
-		$result='';
1097
+		$result = '';
1098 1098
 
1099 1099
 		if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1100 1100
 		else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
@@ -1104,67 +1104,67 @@  discard block
 block discarded – undo
1104 1104
 		if ($option !== 'nolink')
1105 1105
 		{
1106 1106
 			// Add param to save lastsearch_values or not
1107
-			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1108
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1109
-			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1107
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1108
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1109
+			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1110 1110
 		}
1111 1111
 
1112
-		$picto='bill';
1113
-		if ($this->type == self::TYPE_REPLACEMENT) $picto.='r';	// Replacement invoice
1114
-		if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a';	// Credit note
1115
-		if ($this->type == self::TYPE_DEPOSIT) $picto.='d';	// Deposit invoice
1116
-        $label='';
1112
+		$picto = 'bill';
1113
+		if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice
1114
+		if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note
1115
+		if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice
1116
+        $label = '';
1117 1117
 
1118 1118
         if ($user->rights->facture->lire) {
1119
-            $label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
1120
-            if (! empty($this->ref))
1121
-                $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
1122
-            if (! empty($this->ref_client))
1123
-                $label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
1124
-            if (! empty($this->total_ht))
1125
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1126
-            if (! empty($this->total_tva))
1127
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1128
-            if (! empty($this->total_ttc))
1129
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1130
-    		if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1131
-    		if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1132
-    		if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1133
-    		if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1134
-    		if ($moretitle) $label.=' - '.$moretitle;
1119
+            $label = '<u>'.$langs->trans("ShowInvoice").'</u>';
1120
+            if (!empty($this->ref))
1121
+                $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1122
+            if (!empty($this->ref_client))
1123
+                $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
1124
+            if (!empty($this->total_ht))
1125
+                $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1126
+            if (!empty($this->total_tva))
1127
+                $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1128
+            if (!empty($this->total_ttc))
1129
+                $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1130
+    		if ($this->type == self::TYPE_REPLACEMENT) $label = $langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1131
+    		if ($this->type == self::TYPE_CREDIT_NOTE) $label = $langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1132
+    		if ($this->type == self::TYPE_DEPOSIT) $label = $langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1133
+    		if ($this->type == self::TYPE_SITUATION) $label = $langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1134
+    		if ($moretitle) $label .= ' - '.$moretitle;
1135 1135
         }
1136 1136
 
1137
-		$linkclose='';
1137
+		$linkclose = '';
1138 1138
 		if (empty($notooltip) && $user->rights->facture->lire)
1139 1139
 		{
1140
-		    if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1140
+		    if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1141 1141
 		    {
1142
-		        $label=$langs->trans("ShowInvoice");
1143
-		        $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1142
+		        $label = $langs->trans("ShowInvoice");
1143
+		        $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1144 1144
 		    }
1145
-		    $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1146
-		    $linkclose.=' class="classfortooltip"';
1145
+		    $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1146
+		    $linkclose .= ' class="classfortooltip"';
1147 1147
 		}
1148 1148
 
1149
-        $linkstart='<a href="'.$url.'"';
1150
-        $linkstart.=$linkclose.'>';
1151
-		$linkend='</a>';
1149
+        $linkstart = '<a href="'.$url.'"';
1150
+        $linkstart .= $linkclose.'>';
1151
+		$linkend = '</a>';
1152 1152
 
1153
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
1154
-		if ($withpicto && $withpicto != 2) $result.=' ';
1155
-		if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
1153
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
1154
+		if ($withpicto && $withpicto != 2) $result .= ' ';
1155
+		if ($withpicto != 2) $result .= $linkstart.($max ?dol_trunc($this->ref, $max) : $this->ref).$linkend;
1156 1156
 
1157 1157
 		if ($addlinktonotes)
1158 1158
 		{
1159
-		    $txttoshow=($user->societe_id>0?$this->note_public:$this->note_private);
1159
+		    $txttoshow = ($user->societe_id > 0 ? $this->note_public : $this->note_private);
1160 1160
 		    if ($txttoshow)
1161 1161
 		    {
1162
-                $notetoshow=$langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow,1);
1163
-    		    $result.=' <span class="note inline-block">';
1164
-    		    $result.='<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'.img_picto('','object_generic').'</a>';
1162
+                $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1163
+    		    $result .= ' <span class="note inline-block">';
1164
+    		    $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'.img_picto('', 'object_generic').'</a>';
1165 1165
     		    //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1166 1166
     		    //$result.='</a>';
1167
-    		    $result.='</span>';
1167
+    		    $result .= '</span>';
1168 1168
 		    }
1169 1169
 		}
1170 1170
 
@@ -1181,39 +1181,39 @@  discard block
 block discarded – undo
1181 1181
 	 *  @param		bool	$fetch_situation	Fetch the previous and next situation in $tab_previous_situation_invoice and $tab_next_situation_invoice
1182 1182
 	 *	@return     int         			>0 if OK, <0 if KO, 0 if not found
1183 1183
 	 */
1184
-	function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $fetch_situation=false)
1184
+	function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $fetch_situation = false)
1185 1185
 	{
1186 1186
 		global $conf;
1187 1187
 
1188 1188
 		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1189 1189
 
1190 1190
 		$sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount';
1191
-		$sql.= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp';
1192
-		$sql.= ', f.remise_percent, f.remise_absolue, f.remise';
1193
-		$sql.= ', f.datef as df, f.date_pointoftax';
1194
-		$sql.= ', f.date_lim_reglement as dlr';
1195
-		$sql.= ', f.datec as datec';
1196
-		$sql.= ', f.date_valid as datev';
1197
-		$sql.= ', f.tms as datem';
1198
-		$sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
1199
-		$sql.= ', f.fk_facture_source';
1200
-		$sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams';
1201
-		$sql.= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1202
-		$sql.= ', f.fk_account';
1203
-		$sql.= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1204
-		$sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1205
-		$sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1206
-        $sql.= ', f.fk_incoterms, f.location_incoterms';
1207
-        $sql.= ", i.libelle as libelle_incoterms";
1208
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1209
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')';
1210
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')';
1211
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1212
-		$sql.= ' WHERE f.entity = '.$conf->entity;
1213
-		if ($rowid)   $sql.= " AND f.rowid=".$rowid;
1214
-		if ($ref)     $sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
1215
-		if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1216
-		if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
1191
+		$sql .= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp';
1192
+		$sql .= ', f.remise_percent, f.remise_absolue, f.remise';
1193
+		$sql .= ', f.datef as df, f.date_pointoftax';
1194
+		$sql .= ', f.date_lim_reglement as dlr';
1195
+		$sql .= ', f.datec as datec';
1196
+		$sql .= ', f.date_valid as datev';
1197
+		$sql .= ', f.tms as datem';
1198
+		$sql .= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
1199
+		$sql .= ', f.fk_facture_source';
1200
+		$sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams';
1201
+		$sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1202
+		$sql .= ', f.fk_account';
1203
+		$sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1204
+		$sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1205
+		$sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1206
+        $sql .= ', f.fk_incoterms, f.location_incoterms';
1207
+        $sql .= ", i.libelle as libelle_incoterms";
1208
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1209
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN ('.getEntity('c_payment_term').')';
1210
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')';
1211
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1212
+		$sql .= ' WHERE f.entity = '.$conf->entity;
1213
+		if ($rowid)   $sql .= " AND f.rowid=".$rowid;
1214
+		if ($ref)     $sql .= " AND f.facnumber='".$this->db->escape($ref)."'";
1215
+		if ($ref_ext) $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1216
+		if ($ref_int) $sql .= " AND f.ref_int='".$this->db->escape($ref_int)."'";
1217 1217
 
1218 1218
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1219 1219
 		$result = $this->db->query($sql);
@@ -1223,17 +1223,17 @@  discard block
 block discarded – undo
1223 1223
 			{
1224 1224
 				$obj = $this->db->fetch_object($result);
1225 1225
 
1226
-				$this->id					= $obj->rowid;
1227
-				$this->ref					= $obj->facnumber;
1228
-				$this->ref_client			= $obj->ref_client;
1226
+				$this->id = $obj->rowid;
1227
+				$this->ref = $obj->facnumber;
1228
+				$this->ref_client = $obj->ref_client;
1229 1229
 				$this->ref_ext				= $obj->ref_ext;
1230 1230
 				$this->ref_int				= $obj->ref_int;
1231 1231
 				$this->type					= $obj->type;
1232 1232
 				$this->date					= $this->db->jdate($obj->df);
1233 1233
 				$this->date_pointoftax		= $this->db->jdate($obj->date_pointoftax);
1234
-				$this->date_creation		= $this->db->jdate($obj->datec);
1234
+				$this->date_creation = $this->db->jdate($obj->datec);
1235 1235
 				$this->date_validation		= $this->db->jdate($obj->datev);
1236
-				$this->datem				= $this->db->jdate($obj->datem);
1236
+				$this->datem = $this->db->jdate($obj->datem);
1237 1237
 				$this->remise_percent		= $obj->remise_percent;
1238 1238
 				$this->remise_absolue		= $obj->remise_absolue;
1239 1239
 				$this->total_ht				= $obj->total;
@@ -1241,33 +1241,33 @@  discard block
 block discarded – undo
1241 1241
 				$this->total_localtax1		= $obj->localtax1;
1242 1242
 				$this->total_localtax2		= $obj->localtax2;
1243 1243
 				$this->total_ttc			= $obj->total_ttc;
1244
-				$this->revenuestamp         = $obj->revenuestamp;
1244
+				$this->revenuestamp = $obj->revenuestamp;
1245 1245
 				$this->paye					= $obj->paye;
1246 1246
 				$this->close_code			= $obj->close_code;
1247 1247
 				$this->close_note			= $obj->close_note;
1248 1248
 				$this->socid				= $obj->fk_soc;
1249
-				$this->statut				= $obj->fk_statut;
1250
-				$this->date_lim_reglement	= $this->db->jdate($obj->dlr);
1249
+				$this->statut = $obj->fk_statut;
1250
+				$this->date_lim_reglement = $this->db->jdate($obj->dlr);
1251 1251
 				$this->mode_reglement_id	= $obj->fk_mode_reglement;
1252 1252
 				$this->mode_reglement_code	= $obj->mode_reglement_code;
1253 1253
 				$this->mode_reglement		= $obj->mode_reglement_libelle;
1254 1254
 				$this->cond_reglement_id	= $obj->fk_cond_reglement;
1255 1255
 				$this->cond_reglement_code	= $obj->cond_reglement_code;
1256 1256
 				$this->cond_reglement		= $obj->cond_reglement_libelle;
1257
-				$this->cond_reglement_doc	= $obj->cond_reglement_libelle_doc;
1258
-				$this->fk_account           = ($obj->fk_account>0)?$obj->fk_account:null;
1259
-				$this->fk_project			= $obj->fk_projet;
1260
-				$this->fk_facture_source	= $obj->fk_facture_source;
1261
-				$this->note					= $obj->note_private;	// deprecated
1262
-				$this->note_private			= $obj->note_private;
1257
+				$this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1258
+				$this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1259
+				$this->fk_project = $obj->fk_projet;
1260
+				$this->fk_facture_source = $obj->fk_facture_source;
1261
+				$this->note = $obj->note_private; // deprecated
1262
+				$this->note_private = $obj->note_private;
1263 1263
 				$this->note_public			= $obj->note_public;
1264 1264
 				$this->user_author			= $obj->fk_user_author;
1265
-				$this->user_valid			= $obj->fk_user_valid;
1266
-				$this->modelpdf				= $obj->model_pdf;
1265
+				$this->user_valid = $obj->fk_user_valid;
1266
+				$this->modelpdf = $obj->model_pdf;
1267 1267
 				$this->situation_cycle_ref  = $obj->situation_cycle_ref;
1268 1268
 				$this->situation_counter    = $obj->situation_counter;
1269 1269
 				$this->situation_final      = $obj->situation_final;
1270
-				$this->extraparams			= (array) json_decode($obj->extraparams, true);
1270
+				$this->extraparams = (array) json_decode($obj->extraparams, true);
1271 1271
 
1272 1272
 				//Incoterms
1273 1273
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -1276,9 +1276,9 @@  discard block
 block discarded – undo
1276 1276
 
1277 1277
 				// Multicurrency
1278 1278
 				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1279
-				$this->multicurrency_code 		= $obj->multicurrency_code;
1279
+				$this->multicurrency_code = $obj->multicurrency_code;
1280 1280
 				$this->multicurrency_tx 		= $obj->multicurrency_tx;
1281
-				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1281
+				$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1282 1282
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1283 1283
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1284 1284
 
@@ -1292,34 +1292,34 @@  discard block
 block discarded – undo
1292 1292
 				// Retrieve all extrafield for invoice
1293 1293
 				// fetch optionals attributes and labels
1294 1294
 				require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1295
-				$extrafields=new ExtraFields($this->db);
1296
-				$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
1297
-				$this->fetch_optionals($this->id,$extralabels);
1295
+				$extrafields = new ExtraFields($this->db);
1296
+				$extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true);
1297
+				$this->fetch_optionals($this->id, $extralabels);
1298 1298
 
1299 1299
 				/*
1300 1300
 				 * Lines
1301 1301
 				*/
1302 1302
 
1303
-				$this->lines  = array();
1303
+				$this->lines = array();
1304 1304
 
1305
-				$result=$this->fetch_lines();
1305
+				$result = $this->fetch_lines();
1306 1306
 				if ($result < 0)
1307 1307
 				{
1308
-					$this->error=$this->db->error();
1308
+					$this->error = $this->db->error();
1309 1309
 					return -3;
1310 1310
 				}
1311 1311
 				return 1;
1312 1312
 			}
1313 1313
 			else
1314 1314
 			{
1315
-				$this->error='Bill with id '.$rowid.' or ref '.$ref.' not found';
1315
+				$this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
1316 1316
 				dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
1317 1317
 				return 0;
1318 1318
 			}
1319 1319
 		}
1320 1320
 		else
1321 1321
 		{
1322
-			$this->error=$this->db->error();
1322
+			$this->error = $this->db->error();
1323 1323
 			return -1;
1324 1324
 		}
1325 1325
 	}
@@ -1332,21 +1332,21 @@  discard block
 block discarded – undo
1332 1332
 	 */
1333 1333
 	function fetch_lines()
1334 1334
 	{
1335
-		$this->lines=array();
1335
+		$this->lines = array();
1336 1336
 
1337 1337
 		$sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
1338
-		$sql.= ' l.situation_percent, l.fk_prev_id,';
1339
-		$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
1340
-		$sql.= ' l.rang, l.special_code,';
1341
-		$sql.= ' l.date_start as date_start, l.date_end as date_end,';
1342
-		$sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
1343
-		$sql.= ' l.fk_unit,';
1344
-		$sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1345
-		$sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
1346
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
1347
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
1348
-		$sql.= ' WHERE l.fk_facture = '.$this->id;
1349
-		$sql.= ' ORDER BY l.rang, l.rowid';
1338
+		$sql .= ' l.situation_percent, l.fk_prev_id,';
1339
+		$sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
1340
+		$sql .= ' l.rang, l.special_code,';
1341
+		$sql .= ' l.date_start as date_start, l.date_end as date_end,';
1342
+		$sql .= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
1343
+		$sql .= ' l.fk_unit,';
1344
+		$sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1345
+		$sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
1346
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
1347
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
1348
+		$sql .= ' WHERE l.fk_facture = '.$this->id;
1349
+		$sql .= ' ORDER BY l.rang, l.rowid';
1350 1350
 
1351 1351
 		dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
1352 1352
 		$result = $this->db->query($sql);
@@ -1360,22 +1360,22 @@  discard block
 block discarded – undo
1360 1360
 				$line = new FactureLigne($this->db);
1361 1361
 
1362 1362
 				$line->id               = $objp->rowid;
1363
-				$line->rowid	        = $objp->rowid;             // deprecated
1363
+				$line->rowid = $objp->rowid; // deprecated
1364 1364
 				$line->fk_facture       = $objp->fk_facture;
1365
-				$line->label            = $objp->custom_label;		// deprecated
1366
-				$line->desc             = $objp->description;		// Description line
1367
-				$line->description      = $objp->description;		// Description line
1368
-				$line->product_type     = $objp->product_type;		// Type of line
1369
-				$line->ref              = $objp->product_ref;		// Ref product
1370
-				$line->product_ref      = $objp->product_ref;		// Ref product
1371
-				$line->libelle          = $objp->product_label;		// TODO deprecated
1372
-				$line->product_label	= $objp->product_label;		// Label product
1373
-				$line->product_desc     = $objp->product_desc;		// Description product
1374
-				$line->fk_product_type  = $objp->fk_product_type;	// Type of product
1365
+				$line->label            = $objp->custom_label; // deprecated
1366
+				$line->desc             = $objp->description; // Description line
1367
+				$line->description      = $objp->description; // Description line
1368
+				$line->product_type     = $objp->product_type; // Type of line
1369
+				$line->ref              = $objp->product_ref; // Ref product
1370
+				$line->product_ref      = $objp->product_ref; // Ref product
1371
+				$line->libelle          = $objp->product_label; // TODO deprecated
1372
+				$line->product_label = $objp->product_label; // Label product
1373
+				$line->product_desc     = $objp->product_desc; // Description product
1374
+				$line->fk_product_type  = $objp->fk_product_type; // Type of product
1375 1375
 				$line->qty              = $objp->qty;
1376 1376
 				$line->subprice         = $objp->subprice;
1377 1377
 
1378
-                $line->vat_src_code     = $objp->vat_src_code;
1378
+                $line->vat_src_code = $objp->vat_src_code;
1379 1379
 				$line->tva_tx           = $objp->tva_tx;
1380 1380
 				$line->localtax1_tx     = $objp->localtax1_tx;
1381 1381
 				$line->localtax2_tx     = $objp->localtax2_tx;
@@ -1395,21 +1395,21 @@  discard block
 block discarded – undo
1395 1395
 				$line->total_localtax2  = $objp->total_localtax2;
1396 1396
 				$line->total_ttc        = $objp->total_ttc;
1397 1397
 				$line->code_ventilation = $objp->fk_code_ventilation;
1398
-				$line->fk_fournprice 	= $objp->fk_fournprice;
1399
-				$marginInfos			= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1400
-				$line->pa_ht 			= $marginInfos[0];
1398
+				$line->fk_fournprice = $objp->fk_fournprice;
1399
+				$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1400
+				$line->pa_ht = $marginInfos[0];
1401 1401
 				$line->marge_tx			= $marginInfos[1];
1402 1402
 				$line->marque_tx		= $marginInfos[2];
1403
-				$line->rang				= $objp->rang;
1404
-				$line->special_code		= $objp->special_code;
1405
-				$line->fk_parent_line	= $objp->fk_parent_line;
1406
-				$line->situation_percent= $objp->situation_percent;
1403
+				$line->rang = $objp->rang;
1404
+				$line->special_code = $objp->special_code;
1405
+				$line->fk_parent_line = $objp->fk_parent_line;
1406
+				$line->situation_percent = $objp->situation_percent;
1407 1407
 				$line->fk_prev_id       = $objp->fk_prev_id;
1408
-				$line->fk_unit	        = $objp->fk_unit;
1408
+				$line->fk_unit = $objp->fk_unit;
1409 1409
 
1410 1410
 				// Multicurrency
1411
-				$line->fk_multicurrency 		= $objp->fk_multicurrency;
1412
-				$line->multicurrency_code 		= $objp->multicurrency_code;
1411
+				$line->fk_multicurrency = $objp->fk_multicurrency;
1412
+				$line->multicurrency_code = $objp->multicurrency_code;
1413 1413
 				$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
1414 1414
 				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
1415 1415
 				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
 		}
1425 1425
 		else
1426 1426
 		{
1427
-			$this->error=$this->db->error();
1427
+			$this->error = $this->db->error();
1428 1428
 			return -3;
1429 1429
 		}
1430 1430
 	}
@@ -1467,22 +1467,22 @@  discard block
 block discarded – undo
1467 1467
 	 *      @param      int		$notrigger	    0=launch triggers after, 1=disable triggers
1468 1468
 	 *      @return     int      			   	<0 if KO, >0 if OK
1469 1469
 	 */
1470
-	function update($user=null, $notrigger=0)
1470
+	function update($user = null, $notrigger = 0)
1471 1471
 	{
1472
-		$error=0;
1472
+		$error = 0;
1473 1473
 
1474 1474
 		// Clean parameters
1475
-		if (empty($this->type)) $this->type= self::TYPE_STANDARD;
1476
-		if (isset($this->facnumber)) $this->facnumber=trim($this->ref);
1477
-		if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
1478
-		if (isset($this->increment)) $this->increment=trim($this->increment);
1479
-		if (isset($this->close_code)) $this->close_code=trim($this->close_code);
1480
-		if (isset($this->close_note)) $this->close_note=trim($this->close_note);
1481
-		if (isset($this->note) || isset($this->note_private)) $this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private));		// deprecated
1482
-		if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1483
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1484
-		if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
1485
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1475
+		if (empty($this->type)) $this->type = self::TYPE_STANDARD;
1476
+		if (isset($this->facnumber)) $this->facnumber = trim($this->ref);
1477
+		if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client);
1478
+		if (isset($this->increment)) $this->increment = trim($this->increment);
1479
+		if (isset($this->close_code)) $this->close_code = trim($this->close_code);
1480
+		if (isset($this->close_note)) $this->close_note = trim($this->close_note);
1481
+		if (isset($this->note) || isset($this->note_private)) $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
1482
+		if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1483
+		if (isset($this->note_public)) $this->note_public = trim($this->note_public);
1484
+		if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf);
1485
+		if (isset($this->import_key)) $this->import_key = trim($this->import_key);
1486 1486
 		if (empty($this->situation_cycle_ref)) {
1487 1487
 			$this->situation_cycle_ref = 'null';
1488 1488
 		}
@@ -1501,58 +1501,58 @@  discard block
 block discarded – undo
1501 1501
 		// Update request
1502 1502
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
1503 1503
 
1504
-		$sql.= " facnumber=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
1505
-		$sql.= " type=".(isset($this->type)?$this->type:"null").",";
1506
-		$sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
1507
-		$sql.= " increment=".(isset($this->increment)?"'".$this->db->escape($this->increment)."'":"null").",";
1508
-		$sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
1509
-		$sql.= " datec=".(strval($this->date_creation)!='' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1510
-		$sql.= " datef=".(strval($this->date)!='' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1511
-		$sql.= " date_pointoftax=".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
1512
-		$sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1513
-		$sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
1514
-		$sql.= " remise_percent=".(isset($this->remise_percent)?$this->remise_percent:"null").",";
1515
-		$sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->remise_absolue:"null").",";
1516
-		$sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
1517
-		$sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
1518
-		$sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
1519
-		$sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").",";
1520
-		$sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
1521
-		$sql.= " total=".(isset($this->total_ht)?$this->total_ht:"null").",";
1522
-		$sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
1523
-		$sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->revenuestamp:"null").",";
1524
-		$sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
1525
-		$sql.= " fk_user_author=".(isset($this->user_author)?$this->user_author:"null").",";
1526
-		$sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
1527
-		$sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
1528
-		$sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
1529
-		$sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
1530
-		$sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
1531
-		$sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
1532
-		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
1533
-		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
1534
-		$sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
1535
-		$sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
1536
-		$sql.= ", situation_cycle_ref=".$this->situation_cycle_ref;
1537
-		$sql.= ", situation_counter=".$this->situation_counter;
1538
-		$sql.= ", situation_final=".$this->situation_final;
1539
-
1540
-		$sql.= " WHERE rowid=".$this->id;
1504
+		$sql .= " facnumber=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1505
+		$sql .= " type=".(isset($this->type) ? $this->type : "null").",";
1506
+		$sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1507
+		$sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
1508
+		$sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1509
+		$sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1510
+		$sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1511
+		$sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
1512
+		$sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1513
+		$sql .= " paye=".(isset($this->paye) ? $this->paye : "null").",";
1514
+		$sql .= " remise_percent=".(isset($this->remise_percent) ? $this->remise_percent : "null").",";
1515
+		$sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->remise_absolue : "null").",";
1516
+		$sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
1517
+		$sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
1518
+		$sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1519
+		$sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1520
+		$sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1521
+		$sql .= " total=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1522
+		$sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1523
+		$sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->revenuestamp : "null").",";
1524
+		$sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
1525
+		$sql .= " fk_user_author=".(isset($this->user_author) ? $this->user_author : "null").",";
1526
+		$sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
1527
+		$sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "null").",";
1528
+		$sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
1529
+		$sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
1530
+		$sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
1531
+		$sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
1532
+		$sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1533
+		$sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1534
+		$sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").",";
1535
+		$sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1536
+		$sql .= ", situation_cycle_ref=".$this->situation_cycle_ref;
1537
+		$sql .= ", situation_counter=".$this->situation_counter;
1538
+		$sql .= ", situation_final=".$this->situation_final;
1539
+
1540
+		$sql .= " WHERE rowid=".$this->id;
1541 1541
 
1542 1542
 		$this->db->begin();
1543 1543
 
1544 1544
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
1545 1545
 		$resql = $this->db->query($sql);
1546
-		if (! $resql) {
1547
-			$error++; $this->errors[]="Error ".$this->db->lasterror();
1546
+		if (!$resql) {
1547
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
1548 1548
 		}
1549 1549
 
1550
-		if (! $error)
1550
+		if (!$error)
1551 1551
 		{
1552
-			if (! $notrigger)
1552
+			if (!$notrigger)
1553 1553
 			{
1554 1554
 	            // Call trigger
1555
-	            $result=$this->call_trigger('BILL_MODIFY',$user);
1555
+	            $result = $this->call_trigger('BILL_MODIFY', $user);
1556 1556
 	            if ($result < 0) $error++;
1557 1557
 	            // End call triggers
1558 1558
 			}
@@ -1561,13 +1561,13 @@  discard block
 block discarded – undo
1561 1561
 		// Commit or rollback
1562 1562
 		if ($error)
1563 1563
 		{
1564
-			foreach($this->errors as $errmsg)
1564
+			foreach ($this->errors as $errmsg)
1565 1565
 			{
1566 1566
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1567
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
1567
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1568 1568
 			}
1569 1569
 			$this->db->rollback();
1570
-			return -1*$error;
1570
+			return -1 * $error;
1571 1571
 		}
1572 1572
 		else
1573 1573
 		{
@@ -1592,40 +1592,40 @@  discard block
 block discarded – undo
1592 1592
 
1593 1593
 		$this->db->begin();
1594 1594
 
1595
-		$remise=new DiscountAbsolute($this->db);
1596
-		$result=$remise->fetch($idremise);
1595
+		$remise = new DiscountAbsolute($this->db);
1596
+		$result = $remise->fetch($idremise);
1597 1597
 
1598 1598
 		if ($result > 0)
1599 1599
 		{
1600 1600
 			if ($remise->fk_facture)	// Protection against multiple submission
1601 1601
 			{
1602
-				$this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1602
+				$this->error = $langs->trans("ErrorDiscountAlreadyUsed");
1603 1603
 				$this->db->rollback();
1604 1604
 				return -5;
1605 1605
 			}
1606 1606
 
1607
-			$facligne=new FactureLigne($this->db);
1608
-			$facligne->fk_facture=$this->id;
1609
-			$facligne->fk_remise_except=$remise->id;
1610
-			$facligne->desc=$remise->description;   	// Description ligne
1611
-			$facligne->vat_src_code=$remise->vat_src_code;
1612
-			$facligne->tva_tx=$remise->tva_tx;
1607
+			$facligne = new FactureLigne($this->db);
1608
+			$facligne->fk_facture = $this->id;
1609
+			$facligne->fk_remise_except = $remise->id;
1610
+			$facligne->desc = $remise->description; // Description ligne
1611
+			$facligne->vat_src_code = $remise->vat_src_code;
1612
+			$facligne->tva_tx = $remise->tva_tx;
1613 1613
 			$facligne->subprice = -$remise->amount_ht;
1614
-			$facligne->fk_product=0;					// Id produit predefini
1615
-			$facligne->qty=1;
1616
-			$facligne->remise_percent=0;
1617
-			$facligne->rang=-1;
1618
-			$facligne->info_bits=2;
1614
+			$facligne->fk_product = 0; // Id produit predefini
1615
+			$facligne->qty = 1;
1616
+			$facligne->remise_percent = 0;
1617
+			$facligne->rang = -1;
1618
+			$facligne->info_bits = 2;
1619 1619
 
1620 1620
 			// Get buy/cost price of invoice that is source of discount
1621 1621
 			if ($remise->fk_facture_source > 0)
1622 1622
 			{
1623
-    			$srcinvoice=new Facture($this->db);
1623
+    			$srcinvoice = new Facture($this->db);
1624 1624
     			$srcinvoice->fetch($remise->fk_facture_source);
1625
-    			$totalcostpriceofinvoice=0;
1626
-    			include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';  // TODO Move this into commonobject
1627
-    			$formmargin=new FormMargin($this->db);
1628
-    			$arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false);
1625
+    			$totalcostpriceofinvoice = 0;
1626
+    			include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
1627
+    			$formmargin = new FormMargin($this->db);
1628
+    			$arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
1629 1629
         		$facligne->pa_ht = $arraytmp['pa_total'];
1630 1630
 			}
1631 1631
 
@@ -1638,17 +1638,17 @@  discard block
 block discarded – undo
1638 1638
 			$facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
1639 1639
 			$facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
1640 1640
 
1641
-			$lineid=$facligne->insert();
1641
+			$lineid = $facligne->insert();
1642 1642
 			if ($lineid > 0)
1643 1643
 			{
1644
-				$result=$this->update_price(1);
1644
+				$result = $this->update_price(1);
1645 1645
 				if ($result > 0)
1646 1646
 				{
1647 1647
 					// Create linke between discount and invoice line
1648
-					$result=$remise->link_to_invoice($lineid,0);
1648
+					$result = $remise->link_to_invoice($lineid, 0);
1649 1649
 					if ($result < 0)
1650 1650
 					{
1651
-						$this->error=$remise->error;
1651
+						$this->error = $remise->error;
1652 1652
 						$this->db->rollback();
1653 1653
 						return -4;
1654 1654
 					}
@@ -1658,14 +1658,14 @@  discard block
 block discarded – undo
1658 1658
 				}
1659 1659
 				else
1660 1660
 				{
1661
-					$this->error=$facligne->error;
1661
+					$this->error = $facligne->error;
1662 1662
 					$this->db->rollback();
1663 1663
 					return -1;
1664 1664
 				}
1665 1665
 			}
1666 1666
 			else
1667 1667
 			{
1668
-				$this->error=$facligne->error;
1668
+				$this->error = $facligne->error;
1669 1669
 				$this->db->rollback();
1670 1670
 				return -2;
1671 1671
 			}
@@ -1684,11 +1684,11 @@  discard block
 block discarded – undo
1684 1684
 	 *  @param     	int		$notrigger		1=Does not execute triggers, 0= execute triggers
1685 1685
 	 *	@return		int						<0 if KO, >0 if OK
1686 1686
 	 */
1687
-	function set_ref_client($ref_client, $notrigger=0)
1687
+	function set_ref_client($ref_client, $notrigger = 0)
1688 1688
 	{
1689 1689
 	    global $user;
1690 1690
 
1691
-		$error=0;
1691
+		$error = 0;
1692 1692
 
1693 1693
 		$this->db->begin();
1694 1694
 
@@ -1700,27 +1700,27 @@  discard block
 block discarded – undo
1700 1700
 		$sql .= ' WHERE rowid = '.$this->id;
1701 1701
 
1702 1702
 		dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
1703
-		$resql=$this->db->query($sql);
1703
+		$resql = $this->db->query($sql);
1704 1704
 		if (!$resql)
1705 1705
 		{
1706
-			$this->errors[]=$this->db->error();
1706
+			$this->errors[] = $this->db->error();
1707 1707
 			$error++;
1708 1708
 		}
1709 1709
 
1710
-		if (! $error)
1710
+		if (!$error)
1711 1711
 		{
1712 1712
 			$this->ref_client = $ref_client;
1713 1713
 		}
1714 1714
 
1715
-		if (! $notrigger && empty($error))
1715
+		if (!$notrigger && empty($error))
1716 1716
 		{
1717 1717
 			// Call trigger
1718
-			$result=$this->call_trigger('BILL_MODIFY',$user);
1718
+			$result = $this->call_trigger('BILL_MODIFY', $user);
1719 1719
 			if ($result < 0) $error++;
1720 1720
 			// End call triggers
1721 1721
 		}
1722 1722
 
1723
-		if (! $error)
1723
+		if (!$error)
1724 1724
 		{
1725 1725
 
1726 1726
 			$this->ref_client = $ref_client;
@@ -1730,13 +1730,13 @@  discard block
 block discarded – undo
1730 1730
 		}
1731 1731
 		else
1732 1732
 		{
1733
-			foreach($this->errors as $errmsg)
1733
+			foreach ($this->errors as $errmsg)
1734 1734
 			{
1735 1735
 				dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1736
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
1736
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1737 1737
 			}
1738 1738
 			$this->db->rollback();
1739
-			return -1*$error;
1739
+			return -1 * $error;
1740 1740
 		}
1741 1741
 	}
1742 1742
 
@@ -1748,12 +1748,12 @@  discard block
 block discarded – undo
1748 1748
 	 *	@param		int		$idwarehouse	Id warehouse to use for stock change.
1749 1749
 	 *	@return		int						<0 if KO, 0=Refused, >0 if OK
1750 1750
 	 */
1751
-	function delete($user, $notrigger=0, $idwarehouse=-1)
1751
+	function delete($user, $notrigger = 0, $idwarehouse = -1)
1752 1752
 	{
1753
-		global $langs,$conf;
1753
+		global $langs, $conf;
1754 1754
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1755 1755
 
1756
-		$rowid=$this->id;
1756
+		$rowid = $this->id;
1757 1757
 
1758 1758
 		dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG);
1759 1759
 
@@ -1762,21 +1762,21 @@  discard block
 block discarded – undo
1762 1762
 
1763 1763
 		if ($test <= 0) return $test;
1764 1764
 
1765
-		$error=0;
1765
+		$error = 0;
1766 1766
 
1767 1767
 		$this->db->begin();
1768 1768
 
1769
-		if (! $error && ! $notrigger)
1769
+		if (!$error && !$notrigger)
1770 1770
 		{
1771 1771
             // Call trigger
1772
-            $result=$this->call_trigger('BILL_DELETE',$user);
1772
+            $result = $this->call_trigger('BILL_DELETE', $user);
1773 1773
             if ($result < 0) $error++;
1774 1774
             // End call triggers
1775 1775
 		}
1776 1776
 
1777 1777
 		// Removed extrafields
1778
-		if (! $error) {
1779
-			$result=$this->deleteExtraFields();
1778
+		if (!$error) {
1779
+			$result = $this->deleteExtraFields();
1780 1780
 			if ($result < 0)
1781 1781
 			{
1782 1782
 				$error++;
@@ -1784,52 +1784,52 @@  discard block
 block discarded – undo
1784 1784
 			}
1785 1785
 		}
1786 1786
 
1787
-		if (! $error)
1787
+		if (!$error)
1788 1788
 		{
1789 1789
 			// Delete linked object
1790 1790
 			$res = $this->deleteObjectLinked();
1791 1791
 			if ($res < 0) $error++;
1792 1792
 		}
1793 1793
 
1794
-		if (! $error)
1794
+		if (!$error)
1795 1795
 		{
1796 1796
 			// If invoice was converted into a discount not yet consumed, we remove discount
1797 1797
 			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
1798
-			$sql.= ' WHERE fk_facture_source = '.$rowid;
1799
-			$sql.= ' AND fk_facture_line IS NULL';
1800
-			$resql=$this->db->query($sql);
1798
+			$sql .= ' WHERE fk_facture_source = '.$rowid;
1799
+			$sql .= ' AND fk_facture_line IS NULL';
1800
+			$resql = $this->db->query($sql);
1801 1801
 
1802 1802
 			// If invoice has consumned discounts
1803 1803
 			$this->fetch_lines();
1804
-			$list_rowid_det=array();
1805
-			foreach($this->lines as $key => $invoiceline)
1804
+			$list_rowid_det = array();
1805
+			foreach ($this->lines as $key => $invoiceline)
1806 1806
 			{
1807
-				$list_rowid_det[]=$invoiceline->rowid;
1807
+				$list_rowid_det[] = $invoiceline->rowid;
1808 1808
 			}
1809 1809
 
1810 1810
 			// Consumned discounts are freed
1811 1811
 			if (count($list_rowid_det))
1812 1812
 			{
1813 1813
 				$sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
1814
-				$sql.= ' SET fk_facture = NULL, fk_facture_line = NULL';
1815
-				$sql.= ' WHERE fk_facture_line IN ('.join(',',$list_rowid_det).')';
1814
+				$sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
1815
+				$sql .= ' WHERE fk_facture_line IN ('.join(',', $list_rowid_det).')';
1816 1816
 
1817 1817
 				dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1818
-				if (! $this->db->query($sql))
1818
+				if (!$this->db->query($sql))
1819 1819
 				{
1820
-					$this->error=$this->db->error()." sql=".$sql;
1820
+					$this->error = $this->db->error()." sql=".$sql;
1821 1821
 					$this->db->rollback();
1822 1822
 					return -5;
1823 1823
 				}
1824 1824
 			}
1825 1825
 
1826 1826
 			// If we decrement stock on invoice validation, we increment
1827
-			if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse!=-1)
1827
+			if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1)
1828 1828
 			{
1829 1829
 				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1830 1830
 				$langs->load("agenda");
1831 1831
 
1832
-				$num=count($this->lines);
1832
+				$num = count($this->lines);
1833 1833
 				for ($i = 0; $i < $num; $i++)
1834 1834
 				{
1835 1835
 					if ($this->lines[$i]->fk_product > 0)
@@ -1837,8 +1837,8 @@  discard block
 block discarded – undo
1837 1837
 						$mouvP = new MouvementStock($this->db);
1838 1838
 						$mouvP->origin = &$this;
1839 1839
 						// We decrease stock for product
1840
-						if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr",$this->ref));
1841
-						else $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr",$this->ref));	// we use 0 for price, to not change the weighted average value
1840
+						if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
1841
+						else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
1842 1842
 					}
1843 1843
 				}
1844 1844
 			}
@@ -1855,31 +1855,31 @@  discard block
 block discarded – undo
1855 1855
 
1856 1856
 				dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1857 1857
 
1858
-				$resql=$this->db->query($sql);
1858
+				$resql = $this->db->query($sql);
1859 1859
 				if ($resql)
1860 1860
 				{
1861 1861
 					// On efface le repertoire de pdf provisoire
1862 1862
 					$ref = dol_sanitizeFileName($this->ref);
1863 1863
 					if ($conf->facture->dir_output && !empty($this->ref))
1864 1864
 					{
1865
-						$dir = $conf->facture->dir_output . "/" . $ref;
1866
-						$file = $conf->facture->dir_output . "/" . $ref . "/" . $ref . ".pdf";
1865
+						$dir = $conf->facture->dir_output."/".$ref;
1866
+						$file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
1867 1867
 						if (file_exists($file))	// We must delete all files before deleting directory
1868 1868
 						{
1869
-							$ret=dol_delete_preview($this);
1869
+							$ret = dol_delete_preview($this);
1870 1870
 
1871
-							if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1871
+							if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
1872 1872
 							{
1873
-								$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
1873
+								$this->error = $langs->trans("ErrorCanNotDeleteFile", $file);
1874 1874
 								$this->db->rollback();
1875 1875
 								return 0;
1876 1876
 							}
1877 1877
 						}
1878 1878
 						if (file_exists($dir))
1879 1879
 						{
1880
-							if (! dol_delete_dir_recursive($dir)) // For remove dir and meta
1880
+							if (!dol_delete_dir_recursive($dir)) // For remove dir and meta
1881 1881
 							{
1882
-								$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
1882
+								$this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
1883 1883
 								$this->db->rollback();
1884 1884
 								return 0;
1885 1885
 							}
@@ -1891,14 +1891,14 @@  discard block
 block discarded – undo
1891 1891
 				}
1892 1892
 				else
1893 1893
 				{
1894
-					$this->error=$this->db->lasterror()." sql=".$sql;
1894
+					$this->error = $this->db->lasterror()." sql=".$sql;
1895 1895
 					$this->db->rollback();
1896 1896
 					return -6;
1897 1897
 				}
1898 1898
 			}
1899 1899
 			else
1900 1900
 			{
1901
-				$this->error=$this->db->lasterror()." sql=".$sql;
1901
+				$this->error = $this->db->lasterror()." sql=".$sql;
1902 1902
 				$this->db->rollback();
1903 1903
 				return -4;
1904 1904
 			}
@@ -1919,9 +1919,9 @@  discard block
 block discarded – undo
1919 1919
 	 *	@param  string	$close_note	Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
1920 1920
 	 *  @return int         		<0 if KO, >0 if OK
1921 1921
 	 */
1922
-	function set_paid($user, $close_code='', $close_note='')
1922
+	function set_paid($user, $close_code = '', $close_note = '')
1923 1923
 	{
1924
-		$error=0;
1924
+		$error = 0;
1925 1925
 
1926 1926
 		if ($this->paye != 1)
1927 1927
 		{
@@ -1929,28 +1929,28 @@  discard block
 block discarded – undo
1929 1929
 
1930 1930
 			dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG);
1931 1931
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
1932
-			$sql.= ' fk_statut='.self::STATUS_CLOSED;
1933
-			if (! $close_code) $sql.= ', paye=1';
1934
-			if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
1935
-			if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
1936
-			$sql.= ' WHERE rowid = '.$this->id;
1932
+			$sql .= ' fk_statut='.self::STATUS_CLOSED;
1933
+			if (!$close_code) $sql .= ', paye=1';
1934
+			if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'";
1935
+			if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'";
1936
+			$sql .= ' WHERE rowid = '.$this->id;
1937 1937
 
1938 1938
 			dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
1939 1939
 			$resql = $this->db->query($sql);
1940 1940
 			if ($resql)
1941 1941
 			{
1942 1942
 	            // Call trigger
1943
-	            $result=$this->call_trigger('BILL_PAYED',$user);
1943
+	            $result = $this->call_trigger('BILL_PAYED', $user);
1944 1944
 	            if ($result < 0) $error++;
1945 1945
 	            // End call triggers
1946 1946
 			}
1947 1947
 			else
1948 1948
 			{
1949 1949
 				$error++;
1950
-				$this->error=$this->db->lasterror();
1950
+				$this->error = $this->db->lasterror();
1951 1951
 			}
1952 1952
 
1953
-			if (! $error)
1953
+			if (!$error)
1954 1954
 			{
1955 1955
 				$this->db->commit();
1956 1956
 				return 1;
@@ -1978,31 +1978,31 @@  discard block
 block discarded – undo
1978 1978
 	 */
1979 1979
 	function set_unpaid($user)
1980 1980
 	{
1981
-		$error=0;
1981
+		$error = 0;
1982 1982
 
1983 1983
 		$this->db->begin();
1984 1984
 
1985 1985
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
1986
-		$sql.= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null';
1987
-		$sql.= ' WHERE rowid = '.$this->id;
1986
+		$sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null';
1987
+		$sql .= ' WHERE rowid = '.$this->id;
1988 1988
 
1989 1989
 		dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1990 1990
 		$resql = $this->db->query($sql);
1991 1991
 		if ($resql)
1992 1992
 		{
1993 1993
             // Call trigger
1994
-            $result=$this->call_trigger('BILL_UNPAYED',$user);
1994
+            $result = $this->call_trigger('BILL_UNPAYED', $user);
1995 1995
             if ($result < 0) $error++;
1996 1996
             // End call triggers
1997 1997
 		}
1998 1998
 		else
1999 1999
 		{
2000 2000
 			$error++;
2001
-			$this->error=$this->db->error();
2001
+			$this->error = $this->db->error();
2002 2002
 			dol_print_error($this->db);
2003 2003
 		}
2004 2004
 
2005
-		if (! $error)
2005
+		if (!$error)
2006 2006
 		{
2007 2007
 			$this->db->commit();
2008 2008
 			return 1;
@@ -2025,7 +2025,7 @@  discard block
 block discarded – undo
2025 2025
 	 *	@param	string	$close_note		Comment
2026 2026
 	 *	@return int         			<0 if KO, >0 if OK
2027 2027
 	 */
2028
-	function set_canceled($user,$close_code='',$close_note='')
2028
+	function set_canceled($user, $close_code = '', $close_note = '')
2029 2029
 	{
2030 2030
 
2031 2031
 		dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG);
@@ -2033,10 +2033,10 @@  discard block
 block discarded – undo
2033 2033
 		$this->db->begin();
2034 2034
 
2035 2035
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2036
-		$sql.= ' fk_statut='.self::STATUS_ABANDONED;
2037
-		if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
2038
-		if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
2039
-		$sql.= ' WHERE rowid = '.$this->id;
2036
+		$sql .= ' fk_statut='.self::STATUS_ABANDONED;
2037
+		if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'";
2038
+		if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'";
2039
+		$sql .= ' WHERE rowid = '.$this->id;
2040 2040
 
2041 2041
 		$resql = $this->db->query($sql);
2042 2042
 		if ($resql)
@@ -2044,14 +2044,14 @@  discard block
 block discarded – undo
2044 2044
 			// On desaffecte de la facture les remises liees
2045 2045
 			// car elles n'ont pas ete utilisees vu que la facture est abandonnee.
2046 2046
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2047
-			$sql.= ' SET fk_facture = NULL';
2048
-			$sql.= ' WHERE fk_facture = '.$this->id;
2047
+			$sql .= ' SET fk_facture = NULL';
2048
+			$sql .= ' WHERE fk_facture = '.$this->id;
2049 2049
 
2050
-			$resql=$this->db->query($sql);
2050
+			$resql = $this->db->query($sql);
2051 2051
 			if ($resql)
2052 2052
 			{
2053 2053
 	            // Call trigger
2054
-	            $result=$this->call_trigger('BILL_CANCEL',$user);
2054
+	            $result = $this->call_trigger('BILL_CANCEL', $user);
2055 2055
 	            if ($result < 0)
2056 2056
 	            {
2057 2057
 					$this->db->rollback();
@@ -2064,14 +2064,14 @@  discard block
 block discarded – undo
2064 2064
 			}
2065 2065
 			else
2066 2066
 			{
2067
-				$this->error=$this->db->error()." sql=".$sql;
2067
+				$this->error = $this->db->error()." sql=".$sql;
2068 2068
 				$this->db->rollback();
2069 2069
 				return -1;
2070 2070
 			}
2071 2071
 		}
2072 2072
 		else
2073 2073
 		{
2074
-			$this->error=$this->db->error()." sql=".$sql;
2074
+			$this->error = $this->db->error()." sql=".$sql;
2075 2075
 			$this->db->rollback();
2076 2076
 			return -2;
2077 2077
 		}
@@ -2087,14 +2087,14 @@  discard block
 block discarded – undo
2087 2087
 	 * @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
2088 2088
      * @return	int						<0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK
2089 2089
 	 */
2090
-	function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
2090
+	function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
2091 2091
 	{
2092
-		global $conf,$langs;
2092
+		global $conf, $langs;
2093 2093
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2094 2094
 
2095
-		$now=dol_now();
2095
+		$now = dol_now();
2096 2096
 
2097
-		$error=0;
2097
+		$error = 0;
2098 2098
 		dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
2099 2099
 
2100 2100
 		// Force to have object complete for checks
@@ -2102,7 +2102,7 @@  discard block
 block discarded – undo
2102 2102
 		$this->fetch_lines();
2103 2103
 
2104 2104
 		// Check parameters
2105
-		if (! $this->brouillon)
2105
+		if (!$this->brouillon)
2106 2106
 		{
2107 2107
 			dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
2108 2108
 			return 0;
@@ -2110,13 +2110,13 @@  discard block
 block discarded – undo
2110 2110
 		if (count($this->lines) <= 0)
2111 2111
 		{
2112 2112
         	$langs->load("errors");
2113
-			$this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
2113
+			$this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
2114 2114
 			return -1;
2115 2115
 		}
2116 2116
 		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
2117
-       	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
2117
+       	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
2118 2118
 		{
2119
-			$this->error='Permission denied';
2119
+			$this->error = 'Permission denied';
2120 2120
 			dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
2121 2121
 			return -1;
2122 2122
 		}
@@ -2129,36 +2129,36 @@  discard block
 block discarded – undo
2129 2129
 			// Controle que facture source connue
2130 2130
 			if ($this->fk_facture_source <= 0)
2131 2131
 			{
2132
-				$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("InvoiceReplacement"));
2132
+				$this->error = $langs->trans("ErrorFieldRequired", $langs->trans("InvoiceReplacement"));
2133 2133
 				$this->db->rollback();
2134 2134
 				return -10;
2135 2135
 			}
2136 2136
 
2137 2137
 			// Charge la facture source a remplacer
2138
-			$facreplaced=new Facture($this->db);
2139
-			$result=$facreplaced->fetch($this->fk_facture_source);
2138
+			$facreplaced = new Facture($this->db);
2139
+			$result = $facreplaced->fetch($this->fk_facture_source);
2140 2140
 			if ($result <= 0)
2141 2141
 			{
2142
-				$this->error=$langs->trans("ErrorBadInvoice");
2142
+				$this->error = $langs->trans("ErrorBadInvoice");
2143 2143
 				$this->db->rollback();
2144 2144
 				return -11;
2145 2145
 			}
2146 2146
 
2147 2147
 			// Controle que facture source non deja remplacee par une autre
2148
-			$idreplacement=$facreplaced->getIdReplacingInvoice('validated');
2148
+			$idreplacement = $facreplaced->getIdReplacingInvoice('validated');
2149 2149
 			if ($idreplacement && $idreplacement != $this->id)
2150 2150
 			{
2151
-				$facreplacement=new Facture($this->db);
2151
+				$facreplacement = new Facture($this->db);
2152 2152
 				$facreplacement->fetch($idreplacement);
2153
-				$this->error=$langs->trans("ErrorInvoiceAlreadyReplaced",$facreplaced->ref,$facreplacement->ref);
2153
+				$this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
2154 2154
 				$this->db->rollback();
2155 2155
 				return -12;
2156 2156
 			}
2157 2157
 
2158
-			$result=$facreplaced->set_canceled($user,'replaced','');
2158
+			$result = $facreplaced->set_canceled($user, 'replaced', '');
2159 2159
 			if ($result < 0)
2160 2160
 			{
2161
-				$this->error=$facreplaced->error;
2161
+				$this->error = $facreplaced->error;
2162 2162
 				$this->db->rollback();
2163 2163
 				return -13;
2164 2164
 			}
@@ -2171,10 +2171,10 @@  discard block
 block discarded – undo
2171 2171
 		}
2172 2172
 		else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
2173 2173
 		{
2174
-			if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2174
+			if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2175 2175
 			{
2176
-				$this->date=dol_now();
2177
-				$this->date_lim_reglement=$this->calculate_date_lim_reglement();
2176
+				$this->date = dol_now();
2177
+				$this->date_lim_reglement = $this->calculate_date_lim_reglement();
2178 2178
 			}
2179 2179
 			$num = $this->getNextNumRef($this->thirdparty);
2180 2180
 		}
@@ -2190,41 +2190,41 @@  discard block
 block discarded – undo
2190 2190
 
2191 2191
 			// Validate
2192 2192
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2193
-			$sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
2194
-			if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2193
+			$sql .= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
2194
+			if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2195 2195
 			{
2196
-				$sql.= ", datef='".$this->db->idate($this->date)."'";
2197
-				$sql.= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
2196
+				$sql .= ", datef='".$this->db->idate($this->date)."'";
2197
+				$sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
2198 2198
 			}
2199
-			$sql.= ' WHERE rowid = '.$this->id;
2199
+			$sql .= ' WHERE rowid = '.$this->id;
2200 2200
 
2201 2201
 			dol_syslog(get_class($this)."::validate", LOG_DEBUG);
2202
-			$resql=$this->db->query($sql);
2203
-			if (! $resql)
2202
+			$resql = $this->db->query($sql);
2203
+			if (!$resql)
2204 2204
 			{
2205 2205
 				dol_print_error($this->db);
2206 2206
 				$error++;
2207 2207
 			}
2208 2208
 
2209 2209
 			// On verifie si la facture etait une provisoire
2210
-			if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref)))
2210
+			if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref)))
2211 2211
 			{
2212 2212
 				// La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
2213 2213
 			}
2214 2214
 
2215
-			if (! $error)
2215
+			if (!$error)
2216 2216
 			{
2217 2217
 				// Define third party as a customer
2218
-				$result=$this->thirdparty->set_as_client();
2218
+				$result = $this->thirdparty->set_as_client();
2219 2219
 
2220 2220
 				// Si active on decremente le produit principal et ses composants a la validation de facture
2221
-				if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0)
2221
+				if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0)
2222 2222
 				{
2223 2223
 					require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2224 2224
 					$langs->load("agenda");
2225 2225
 
2226 2226
 					// Loop on each line
2227
-					$cpt=count($this->lines);
2227
+					$cpt = count($this->lines);
2228 2228
 					for ($i = 0; $i < $cpt; $i++)
2229 2229
 					{
2230 2230
 						if ($this->lines[$i]->fk_product > 0)
@@ -2232,8 +2232,8 @@  discard block
 block discarded – undo
2232 2232
 							$mouvP = new MouvementStock($this->db);
2233 2233
 							$mouvP->origin = &$this;
2234 2234
 							// We decrease stock for product
2235
-							if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr",$num));
2236
-							else $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
2235
+							if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
2236
+							else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
2237 2237
 							if ($result < 0) {
2238 2238
 								$error++;
2239 2239
 							}
@@ -2243,15 +2243,15 @@  discard block
 block discarded – undo
2243 2243
 			}
2244 2244
 
2245 2245
 			// Trigger calls
2246
-			if (! $error && ! $notrigger)
2246
+			if (!$error && !$notrigger)
2247 2247
 			{
2248 2248
 	            // Call trigger
2249
-	            $result=$this->call_trigger('BILL_VALIDATE',$user);
2249
+	            $result = $this->call_trigger('BILL_VALIDATE', $user);
2250 2250
 	            if ($result < 0) $error++;
2251 2251
 	            // End call triggers
2252 2252
 			}
2253 2253
 
2254
-			if (! $error)
2254
+			if (!$error)
2255 2255
 			{
2256 2256
 				$this->oldref = $this->ref;
2257 2257
 
@@ -2272,13 +2272,13 @@  discard block
 block discarded – undo
2272 2272
 						{
2273 2273
 							dol_syslog("Rename ok");
2274 2274
 	                        // Rename docs starting with $oldref with $newref
2275
-	                        $listoffiles=dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
2276
-	                        foreach($listoffiles as $fileentry)
2275
+	                        $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
2276
+	                        foreach ($listoffiles as $fileentry)
2277 2277
 	                        {
2278
-	                        	$dirsource=$fileentry['name'];
2279
-	                        	$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
2280
-	                        	$dirsource=$fileentry['path'].'/'.$dirsource;
2281
-	                        	$dirdest=$fileentry['path'].'/'.$dirdest;
2278
+	                        	$dirsource = $fileentry['name'];
2279
+	                        	$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2280
+	                        	$dirsource = $fileentry['path'].'/'.$dirsource;
2281
+	                        	$dirdest = $fileentry['path'].'/'.$dirdest;
2282 2282
 	                        	@rename($dirsource, $dirdest);
2283 2283
 	                        }
2284 2284
 						}
@@ -2286,22 +2286,22 @@  discard block
 block discarded – undo
2286 2286
 				}
2287 2287
 			}
2288 2288
 
2289
-			if (! $error && !$this->is_last_in_cycle())
2289
+			if (!$error && !$this->is_last_in_cycle())
2290 2290
 			{
2291
-				if (! $this->updatePriceNextInvoice($langs))
2291
+				if (!$this->updatePriceNextInvoice($langs))
2292 2292
 				{
2293 2293
 					$error++;
2294 2294
 				}
2295 2295
 			}
2296 2296
 
2297 2297
 			// Set new ref and define current statut
2298
-			if (! $error)
2298
+			if (!$error)
2299 2299
 			{
2300 2300
 				$this->ref = $num;
2301
-				$this->facnumber=$num;
2302
-				$this->statut= self::STATUS_VALIDATED;
2303
-				$this->brouillon=0;
2304
-				$this->date_validation=$now;
2301
+				$this->facnumber = $num;
2302
+				$this->statut = self::STATUS_VALIDATED;
2303
+				$this->brouillon = 0;
2304
+				$this->date_validation = $now;
2305 2305
 				$i = 0;
2306 2306
 
2307 2307
                 if (!empty($conf->global->INVOICE_USE_SITUATION))
@@ -2323,7 +2323,7 @@  discard block
 block discarded – undo
2323 2323
 			$error++;
2324 2324
 		}
2325 2325
 
2326
-		if (! $error)
2326
+		if (!$error)
2327 2327
 		{
2328 2328
 			$this->db->commit();
2329 2329
 			return 1;
@@ -2381,11 +2381,11 @@  discard block
 block discarded – undo
2381 2381
 	 *	@param	int		$idwarehouse	Id warehouse to use for stock change.
2382 2382
 	 *	@return	int						<0 if KO, >0 if OK
2383 2383
 	 */
2384
-	function set_draft($user,$idwarehouse=-1)
2384
+	function set_draft($user, $idwarehouse = -1)
2385 2385
 	{
2386
-		global $conf,$langs;
2386
+		global $conf, $langs;
2387 2387
 
2388
-		$error=0;
2388
+		$error = 0;
2389 2389
 
2390 2390
 		if ($this->statut == self::STATUS_DRAFT)
2391 2391
 		{
@@ -2396,20 +2396,20 @@  discard block
 block discarded – undo
2396 2396
 		$this->db->begin();
2397 2397
 
2398 2398
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facture";
2399
-		$sql.= " SET fk_statut = ".self::STATUS_DRAFT;
2400
-		$sql.= " WHERE rowid = ".$this->id;
2399
+		$sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2400
+		$sql .= " WHERE rowid = ".$this->id;
2401 2401
 
2402 2402
 		dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
2403
-		$result=$this->db->query($sql);
2403
+		$result = $this->db->query($sql);
2404 2404
 		if ($result)
2405 2405
 		{
2406 2406
 			// Si on decremente le produit principal et ses composants a la validation de facture, on réincrement
2407
-			if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
2407
+			if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
2408 2408
 			{
2409 2409
 				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2410 2410
 				$langs->load("agenda");
2411 2411
 
2412
-				$num=count($this->lines);
2412
+				$num = count($this->lines);
2413 2413
 				for ($i = 0; $i < $num; $i++)
2414 2414
 				{
2415 2415
 					if ($this->lines[$i]->fk_product > 0)
@@ -2417,24 +2417,24 @@  discard block
 block discarded – undo
2417 2417
 						$mouvP = new MouvementStock($this->db);
2418 2418
 						$mouvP->origin = &$this;
2419 2419
 						// We decrease stock for product
2420
-						if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
2421
-						else $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));	// we use 0 for price, to not change the weighted average value
2420
+						if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
2421
+						else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
2422 2422
 					}
2423 2423
 				}
2424 2424
 			}
2425 2425
 
2426 2426
 			if ($error == 0)
2427 2427
 			{
2428
-				$old_statut=$this->statut;
2428
+				$old_statut = $this->statut;
2429 2429
 				$this->brouillon = 1;
2430 2430
 				$this->statut = self::STATUS_DRAFT;
2431 2431
 	            // Call trigger
2432
-	            $result=$this->call_trigger('BILL_UNVALIDATE',$user);
2432
+	            $result = $this->call_trigger('BILL_UNVALIDATE', $user);
2433 2433
 	            if ($result < 0)
2434 2434
 				{
2435 2435
 					$error++;
2436
-					$this->statut=$old_statut;
2437
-					$this->brouillon=0;
2436
+					$this->statut = $old_statut;
2437
+					$this->brouillon = 0;
2438 2438
 				}
2439 2439
 	            // End call triggers
2440 2440
 			} else {
@@ -2455,7 +2455,7 @@  discard block
 block discarded – undo
2455 2455
 		}
2456 2456
 		else
2457 2457
 		{
2458
-			$this->error=$this->db->error();
2458
+			$this->error = $this->db->error();
2459 2459
 			$this->db->rollback();
2460 2460
 			return -1;
2461 2461
 		}
@@ -2500,11 +2500,11 @@  discard block
 block discarded – undo
2500 2500
 	 * 		@param		double		$pu_ht_devise		Unit price in currency
2501 2501
 	 *    	@return    	int             				<0 if KO, Id of line if OK
2502 2502
 	 */
2503
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0)
2503
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = 0, $fk_remise_except = '', $price_base_type = 'HT', $pu_ttc = 0, $type = self::TYPE_STANDARD, $rang = -1, $special_code = 0, $origin = '', $origin_id = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = 0, $situation_percent = 100, $fk_prev_id = '', $fk_unit = null, $pu_ht_devise = 0)
2504 2504
 	{
2505 2505
 		// Deprecation warning
2506 2506
 		if ($label) {
2507
-			dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING);
2507
+			dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
2508 2508
 		}
2509 2509
 
2510 2510
 		global $mysoc, $conf, $langs;
@@ -2513,63 +2513,63 @@  discard block
 block discarded – undo
2513 2513
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2514 2514
 
2515 2515
 		// Clean parameters
2516
-		if (empty($remise_percent)) $remise_percent=0;
2517
-		if (empty($qty)) $qty=0;
2518
-		if (empty($info_bits)) $info_bits=0;
2519
-		if (empty($rang)) $rang=0;
2520
-		if (empty($ventil)) $ventil=0;
2521
-		if (empty($txtva)) $txtva=0;
2522
-		if (empty($txlocaltax1)) $txlocaltax1=0;
2523
-		if (empty($txlocaltax2)) $txlocaltax2=0;
2524
-		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
2516
+		if (empty($remise_percent)) $remise_percent = 0;
2517
+		if (empty($qty)) $qty = 0;
2518
+		if (empty($info_bits)) $info_bits = 0;
2519
+		if (empty($rang)) $rang = 0;
2520
+		if (empty($ventil)) $ventil = 0;
2521
+		if (empty($txtva)) $txtva = 0;
2522
+		if (empty($txlocaltax1)) $txlocaltax1 = 0;
2523
+		if (empty($txlocaltax2)) $txlocaltax2 = 0;
2524
+		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
2525 2525
 		if (empty($fk_prev_id)) $fk_prev_id = 'null';
2526
-		if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2526
+		if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2527 2527
 
2528
-		$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2528
+		$localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2529 2529
 
2530 2530
 		// Clean vat code
2531
-		$vat_src_code='';
2531
+		$vat_src_code = '';
2532 2532
 		if (preg_match('/\((.*)\)/', $txtva, $reg))
2533 2533
 		{
2534 2534
 		    $vat_src_code = $reg[1];
2535
-		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2535
+		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2536 2536
 		}
2537 2537
 
2538
-		$remise_percent=price2num($remise_percent);
2539
-		$qty=price2num($qty);
2540
-		$pu_ht=price2num($pu_ht);
2541
-		$pu_ttc=price2num($pu_ttc);
2542
-		$pa_ht=price2num($pa_ht);
2543
-		$txtva=price2num($txtva);
2544
-		$txlocaltax1=price2num($txlocaltax1);
2545
-		$txlocaltax2=price2num($txlocaltax2);
2538
+		$remise_percent = price2num($remise_percent);
2539
+		$qty = price2num($qty);
2540
+		$pu_ht = price2num($pu_ht);
2541
+		$pu_ttc = price2num($pu_ttc);
2542
+		$pa_ht = price2num($pa_ht);
2543
+		$txtva = price2num($txtva);
2544
+		$txlocaltax1 = price2num($txlocaltax1);
2545
+		$txlocaltax2 = price2num($txlocaltax2);
2546 2546
 
2547
-		if ($price_base_type=='HT')
2547
+		if ($price_base_type == 'HT')
2548 2548
 		{
2549
-			$pu=$pu_ht;
2549
+			$pu = $pu_ht;
2550 2550
 		}
2551 2551
 		else
2552 2552
 		{
2553
-			$pu=$pu_ttc;
2553
+			$pu = $pu_ttc;
2554 2554
 		}
2555 2555
 
2556 2556
 		// Check parameters
2557 2557
 		if ($type < 0) return -1;
2558 2558
 
2559
-		if (! empty($this->brouillon))
2559
+		if (!empty($this->brouillon))
2560 2560
 		{
2561 2561
 			$this->db->begin();
2562 2562
 
2563
-			$product_type=$type;
2563
+			$product_type = $type;
2564 2564
 			if (!empty($fk_product))
2565 2565
 			{
2566
-				$product=new Product($this->db);
2567
-				$result=$product->fetch($fk_product);
2568
-				$product_type=$product->type;
2566
+				$product = new Product($this->db);
2567
+				$result = $product->fetch($fk_product);
2568
+				$product_type = $product->type;
2569 2569
 
2570
-				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2570
+				if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2571 2571
                     $langs->load("errors");
2572
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2572
+				    $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2573 2573
 					$this->db->rollback();
2574 2574
 					return -3;
2575 2575
 				}
@@ -2590,7 +2590,7 @@  discard block
 block discarded – undo
2590 2590
 			$pu_ht = $tabprice[3];
2591 2591
 
2592 2592
 			// MultiCurrency
2593
-			$multicurrency_total_ht  = $tabprice[16];
2593
+			$multicurrency_total_ht = $tabprice[16];
2594 2594
             $multicurrency_total_tva = $tabprice[17];
2595 2595
             $multicurrency_total_ttc = $tabprice[18];
2596 2596
 			$pu_ht_devise = $tabprice[19];
@@ -2604,72 +2604,72 @@  discard block
 block discarded – undo
2604 2604
 			}
2605 2605
 
2606 2606
 			// Insert line
2607
-			$this->line=new FactureLigne($this->db);
2607
+			$this->line = new FactureLigne($this->db);
2608 2608
 
2609 2609
 			$this->line->context = $this->context;
2610 2610
 
2611
-			$this->line->fk_facture=$this->id;
2612
-			$this->line->label=$label;	// deprecated
2613
-			$this->line->desc=$desc;
2611
+			$this->line->fk_facture = $this->id;
2612
+			$this->line->label = $label; // deprecated
2613
+			$this->line->desc = $desc;
2614 2614
 
2615
-			$this->line->qty=            ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	    // For credit note, quantity is always positive and unit price negative
2616
-			$this->line->subprice=       ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
2615
+			$this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
2616
+			$this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
2617 2617
 
2618
-			$this->line->vat_src_code=$vat_src_code;
2619
-			$this->line->tva_tx=$txtva;
2620
-			$this->line->localtax1_tx=$txlocaltax1;
2621
-			$this->line->localtax2_tx=$txlocaltax2;
2618
+			$this->line->vat_src_code = $vat_src_code;
2619
+			$this->line->tva_tx = $txtva;
2620
+			$this->line->localtax1_tx = $txlocaltax1;
2621
+			$this->line->localtax2_tx = $txlocaltax2;
2622 2622
 			$this->line->localtax1_type = $localtaxes_type[0];
2623 2623
 			$this->line->localtax2_type = $localtaxes_type[2];
2624 2624
 
2625
-			$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
2626
-			$this->line->total_ttc=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);  // For credit note and if qty is negative, total is negative
2627
-			$this->line->total_tva=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva);  // For credit note and if qty is negative, total is negative
2628
-			$this->line->total_localtax1=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax1):$total_localtax1);  // For credit note and if qty is negative, total is negative
2629
-			$this->line->total_localtax2=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax2):$total_localtax2);  // For credit note and if qty is negative, total is negative
2630
-
2631
-			$this->line->fk_product=$fk_product;
2632
-			$this->line->product_type=$product_type;
2633
-			$this->line->remise_percent=$remise_percent;
2634
-			$this->line->date_start=$date_start;
2635
-			$this->line->date_end=$date_end;
2636
-			$this->line->ventil=$ventil;
2637
-			$this->line->rang=$rangtouse;
2638
-			$this->line->info_bits=$info_bits;
2639
-			$this->line->fk_remise_except=$fk_remise_except;
2640
-
2641
-			$this->line->special_code=$special_code;
2642
-			$this->line->fk_parent_line=$fk_parent_line;
2643
-			$this->line->origin=$origin;
2644
-			$this->line->origin_id=$origin_id;
2625
+			$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
2626
+			$this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative
2627
+			$this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva); // For credit note and if qty is negative, total is negative
2628
+			$this->line->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax1) : $total_localtax1); // For credit note and if qty is negative, total is negative
2629
+			$this->line->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax2) : $total_localtax2); // For credit note and if qty is negative, total is negative
2630
+
2631
+			$this->line->fk_product = $fk_product;
2632
+			$this->line->product_type = $product_type;
2633
+			$this->line->remise_percent = $remise_percent;
2634
+			$this->line->date_start = $date_start;
2635
+			$this->line->date_end = $date_end;
2636
+			$this->line->ventil = $ventil;
2637
+			$this->line->rang = $rangtouse;
2638
+			$this->line->info_bits = $info_bits;
2639
+			$this->line->fk_remise_except = $fk_remise_except;
2640
+
2641
+			$this->line->special_code = $special_code;
2642
+			$this->line->fk_parent_line = $fk_parent_line;
2643
+			$this->line->origin = $origin;
2644
+			$this->line->origin_id = $origin_id;
2645 2645
 			$this->line->situation_percent = $situation_percent;
2646 2646
 			$this->line->fk_prev_id = $fk_prev_id;
2647
-			$this->line->fk_unit=$fk_unit;
2647
+			$this->line->fk_unit = $fk_unit;
2648 2648
 
2649 2649
 			// infos marge
2650 2650
 			$this->line->fk_fournprice = $fk_fournprice;
2651 2651
 			$this->line->pa_ht = $pa_ht;
2652 2652
 
2653 2653
 			// Multicurrency
2654
-			$this->line->fk_multicurrency			= $this->fk_multicurrency;
2655
-			$this->line->multicurrency_code			= $this->multicurrency_code;
2654
+			$this->line->fk_multicurrency = $this->fk_multicurrency;
2655
+			$this->line->multicurrency_code = $this->multicurrency_code;
2656 2656
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
2657 2657
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
2658 2658
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2659 2659
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2660 2660
 
2661
-			if (is_array($array_options) && count($array_options)>0) {
2662
-				$this->line->array_options=$array_options;
2661
+			if (is_array($array_options) && count($array_options) > 0) {
2662
+				$this->line->array_options = $array_options;
2663 2663
 			}
2664 2664
 
2665
-			$result=$this->line->insert();
2665
+			$result = $this->line->insert();
2666 2666
 			if ($result > 0)
2667 2667
 			{
2668 2668
 				// Reorder if child line
2669
-				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2669
+				if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
2670 2670
 
2671 2671
 				// Mise a jour informations denormalisees au niveau de la facture meme
2672
-				$result=$this->update_price(1,'auto',0,$mysoc);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
2672
+				$result = $this->update_price(1, 'auto', 0, $mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
2673 2673
 				if ($result > 0)
2674 2674
 				{
2675 2675
 					$this->db->commit();
@@ -2677,14 +2677,14 @@  discard block
 block discarded – undo
2677 2677
 				}
2678 2678
 				else
2679 2679
 				{
2680
-					$this->error=$this->db->error();
2680
+					$this->error = $this->db->error();
2681 2681
 					$this->db->rollback();
2682 2682
 					return -1;
2683 2683
 				}
2684 2684
 			}
2685 2685
 			else
2686 2686
 			{
2687
-				$this->error=$this->line->error;
2687
+				$this->error = $this->line->error;
2688 2688
 				$this->db->rollback();
2689 2689
 				return -2;
2690 2690
 			}
@@ -2720,17 +2720,17 @@  discard block
 block discarded – undo
2720 2720
 	 * 	@param		int			$notrigger			disable line update trigger
2721 2721
 	 *  @return    	int             				< 0 if KO, > 0 if OK
2722 2722
 	 */
2723
-	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type= self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $situation_percent=100, $fk_unit = null, $pu_ht_devise = 0, $notrigger=0)
2723
+	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0)
2724 2724
 	{
2725
-		global $conf,$user;
2725
+		global $conf, $user;
2726 2726
 		// Deprecation warning
2727 2727
 		if ($label) {
2728
-			dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING);
2728
+			dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
2729 2729
 		}
2730 2730
 
2731 2731
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2732 2732
 
2733
-		global $mysoc,$langs;
2733
+		global $mysoc, $langs;
2734 2734
 
2735 2735
 		dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code fk_unit=$fk_unit", LOG_DEBUG);
2736 2736
 
@@ -2740,7 +2740,7 @@  discard block
 block discarded – undo
2740 2740
 			{
2741 2741
 				if (!$this->checkProgressLine($rowid, $situation_percent))
2742 2742
 				{
2743
-					if (!$this->error) $this->error=$langs->trans('invoiceLineProgressError');
2743
+					if (!$this->error) $this->error = $langs->trans('invoiceLineProgressError');
2744 2744
 					return -3;
2745 2745
 				}
2746 2746
 			}
@@ -2748,12 +2748,12 @@  discard block
 block discarded – undo
2748 2748
 			$this->db->begin();
2749 2749
 
2750 2750
 			// Clean parameters
2751
-			if (empty($qty)) $qty=0;
2752
-			if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
2753
-			if (empty($special_code) || $special_code == 3) $special_code=0;
2754
-			if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2751
+			if (empty($qty)) $qty = 0;
2752
+			if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
2753
+			if (empty($special_code) || $special_code == 3) $special_code = 0;
2754
+			if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2755 2755
 
2756
-			$remise_percent	= price2num($remise_percent);
2756
+			$remise_percent = price2num($remise_percent);
2757 2757
 			$qty			= price2num($qty);
2758 2758
 			$pu 			= price2num($pu);
2759 2759
 			$pa_ht			= price2num($pa_ht);
@@ -2768,29 +2768,29 @@  discard block
 block discarded – undo
2768 2768
 			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2769 2769
 			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2770 2770
 
2771
-			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
2771
+			$localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2772 2772
 
2773 2773
 			// Clean vat code
2774
-    		$vat_src_code='';
2774
+    		$vat_src_code = '';
2775 2775
     		if (preg_match('/\((.*)\)/', $txtva, $reg))
2776 2776
     		{
2777 2777
     		    $vat_src_code = $reg[1];
2778
-    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
2778
+    		    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2779 2779
     		}
2780 2780
 
2781
-			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
2781
+			$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
2782 2782
 
2783 2783
 			$total_ht  = $tabprice[0];
2784 2784
 			$total_tva = $tabprice[1];
2785 2785
 			$total_ttc = $tabprice[2];
2786
-			$total_localtax1=$tabprice[9];
2787
-			$total_localtax2=$tabprice[10];
2786
+			$total_localtax1 = $tabprice[9];
2787
+			$total_localtax2 = $tabprice[10];
2788 2788
 			$pu_ht  = $tabprice[3];
2789 2789
 			$pu_tva = $tabprice[4];
2790 2790
 			$pu_ttc = $tabprice[5];
2791 2791
 
2792 2792
 			// MultiCurrency
2793
-			$multicurrency_total_ht  = $tabprice[16];
2793
+			$multicurrency_total_ht = $tabprice[16];
2794 2794
             $multicurrency_total_tva = $tabprice[17];
2795 2795
             $multicurrency_total_ttc = $tabprice[18];
2796 2796
 			$pu_ht_devise = $tabprice[19];
@@ -2800,10 +2800,10 @@  discard block
 block discarded – undo
2800 2800
 			$remise = 0;
2801 2801
 			if ($remise_percent > 0)
2802 2802
 			{
2803
-				$remise = round(($pu * $remise_percent / 100),2);
2803
+				$remise = round(($pu * $remise_percent / 100), 2);
2804 2804
 				$price = ($pu - $remise);
2805 2805
 			}
2806
-			$price    = price2num($price);
2806
+			$price = price2num($price);
2807 2807
 
2808 2808
 			//Fetch current line from the database and then clone the object and set it in $oldline property
2809 2809
 			$line = new FactureLigne($this->db);
@@ -2811,13 +2811,13 @@  discard block
 block discarded – undo
2811 2811
 
2812 2812
 			if (!empty($line->fk_product))
2813 2813
 			{
2814
-				$product=new Product($this->db);
2815
-				$result=$product->fetch($line->fk_product);
2816
-				$product_type=$product->type;
2814
+				$product = new Product($this->db);
2815
+				$result = $product->fetch($line->fk_product);
2816
+				$product_type = $product->type;
2817 2817
 
2818
-				if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2818
+				if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
2819 2819
                     $langs->load("errors");
2820
-				    $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2820
+				    $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
2821 2821
 					$this->db->rollback();
2822 2822
 					return -3;
2823 2823
 				}
@@ -2830,7 +2830,7 @@  discard block
 block discarded – undo
2830 2830
             $this->line->context = $this->context;
2831 2831
 
2832 2832
 			// Reorder if fk_parent_line change
2833
-			if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2833
+			if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
2834 2834
 			{
2835 2835
 				$rangmax = $this->line_max($fk_parent_line);
2836 2836
 				$this->line->rang = $rangmax + 1;
@@ -2838,32 +2838,32 @@  discard block
 block discarded – undo
2838 2838
 
2839 2839
 			$this->line->rowid				= $rowid;
2840 2840
 			$this->line->label				= $label;
2841
-			$this->line->desc				= $desc;
2842
-			$this->line->qty				= ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	// For credit note, quantity is always positive and unit price negative
2841
+			$this->line->desc = $desc;
2842
+			$this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
2843 2843
 
2844
-			$this->line->vat_src_code       = $vat_src_code;
2845
-			$this->line->tva_tx				= $txtva;
2844
+			$this->line->vat_src_code = $vat_src_code;
2845
+			$this->line->tva_tx = $txtva;
2846 2846
 			$this->line->localtax1_tx		= $txlocaltax1;
2847 2847
 			$this->line->localtax2_tx		= $txlocaltax2;
2848 2848
 			$this->line->localtax1_type		= $localtaxes_type[0];
2849 2849
 			$this->line->localtax2_type		= $localtaxes_type[2];
2850 2850
 
2851 2851
 			$this->line->remise_percent		= $remise_percent;
2852
-			$this->line->subprice			= ($this->type==2?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
2853
-			$this->line->date_start			= $date_start;
2852
+			$this->line->subprice			= ($this->type == 2 ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
2853
+			$this->line->date_start = $date_start;
2854 2854
 			$this->line->date_end			= $date_end;
2855
-			$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
2856
-			$this->line->total_tva			= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva);
2855
+			$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
2856
+			$this->line->total_tva			= (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
2857 2857
 			$this->line->total_localtax1	= $total_localtax1;
2858 2858
 			$this->line->total_localtax2	= $total_localtax2;
2859
-			$this->line->total_ttc			= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc);
2859
+			$this->line->total_ttc			= (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
2860 2860
 			$this->line->info_bits			= $info_bits;
2861 2861
 			$this->line->special_code		= $special_code;
2862 2862
 			$this->line->product_type		= $type;
2863
-			$this->line->fk_parent_line		= $fk_parent_line;
2864
-			$this->line->skip_update_total	= $skip_update_total;
2865
-			$this->line->situation_percent  = $situation_percent;
2866
-			$this->line->fk_unit				= $fk_unit;
2863
+			$this->line->fk_parent_line = $fk_parent_line;
2864
+			$this->line->skip_update_total = $skip_update_total;
2865
+			$this->line->situation_percent = $situation_percent;
2866
+			$this->line->fk_unit = $fk_unit;
2867 2867
 
2868 2868
 			$this->line->fk_fournprice = $fk_fournprice;
2869 2869
 			$this->line->pa_ht = $pa_ht;
@@ -2874,15 +2874,15 @@  discard block
 block discarded – undo
2874 2874
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
2875 2875
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
2876 2876
 
2877
-			if (is_array($array_options) && count($array_options)>0) {
2878
-				$this->line->array_options=$array_options;
2877
+			if (is_array($array_options) && count($array_options) > 0) {
2878
+				$this->line->array_options = $array_options;
2879 2879
 			}
2880 2880
 
2881
-			$result=$this->line->update($user, $notrigger);
2881
+			$result = $this->line->update($user, $notrigger);
2882 2882
 			if ($result > 0)
2883 2883
 			{
2884 2884
 				// Reorder if child line
2885
-				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2885
+				if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
2886 2886
 
2887 2887
 				// Mise a jour info denormalisees au niveau facture
2888 2888
 				$this->update_price(1);
@@ -2891,14 +2891,14 @@  discard block
 block discarded – undo
2891 2891
 			}
2892 2892
 			else
2893 2893
 			{
2894
-			    $this->error=$this->line->error;
2894
+			    $this->error = $this->line->error;
2895 2895
 				$this->db->rollback();
2896 2896
 				return -1;
2897 2897
 			}
2898 2898
 		}
2899 2899
 		else
2900 2900
 		{
2901
-			$this->error="Invoice statut makes operation forbidden";
2901
+			$this->error = "Invoice statut makes operation forbidden";
2902 2902
 			return -2;
2903 2903
 		}
2904 2904
 	}
@@ -2918,9 +2918,9 @@  discard block
 block discarded – undo
2918 2918
 				AND f.fk_statut <> 0';
2919 2919
 
2920 2920
 		$result = $this->db->query($sql);
2921
-		if (! $result)
2921
+		if (!$result)
2922 2922
 		{
2923
-			$this->error=$this->db->error();
2923
+			$this->error = $this->db->error();
2924 2924
 			return false;
2925 2925
 		}
2926 2926
 
@@ -2939,9 +2939,9 @@  discard block
 block discarded – undo
2939 2939
 	 */
2940 2940
 	function update_percent($line, $percent)
2941 2941
 	{
2942
-	    global $mysoc,$user;
2942
+	    global $mysoc, $user;
2943 2943
 
2944
-		include_once(DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php');
2944
+		include_once(DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php');
2945 2945
 
2946 2946
 		// Cap percentages to 100
2947 2947
 		if ($percent > 100) $percent = 100;
@@ -2969,9 +2969,9 @@  discard block
 block discarded – undo
2969 2969
 
2970 2970
 		dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG);
2971 2971
 
2972
-		if (! $this->brouillon)
2972
+		if (!$this->brouillon)
2973 2973
 		{
2974
-			$this->error='ErrorBadStatus';
2974
+			$this->error = 'ErrorBadStatus';
2975 2975
 			return -1;
2976 2976
 		}
2977 2977
 
@@ -2979,29 +2979,29 @@  discard block
 block discarded – undo
2979 2979
 
2980 2980
 		// Libere remise liee a ligne de facture
2981 2981
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2982
-		$sql.= ' SET fk_facture_line = NULL';
2983
-		$sql.= ' WHERE fk_facture_line = '.$rowid;
2982
+		$sql .= ' SET fk_facture_line = NULL';
2983
+		$sql .= ' WHERE fk_facture_line = '.$rowid;
2984 2984
 
2985 2985
 		dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
2986 2986
 		$result = $this->db->query($sql);
2987
-		if (! $result)
2987
+		if (!$result)
2988 2988
 		{
2989
-			$this->error=$this->db->error();
2989
+			$this->error = $this->db->error();
2990 2990
 			$this->db->rollback();
2991 2991
 			return -1;
2992 2992
 		}
2993 2993
 
2994
-		$line=new FactureLigne($this->db);
2994
+		$line = new FactureLigne($this->db);
2995 2995
 
2996 2996
         $line->context = $this->context;
2997 2997
 
2998 2998
 		// For triggers
2999 2999
 		$result = $line->fetch($rowid);
3000
-		if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors);
3000
+		if (!($result > 0)) dol_print_error($db, $line->error, $line->errors);
3001 3001
 
3002 3002
 		if ($line->delete($user) > 0)
3003 3003
 		{
3004
-			$result=$this->update_price(1);
3004
+			$result = $this->update_price(1);
3005 3005
 
3006 3006
 			if ($result > 0)
3007 3007
 			{
@@ -3011,14 +3011,14 @@  discard block
 block discarded – undo
3011 3011
 			else
3012 3012
 			{
3013 3013
 				$this->db->rollback();
3014
-				$this->error=$this->db->lasterror();
3014
+				$this->error = $this->db->lasterror();
3015 3015
 				return -1;
3016 3016
 			}
3017 3017
 		}
3018 3018
 		else
3019 3019
 		{
3020 3020
 			$this->db->rollback();
3021
-			$this->error=$line->error;
3021
+			$this->error = $line->error;
3022 3022
 			return -1;
3023 3023
 		}
3024 3024
 	}
@@ -3031,41 +3031,41 @@  discard block
 block discarded – undo
3031 3031
 	 *  @param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3032 3032
 	 *	@return		int 		<0 if ko, >0 if ok
3033 3033
 	 */
3034
-	function set_remise($user, $remise, $notrigger=0)
3034
+	function set_remise($user, $remise, $notrigger = 0)
3035 3035
 	{
3036 3036
 		// Clean parameters
3037
-		if (empty($remise)) $remise=0;
3037
+		if (empty($remise)) $remise = 0;
3038 3038
 
3039 3039
 		if ($user->rights->facture->creer)
3040 3040
 		{
3041
-			$remise=price2num($remise);
3041
+			$remise = price2num($remise);
3042 3042
 
3043
-			$error=0;
3043
+			$error = 0;
3044 3044
 
3045 3045
 			$this->db->begin();
3046 3046
 
3047 3047
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3048
-			$sql.= ' SET remise_percent = '.$remise;
3049
-			$sql.= ' WHERE rowid = '.$this->id;
3050
-			$sql.= ' AND fk_statut = '.self::STATUS_DRAFT;
3048
+			$sql .= ' SET remise_percent = '.$remise;
3049
+			$sql .= ' WHERE rowid = '.$this->id;
3050
+			$sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
3051 3051
 
3052 3052
 			dol_syslog(__METHOD__, LOG_DEBUG);
3053
-			$resql=$this->db->query($sql);
3053
+			$resql = $this->db->query($sql);
3054 3054
 			if (!$resql)
3055 3055
 			{
3056
-				$this->errors[]=$this->db->error();
3056
+				$this->errors[] = $this->db->error();
3057 3057
 				$error++;
3058 3058
 			}
3059 3059
 
3060
-			if (! $notrigger && empty($error))
3060
+			if (!$notrigger && empty($error))
3061 3061
 			{
3062 3062
 				// Call trigger
3063
-				$result=$this->call_trigger('BILL_MODIFY',$user);
3063
+				$result = $this->call_trigger('BILL_MODIFY', $user);
3064 3064
 				if ($result < 0) $error++;
3065 3065
 				// End call triggers
3066 3066
 			}
3067 3067
 
3068
-			if (! $error)
3068
+			if (!$error)
3069 3069
 			{
3070 3070
 				$this->remise_percent = $remise;
3071 3071
 				$this->update_price(1);
@@ -3075,13 +3075,13 @@  discard block
 block discarded – undo
3075 3075
 			}
3076 3076
 			else
3077 3077
 			{
3078
-				foreach($this->errors as $errmsg)
3078
+				foreach ($this->errors as $errmsg)
3079 3079
 				{
3080 3080
 					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3081
-					$this->error.=($this->error?', '.$errmsg:$errmsg);
3081
+					$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3082 3082
 				}
3083 3083
 				$this->db->rollback();
3084
-				return -1*$error;
3084
+				return -1 * $error;
3085 3085
 			}
3086 3086
 		}
3087 3087
 	}
@@ -3095,60 +3095,60 @@  discard block
 block discarded – undo
3095 3095
 	 *  @param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
3096 3096
 	 *	@return		int 				<0 if KO, >0 if OK
3097 3097
 	 */
3098
-	function set_remise_absolue($user, $remise, $notrigger=0)
3098
+	function set_remise_absolue($user, $remise, $notrigger = 0)
3099 3099
 	{
3100
-		if (empty($remise)) $remise=0;
3100
+		if (empty($remise)) $remise = 0;
3101 3101
 
3102 3102
 		if ($user->rights->facture->creer)
3103 3103
 		{
3104
-			$error=0;
3104
+			$error = 0;
3105 3105
 
3106 3106
 			$this->db->begin();
3107 3107
 
3108
-			$remise=price2num($remise);
3108
+			$remise = price2num($remise);
3109 3109
 
3110 3110
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3111
-			$sql.= ' SET remise_absolue = '.$remise;
3112
-			$sql.= ' WHERE rowid = '.$this->id;
3113
-			$sql.= ' AND fk_statut = '.self::STATUS_DRAFT;
3111
+			$sql .= ' SET remise_absolue = '.$remise;
3112
+			$sql .= ' WHERE rowid = '.$this->id;
3113
+			$sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
3114 3114
 
3115 3115
 			dol_syslog(__METHOD__, LOG_DEBUG);
3116
-			$resql=$this->db->query($sql);
3116
+			$resql = $this->db->query($sql);
3117 3117
 			if (!$resql)
3118 3118
 			{
3119
-				$this->errors[]=$this->db->error();
3119
+				$this->errors[] = $this->db->error();
3120 3120
 				$error++;
3121 3121
 			}
3122 3122
 
3123
-			if (! $error)
3123
+			if (!$error)
3124 3124
 			{
3125
-				$this->oldcopy= clone $this;
3125
+				$this->oldcopy = clone $this;
3126 3126
 				$this->remise_absolue = $remise;
3127 3127
 				$this->update_price(1);
3128 3128
 			}
3129 3129
 
3130
-			if (! $notrigger && empty($error))
3130
+			if (!$notrigger && empty($error))
3131 3131
 			{
3132 3132
 				// Call trigger
3133
-				$result=$this->call_trigger('BILL_MODIFY',$user);
3133
+				$result = $this->call_trigger('BILL_MODIFY', $user);
3134 3134
 				if ($result < 0) $error++;
3135 3135
 				// End call triggers
3136 3136
 			}
3137 3137
 
3138
-			if (! $error)
3138
+			if (!$error)
3139 3139
 			{
3140 3140
 				$this->db->commit();
3141 3141
 				return 1;
3142 3142
 			}
3143 3143
 			else
3144 3144
 			{
3145
-				foreach($this->errors as $errmsg)
3145
+				foreach ($this->errors as $errmsg)
3146 3146
 				{
3147 3147
 					dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3148
-					$this->error.=($this->error?', '.$errmsg:$errmsg);
3148
+					$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3149 3149
 				}
3150 3150
 				$this->db->rollback();
3151
-				return -1*$error;
3151
+				return -1 * $error;
3152 3152
 			}
3153 3153
 		}
3154 3154
 	}
@@ -3159,41 +3159,41 @@  discard block
 block discarded – undo
3159 3159
 	 *	@param		string	$filtertype		1 to filter on type of payment == 'PRE'
3160 3160
 	 *  @return     array					Array with list of payments
3161 3161
 	 */
3162
-	function getListOfPayments($filtertype='')
3162
+	function getListOfPayments($filtertype = '')
3163 3163
 	{
3164
-		$retarray=array();
3164
+		$retarray = array();
3165 3165
 
3166
-		$table='paiement_facture';
3167
-		$table2='paiement';
3168
-		$field='fk_facture';
3169
-		$field2='fk_paiement';
3166
+		$table = 'paiement_facture';
3167
+		$table2 = 'paiement';
3168
+		$field = 'fk_facture';
3169
+		$field2 = 'fk_paiement';
3170 3170
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
3171 3171
 		{
3172
-			$table='paiementfourn_facturefourn';
3173
-			$table2='paiementfourn';
3174
-			$field='fk_facturefourn';
3175
-			$field2='fk_paiementfourn';
3172
+			$table = 'paiementfourn_facturefourn';
3173
+			$table2 = 'paiementfourn';
3174
+			$field = 'fk_facturefourn';
3175
+			$field2 = 'fk_paiementfourn';
3176 3176
 		}
3177 3177
 
3178 3178
 		$sql = 'SELECT pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code';
3179
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
3180
-		$sql.= ' WHERE pf.'.$field.' = '.$this->id;
3179
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
3180
+		$sql .= ' WHERE pf.'.$field.' = '.$this->id;
3181 3181
 		//$sql.= ' WHERE pf.'.$field.' = 1';
3182
-		$sql.= ' AND pf.'.$field2.' = p.rowid';
3183
-		$sql.= ' AND p.fk_paiement = t.id';
3184
-		$sql.= ' AND t.entity IN (' . getEntity('c_paiement').')';
3185
-		if ($filtertype) $sql.=" AND t.code='PRE'";
3182
+		$sql .= ' AND pf.'.$field2.' = p.rowid';
3183
+		$sql .= ' AND p.fk_paiement = t.id';
3184
+		$sql .= ' AND t.entity IN ('.getEntity('c_paiement').')';
3185
+		if ($filtertype) $sql .= " AND t.code='PRE'";
3186 3186
 
3187 3187
 		dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
3188
-		$resql=$this->db->query($sql);
3188
+		$resql = $this->db->query($sql);
3189 3189
 		if ($resql)
3190 3190
 		{
3191 3191
 			$num = $this->db->num_rows($resql);
3192
-			$i=0;
3192
+			$i = 0;
3193 3193
 			while ($i < $num)
3194 3194
 			{
3195 3195
 				$obj = $this->db->fetch_object($resql);
3196
-				$retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num);
3196
+				$retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num);
3197 3197
 				$i++;
3198 3198
 			}
3199 3199
 			$this->db->free($resql);
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
 		}
3202 3202
 		else
3203 3203
 		{
3204
-			$this->error=$this->db->lasterror();
3204
+			$this->error = $this->db->lasterror();
3205 3205
 			dol_print_error($this->db);
3206 3206
 			return array();
3207 3207
 		}
@@ -3216,21 +3216,21 @@  discard block
 block discarded – undo
3216 3216
 	 *      @param     string		$mode		'next' for next value or 'last' for last value
3217 3217
 	 *      @return    string					free ref or last ref
3218 3218
 	 */
3219
-	function getNextNumRef($soc,$mode='next')
3219
+	function getNextNumRef($soc, $mode = 'next')
3220 3220
 	{
3221 3221
 		global $conf, $langs;
3222 3222
 		$langs->load("bills");
3223 3223
 
3224 3224
 		// Clean parameters (if not defined or using deprecated value)
3225
-		if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON='mod_facture_terre';
3226
-		else if ($conf->global->FACTURE_ADDON=='terre') $conf->global->FACTURE_ADDON='mod_facture_terre';
3227
-		else if ($conf->global->FACTURE_ADDON=='mercure') $conf->global->FACTURE_ADDON='mod_facture_mercure';
3225
+		if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON = 'mod_facture_terre';
3226
+		else if ($conf->global->FACTURE_ADDON == 'terre') $conf->global->FACTURE_ADDON = 'mod_facture_terre';
3227
+		else if ($conf->global->FACTURE_ADDON == 'mercure') $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
3228 3228
 
3229
-		if (! empty($conf->global->FACTURE_ADDON))
3229
+		if (!empty($conf->global->FACTURE_ADDON))
3230 3230
 		{
3231 3231
 			dol_syslog("Call getNextNumRef with FACTURE_ADDON = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->nom.", type=".$soc->typent_code, LOG_DEBUG);
3232 3232
 
3233
-			$mybool=false;
3233
+			$mybool = false;
3234 3234
 
3235 3235
 			$file = $conf->global->FACTURE_ADDON.".php";
3236 3236
 			$classname = $conf->global->FACTURE_ADDON;
@@ -3245,16 +3245,16 @@  discard block
 block discarded – undo
3245 3245
 				// Load file with numbering class (if found)
3246 3246
 				if (is_file($dir.$file) && is_readable($dir.$file))
3247 3247
 				{
3248
-                    $mybool |= include_once $dir . $file;
3248
+                    $mybool |= include_once $dir.$file;
3249 3249
                 }
3250 3250
 			}
3251 3251
 
3252 3252
 			// For compatibility
3253
-			if (! $mybool)
3253
+			if (!$mybool)
3254 3254
 			{
3255 3255
 				$file = $conf->global->FACTURE_ADDON."/".$conf->global->FACTURE_ADDON.".modules.php";
3256 3256
 				$classname = "mod_facture_".$conf->global->FACTURE_ADDON;
3257
-				$classname = preg_replace('/\-.*$/','',$classname);
3257
+				$classname = preg_replace('/\-.*$/', '', $classname);
3258 3258
 				// Include file with class
3259 3259
 				foreach ($conf->file->dol_document_root as $dirroot)
3260 3260
 				{
@@ -3262,27 +3262,27 @@  discard block
 block discarded – undo
3262 3262
 
3263 3263
 					// Load file with numbering class (if found)
3264 3264
 					if (is_file($dir.$file) && is_readable($dir.$file)) {
3265
-                        $mybool |= include_once $dir . $file;
3265
+                        $mybool |= include_once $dir.$file;
3266 3266
                     }
3267 3267
 				}
3268 3268
 			}
3269 3269
 
3270
-			if (! $mybool)
3270
+			if (!$mybool)
3271 3271
 			{
3272
-				dol_print_error('',"Failed to include file ".$file);
3272
+				dol_print_error('', "Failed to include file ".$file);
3273 3273
 				return '';
3274 3274
 			}
3275 3275
 
3276 3276
 			$obj = new $classname();
3277 3277
 			$numref = "";
3278
-			$numref = $obj->getNextValue($soc,$this,$mode);
3278
+			$numref = $obj->getNextValue($soc, $this, $mode);
3279 3279
 
3280 3280
 			/**
3281 3281
 			 * $numref can be empty in case we ask for the last value because if there is no invoice created with the
3282 3282
 			 * set up mask.
3283 3283
 			 */
3284 3284
 			if ($mode != 'last' && !$numref) {
3285
-				$this->error=$obj->error;
3285
+				$this->error = $obj->error;
3286 3286
 				//dol_print_error($this->db,"Facture::getNextNumRef ".$obj->error);
3287 3287
 				return "";
3288 3288
 			}
@@ -3306,11 +3306,11 @@  discard block
 block discarded – undo
3306 3306
 	function info($id)
3307 3307
 	{
3308 3308
 		$sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
3309
-		$sql.= ' fk_user_author, fk_user_valid';
3310
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'facture as c';
3311
-		$sql.= ' WHERE c.rowid = '.$id;
3309
+		$sql .= ' fk_user_author, fk_user_valid';
3310
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
3311
+		$sql .= ' WHERE c.rowid = '.$id;
3312 3312
 
3313
-		$result=$this->db->query($sql);
3313
+		$result = $this->db->query($sql);
3314 3314
 		if ($result)
3315 3315
 		{
3316 3316
 			if ($this->db->num_rows($result))
@@ -3321,7 +3321,7 @@  discard block
 block discarded – undo
3321 3321
 				{
3322 3322
 					$cuser = new User($this->db);
3323 3323
 					$cuser->fetch($obj->fk_user_author);
3324
-					$this->user_creation     = $cuser;
3324
+					$this->user_creation = $cuser;
3325 3325
 				}
3326 3326
 				if ($obj->fk_user_valid)
3327 3327
 				{
@@ -3331,7 +3331,7 @@  discard block
 block discarded – undo
3331 3331
 				}
3332 3332
 				$this->date_creation     = $this->db->jdate($obj->datec);
3333 3333
 				$this->date_modification = $this->db->jdate($obj->datem);
3334
-				$this->date_validation   = $this->db->jdate($obj->datev);	// Should be in log table
3334
+				$this->date_validation   = $this->db->jdate($obj->datev); // Should be in log table
3335 3335
 			}
3336 3336
 			$this->db->free($result);
3337 3337
 		}
@@ -3349,11 +3349,11 @@  discard block
 block discarded – undo
3349 3349
 	function getVentilExportCompta()
3350 3350
 	{
3351 3351
 		// On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
3352
-		$ventilExportCompta = 0 ;
3353
-		$num=count($this->lines);
3352
+		$ventilExportCompta = 0;
3353
+		$num = count($this->lines);
3354 3354
 		for ($i = 0; $i < $num; $i++)
3355 3355
 		{
3356
-			if (! empty($this->lines[$i]->export_compta) && ! empty($this->lines[$i]->code_ventilation))
3356
+			if (!empty($this->lines[$i]->export_compta) && !empty($this->lines[$i]->code_ventilation))
3357 3357
 			{
3358 3358
 				$ventilExportCompta++;
3359 3359
 			}
@@ -3391,8 +3391,8 @@  discard block
 block discarded – undo
3391 3391
 			return 1;
3392 3392
 		}
3393 3393
 
3394
-		if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2;
3395
-		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED))  return 0;
3394
+		if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2;
3395
+		if (!empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED))  return 0;
3396 3396
 
3397 3397
 		// TODO Test if there is at least one payment. If yes, refuse to delete.
3398 3398
 		// ...
@@ -3403,7 +3403,7 @@  discard block
 block discarded – undo
3403 3403
 			// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
3404 3404
 			if (empty($this->thirdparty)) $this->fetch_thirdparty();
3405 3405
 
3406
-			$maxfacnumber = $this->getNextNumRef($this->thirdparty,'last');
3406
+			$maxfacnumber = $this->getNextNumRef($this->thirdparty, 'last');
3407 3407
 			$ventilExportCompta = $this->getVentilExportCompta();
3408 3408
 
3409 3409
 			// If there is no invoice into the reset range and not already dispatched, we can delete
@@ -3434,30 +3434,30 @@  discard block
 block discarded – undo
3434 3434
 	 *  @param    	string	$sortorder		Sort order
3435 3435
 	 *  @return     int             		-1 if KO, array with result if OK
3436 3436
 	 */
3437
-	function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='f.datef,f.rowid', $sortorder='DESC')
3437
+	function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
3438 3438
 	{
3439
-		global $conf,$user;
3439
+		global $conf, $user;
3440 3440
 
3441 3441
 		$ga = array();
3442 3442
 
3443 3443
 		$sql = "SELECT s.rowid, s.nom as name, s.client,";
3444
-		$sql.= " f.rowid as fid, f.facnumber as ref, f.datef as df";
3445
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
3446
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
3447
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3448
-		$sql.= " WHERE f.entity = ".$conf->entity;
3449
-		$sql.= " AND f.fk_soc = s.rowid";
3450
-		if (! $user->rights->societe->client->voir && ! $socid) //restriction
3444
+		$sql .= " f.rowid as fid, f.facnumber as ref, f.datef as df";
3445
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
3446
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
3447
+		if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3448
+		$sql .= " WHERE f.entity = ".$conf->entity;
3449
+		$sql .= " AND f.fk_soc = s.rowid";
3450
+		if (!$user->rights->societe->client->voir && !$socid) //restriction
3451 3451
 		{
3452
-			$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
3452
+			$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
3453 3453
 		}
3454
-		if ($socid) $sql.= " AND s.rowid = ".$socid;
3455
-		if ($draft) $sql.= " AND f.fk_statut = ".self::STATUS_DRAFT;
3456
-		if (is_object($excluser)) $sql.= " AND f.fk_user_author <> ".$excluser->id;
3457
-		$sql.= $this->db->order($sortfield,$sortorder);
3458
-		$sql.= $this->db->plimit($limit,$offset);
3454
+		if ($socid) $sql .= " AND s.rowid = ".$socid;
3455
+		if ($draft) $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
3456
+		if (is_object($excluser)) $sql .= " AND f.fk_user_author <> ".$excluser->id;
3457
+		$sql .= $this->db->order($sortfield, $sortorder);
3458
+		$sql .= $this->db->plimit($limit, $offset);
3459 3459
 
3460
-		$result=$this->db->query($sql);
3460
+		$result = $this->db->query($sql);
3461 3461
 		if ($result)
3462 3462
 		{
3463 3463
 			$numc = $this->db->num_rows($result);
@@ -3478,7 +3478,7 @@  discard block
 block discarded – undo
3478 3478
 					}
3479 3479
 					else
3480 3480
 					{
3481
-						$ga[$i]['id']	= $obj->fid;
3481
+						$ga[$i]['id'] = $obj->fid;
3482 3482
 						$ga[$i]['ref'] 	= $obj->ref;
3483 3483
 						$ga[$i]['name'] = $obj->name;
3484 3484
 					}
@@ -3502,32 +3502,32 @@  discard block
 block discarded – undo
3502 3502
 	 *	@param		int		$socid		Id societe
3503 3503
 	 *	@return    	array				Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
3504 3504
 	 */
3505
-	function list_replacable_invoices($socid=0)
3505
+	function list_replacable_invoices($socid = 0)
3506 3506
 	{
3507 3507
 		global $conf;
3508 3508
 
3509 3509
 		$return = array();
3510 3510
 
3511 3511
 		$sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut,";
3512
-		$sql.= " ff.rowid as rowidnext";
3513
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
3514
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3515
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
3516
-		$sql.= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
3517
-		$sql.= " AND f.entity = ".$conf->entity;
3518
-		$sql.= " AND f.paye = 0";					// Pas classee payee completement
3519
-		$sql.= " AND pf.fk_paiement IS NULL";		// Aucun paiement deja fait
3520
-		$sql.= " AND ff.fk_statut IS NULL";			// Renvoi vrai si pas facture de remplacement
3521
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
3522
-		$sql.= " ORDER BY f.facnumber";
3512
+		$sql .= " ff.rowid as rowidnext";
3513
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3514
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3515
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
3516
+		$sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
3517
+		$sql .= " AND f.entity = ".$conf->entity;
3518
+		$sql .= " AND f.paye = 0"; // Pas classee payee completement
3519
+		$sql .= " AND pf.fk_paiement IS NULL"; // Aucun paiement deja fait
3520
+		$sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
3521
+		if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
3522
+		$sql .= " ORDER BY f.facnumber";
3523 3523
 
3524 3524
 		dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
3525
-		$resql=$this->db->query($sql);
3525
+		$resql = $this->db->query($sql);
3526 3526
 		if ($resql)
3527 3527
 		{
3528
-			while ($obj=$this->db->fetch_object($resql))
3528
+			while ($obj = $this->db->fetch_object($resql))
3529 3529
 			{
3530
-				$return[$obj->rowid]=array(	'id' => $obj->rowid,
3530
+				$return[$obj->rowid] = array('id' => $obj->rowid,
3531 3531
 				'ref' => $obj->facnumber,
3532 3532
 				'status' => $obj->fk_statut);
3533 3533
 			}
@@ -3536,7 +3536,7 @@  discard block
 block discarded – undo
3536 3536
 		}
3537 3537
 		else
3538 3538
 		{
3539
-			$this->error=$this->db->error();
3539
+			$this->error = $this->db->error();
3540 3540
 			return -1;
3541 3541
 		}
3542 3542
 	}
@@ -3550,40 +3550,40 @@  discard block
 block discarded – undo
3550 3550
 	 *	@param		int		$socid		Id societe
3551 3551
 	 *	@return    	array				Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
3552 3552
 	 */
3553
-	function list_qualified_avoir_invoices($socid=0)
3553
+	function list_qualified_avoir_invoices($socid = 0)
3554 3554
 	{
3555 3555
 		global $conf;
3556 3556
 
3557 3557
 		$return = array();
3558 3558
 
3559 3559
 		$sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut, f.type, f.paye, pf.fk_paiement";
3560
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
3561
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3562
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
3563
-		$sql.= " WHERE f.entity = ".$conf->entity;
3564
-		$sql.= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
3560
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3561
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3562
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
3563
+		$sql .= " WHERE f.entity = ".$conf->entity;
3564
+		$sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
3565 3565
 		//  $sql.= " WHERE f.fk_statut >= 1";
3566 3566
 		//	$sql.= " AND (f.paye = 1";				// Classee payee completement
3567 3567
 		//	$sql.= " OR f.close_code IS NOT NULL)";	// Classee payee partiellement
3568
-		$sql.= " AND ff.type IS NULL";			// Renvoi vrai si pas facture de remplacement
3569
-		$sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE;				// Type non 2 si facture non avoir
3570
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
3571
-		$sql.= " ORDER BY f.facnumber";
3568
+		$sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
3569
+		$sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
3570
+		if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
3571
+		$sql .= " ORDER BY f.facnumber";
3572 3572
 
3573 3573
 		dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
3574
-		$resql=$this->db->query($sql);
3574
+		$resql = $this->db->query($sql);
3575 3575
 		if ($resql)
3576 3576
 		{
3577
-			while ($obj=$this->db->fetch_object($resql))
3577
+			while ($obj = $this->db->fetch_object($resql))
3578 3578
 			{
3579
-				$qualified=0;
3580
-				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified=1;
3581
-				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified=1;
3579
+				$qualified = 0;
3580
+				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1;
3581
+				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1;
3582 3582
 				if ($qualified)
3583 3583
 				{
3584 3584
 					//$ref=$obj->facnumber;
3585
-					$paymentornot=($obj->fk_paiement?1:0);
3586
-					$return[$obj->rowid]=array('ref'=>$obj->facnumber,'status'=>$obj->fk_statut,'type'=>$obj->type,'paye'=>$obj->paye,'paymentornot'=>$paymentornot);
3585
+					$paymentornot = ($obj->fk_paiement ? 1 : 0);
3586
+					$return[$obj->rowid] = array('ref'=>$obj->facnumber, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
3587 3587
 				}
3588 3588
 			}
3589 3589
 
@@ -3591,7 +3591,7 @@  discard block
 block discarded – undo
3591 3591
 		}
3592 3592
 		else
3593 3593
 		{
3594
-			$this->error=$this->db->error();
3594
+			$this->error = $this->db->error();
3595 3595
 			return -1;
3596 3596
 		}
3597 3597
 	}
@@ -3605,34 +3605,34 @@  discard block
 block discarded – undo
3605 3605
 	 *  @param		float	$amount		Amount we request direct debit for
3606 3606
 	 *	@return     int         		<0 if KO, >0 if OK
3607 3607
 	 */
3608
-	function demande_prelevement($fuser, $amount=0)
3608
+	function demande_prelevement($fuser, $amount = 0)
3609 3609
 	{
3610 3610
 
3611
-		$error=0;
3611
+		$error = 0;
3612 3612
 
3613 3613
 		dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
3614 3614
 
3615 3615
 		if ($this->statut > self::STATUS_DRAFT && $this->paye == 0)
3616 3616
 		{
3617
-	        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
3617
+	        require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3618 3618
 	        $bac = new CompanyBankAccount($this->db);
3619
-	        $bac->fetch(0,$this->socid);
3619
+	        $bac->fetch(0, $this->socid);
3620 3620
 
3621 3621
         	$sql = 'SELECT count(*)';
3622
-			$sql.= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
3623
-			$sql.= ' WHERE fk_facture = '.$this->id;
3624
-			$sql.= ' AND traite = 0';
3622
+			$sql .= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
3623
+			$sql .= ' WHERE fk_facture = '.$this->id;
3624
+			$sql .= ' AND traite = 0';
3625 3625
 
3626 3626
 			dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
3627
-			$resql=$this->db->query($sql);
3627
+			$resql = $this->db->query($sql);
3628 3628
 			if ($resql)
3629 3629
 			{
3630 3630
 				$row = $this->db->fetch_row($resql);
3631 3631
 				if ($row[0] == 0)
3632 3632
 				{
3633
-					$now=dol_now();
3633
+					$now = dol_now();
3634 3634
 
3635
-                    $totalpaye  = $this->getSommePaiement();
3635
+                    $totalpaye = $this->getSommePaiement();
3636 3636
                     $totalcreditnotes = $this->getSumCreditNotesUsed();
3637 3637
                     $totaldeposits = $this->getSumDepositsUsed();
3638 3638
                     //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
@@ -3641,7 +3641,7 @@  discard block
 block discarded – undo
3641 3641
                     // For example print 239.2 - 229.3 - 9.9; does not return 0.
3642 3642
                     //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
3643 3643
                     //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3644
-					if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
3644
+					if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
3645 3645
 
3646 3646
 					if (is_numeric($amount) && $amount != 0)
3647 3647
 					{
@@ -3657,28 +3657,28 @@  discard block
 block discarded – undo
3657 3657
 						$sql .= ",'".$bac->cle_rib."')";
3658 3658
 
3659 3659
 						dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
3660
-						$resql=$this->db->query($sql);
3661
-						if (! $resql)
3660
+						$resql = $this->db->query($sql);
3661
+						if (!$resql)
3662 3662
 						{
3663
-						    $this->error=$this->db->lasterror();
3663
+						    $this->error = $this->db->lasterror();
3664 3664
 						    dol_syslog(get_class($this).'::demandeprelevement Erreur');
3665 3665
 						    $error++;
3666 3666
 						}
3667 3667
 					}
3668 3668
 					else
3669 3669
 					{
3670
-						$this->error='WithdrawRequestErrorNilAmount';
3670
+						$this->error = 'WithdrawRequestErrorNilAmount';
3671 3671
 	                    dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
3672 3672
 	                    $error++;
3673 3673
 					}
3674 3674
 
3675
-        			if (! $error)
3675
+        			if (!$error)
3676 3676
         			{
3677 3677
         				// Force payment mode of invoice to withdraw
3678 3678
         				$payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1);
3679 3679
         				if ($payment_mode_id > 0)
3680 3680
         				{
3681
-        					$result=$this->setPaymentMethods($payment_mode_id);
3681
+        					$result = $this->setPaymentMethods($payment_mode_id);
3682 3682
         				}
3683 3683
         			}
3684 3684
 
@@ -3687,21 +3687,21 @@  discard block
 block discarded – undo
3687 3687
                 }
3688 3688
                 else
3689 3689
                 {
3690
-                    $this->error="A request already exists";
3690
+                    $this->error = "A request already exists";
3691 3691
                     dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
3692 3692
                     return 0;
3693 3693
                 }
3694 3694
             }
3695 3695
             else
3696 3696
             {
3697
-                $this->error=$this->db->error();
3697
+                $this->error = $this->db->error();
3698 3698
                 dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
3699 3699
                 return -2;
3700 3700
             }
3701 3701
         }
3702 3702
         else
3703 3703
         {
3704
-            $this->error="Status of invoice does not allow this";
3704
+            $this->error = "Status of invoice does not allow this";
3705 3705
             dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
3706 3706
             return -3;
3707 3707
         }
@@ -3719,13 +3719,13 @@  discard block
 block discarded – undo
3719 3719
 		$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
3720 3720
 		$sql .= ' WHERE rowid = '.$did;
3721 3721
 		$sql .= ' AND traite = 0';
3722
-		if ( $this->db->query($sql) )
3722
+		if ($this->db->query($sql))
3723 3723
 		{
3724 3724
 			return 0;
3725 3725
 		}
3726 3726
 		else
3727 3727
 		{
3728
-			$this->error=$this->db->lasterror();
3728
+			$this->error = $this->db->lasterror();
3729 3729
 			dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
3730 3730
 			return -1;
3731 3731
 		}
@@ -3745,33 +3745,33 @@  discard block
 block discarded – undo
3745 3745
 		$clause = " WHERE";
3746 3746
 
3747 3747
 		$sql = "SELECT f.rowid, f.date_lim_reglement as datefin,f.fk_statut";
3748
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
3748
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3749 3749
 		if (!$user->rights->societe->client->voir && !$user->societe_id)
3750 3750
 		{
3751
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
3752
-			$sql.= " WHERE sc.fk_user = " .$user->id;
3751
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
3752
+			$sql .= " WHERE sc.fk_user = ".$user->id;
3753 3753
 			$clause = " AND";
3754 3754
 		}
3755
-		$sql.= $clause." f.paye=0";
3756
-		$sql.= " AND f.entity = ".$conf->entity;
3757
-		$sql.= " AND f.fk_statut = ".self::STATUS_VALIDATED;
3758
-		if ($user->societe_id) $sql.= " AND f.fk_soc = ".$user->societe_id;
3755
+		$sql .= $clause." f.paye=0";
3756
+		$sql .= " AND f.entity = ".$conf->entity;
3757
+		$sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
3758
+		if ($user->societe_id) $sql .= " AND f.fk_soc = ".$user->societe_id;
3759 3759
 
3760
-		$resql=$this->db->query($sql);
3760
+		$resql = $this->db->query($sql);
3761 3761
 		if ($resql)
3762 3762
 		{
3763 3763
 			$langs->load("bills");
3764
-			$now=dol_now();
3764
+			$now = dol_now();
3765 3765
 
3766 3766
 			$response = new WorkboardResponse();
3767
-			$response->warning_delay=$conf->facture->client->warning_delay/60/60/24;
3768
-			$response->label=$langs->trans("CustomerBillsUnpaid");
3769
-			$response->url=DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=customers_bills';
3770
-			$response->img=img_object('',"bill");
3767
+			$response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
3768
+			$response->label = $langs->trans("CustomerBillsUnpaid");
3769
+			$response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=customers_bills';
3770
+			$response->img = img_object('', "bill");
3771 3771
 
3772 3772
 			$generic_facture = new Facture($this->db);
3773 3773
 
3774
-			while ($obj=$this->db->fetch_object($resql))
3774
+			while ($obj = $this->db->fetch_object($resql))
3775 3775
 			{
3776 3776
 				$generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
3777 3777
 				$generic_facture->statut = $obj->fk_statut;
@@ -3788,7 +3788,7 @@  discard block
 block discarded – undo
3788 3788
 		else
3789 3789
 		{
3790 3790
 			dol_print_error($this->db);
3791
-			$this->error=$this->db->error();
3791
+			$this->error = $this->db->error();
3792 3792
 			return -1;
3793 3793
 		}
3794 3794
 	}
@@ -3803,7 +3803,7 @@  discard block
 block discarded – undo
3803 3803
 	 */
3804 3804
 	function getIdBillingContact()
3805 3805
 	{
3806
-		return $this->getIdContact('external','BILLING');
3806
+		return $this->getIdContact('external', 'BILLING');
3807 3807
 	}
3808 3808
 
3809 3809
 	/**
@@ -3813,7 +3813,7 @@  discard block
 block discarded – undo
3813 3813
 	 */
3814 3814
 	function getIdShippingContact()
3815 3815
 	{
3816
-		return $this->getIdContact('external','SHIPPING');
3816
+		return $this->getIdContact('external', 'SHIPPING');
3817 3817
 	}
3818 3818
 
3819 3819
 
@@ -3825,20 +3825,20 @@  discard block
 block discarded – undo
3825 3825
 	 *	@param	string		$option		''=Create a specimen invoice with lines, 'nolines'=No lines
3826 3826
 	 *  @return	void
3827 3827
 	 */
3828
-	function initAsSpecimen($option='')
3828
+	function initAsSpecimen($option = '')
3829 3829
 	{
3830 3830
 		global $langs;
3831 3831
 
3832
-		$now=dol_now();
3833
-		$arraynow=dol_getdate($now);
3834
-		$nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
3832
+		$now = dol_now();
3833
+		$arraynow = dol_getdate($now);
3834
+		$nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
3835 3835
 
3836 3836
         // Load array of products prodids
3837 3837
 		$num_prods = 0;
3838 3838
 		$prodids = array();
3839 3839
 		$sql = "SELECT rowid";
3840
-		$sql.= " FROM ".MAIN_DB_PREFIX."product";
3841
-		$sql.= " WHERE entity IN (".getEntity('product').")";
3840
+		$sql .= " FROM ".MAIN_DB_PREFIX."product";
3841
+		$sql .= " WHERE entity IN (".getEntity('product').")";
3842 3842
 		$resql = $this->db->query($sql);
3843 3843
 		if ($resql)
3844 3844
 		{
@@ -3853,26 +3853,26 @@  discard block
 block discarded – undo
3853 3853
 		}
3854 3854
 		//Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
3855 3855
 		if (empty($num_prods)) {
3856
-			$num_prods=1;
3856
+			$num_prods = 1;
3857 3857
 		}
3858 3858
 
3859 3859
 		// Initialize parameters
3860
-		$this->id=0;
3860
+		$this->id = 0;
3861 3861
 		$this->ref = 'SPECIMEN';
3862
-		$this->specimen=1;
3862
+		$this->specimen = 1;
3863 3863
 		$this->socid = 1;
3864 3864
 		$this->date = $nownotime;
3865
-		$this->date_lim_reglement = $nownotime + 3600 * 24 *30;
3865
+		$this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
3866 3866
 		$this->cond_reglement_id   = 1;
3867 3867
 		$this->cond_reglement_code = 'RECEP';
3868
-		$this->date_lim_reglement=$this->calculate_date_lim_reglement();
3869
-		$this->mode_reglement_id   = 0;		// Not forced to show payment mode CHQ + VIR
3870
-		$this->mode_reglement_code = '';	// Not forced to show payment mode CHQ + VIR
3871
-		$this->note_public='This is a comment (public)';
3872
-		$this->note_private='This is a comment (private)';
3873
-		$this->note='This is a comment (private)';
3874
-		$this->fk_incoterms=0;
3875
-		$this->location_incoterms='';
3868
+		$this->date_lim_reglement = $this->calculate_date_lim_reglement();
3869
+		$this->mode_reglement_id   = 0; // Not forced to show payment mode CHQ + VIR
3870
+		$this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
3871
+		$this->note_public = 'This is a comment (public)';
3872
+		$this->note_private = 'This is a comment (private)';
3873
+		$this->note = 'This is a comment (private)';
3874
+		$this->fk_incoterms = 0;
3875
+		$this->location_incoterms = '';
3876 3876
 
3877 3877
 		if (empty($option) || $option != 'nolines')
3878 3878
 		{
@@ -3881,63 +3881,63 @@  discard block
 block discarded – undo
3881 3881
 			$xnbp = 0;
3882 3882
 			while ($xnbp < $nbp)
3883 3883
 			{
3884
-				$line=new FactureLigne($this->db);
3885
-				$line->desc=$langs->trans("Description")." ".$xnbp;
3886
-				$line->qty=1;
3887
-				$line->subprice=100;
3888
-				$line->tva_tx=19.6;
3889
-				$line->localtax1_tx=0;
3890
-				$line->localtax2_tx=0;
3891
-				$line->remise_percent=0;
3884
+				$line = new FactureLigne($this->db);
3885
+				$line->desc = $langs->trans("Description")." ".$xnbp;
3886
+				$line->qty = 1;
3887
+				$line->subprice = 100;
3888
+				$line->tva_tx = 19.6;
3889
+				$line->localtax1_tx = 0;
3890
+				$line->localtax2_tx = 0;
3891
+				$line->remise_percent = 0;
3892 3892
 				if ($xnbp == 1)        // Qty is negative (product line)
3893 3893
 				{
3894 3894
 					$prodid = mt_rand(1, $num_prods);
3895
-					$line->fk_product=$prodids[$prodid];
3896
-					$line->qty=-1;
3897
-					$line->total_ht=-100;
3898
-					$line->total_ttc=-119.6;
3899
-					$line->total_tva=-19.6;
3900
-					$line->multicurrency_total_ht=-200;
3901
-					$line->multicurrency_total_ttc=-239.2;
3902
-					$line->multicurrency_total_tva=-39.2;
3895
+					$line->fk_product = $prodids[$prodid];
3896
+					$line->qty = -1;
3897
+					$line->total_ht = -100;
3898
+					$line->total_ttc = -119.6;
3899
+					$line->total_tva = -19.6;
3900
+					$line->multicurrency_total_ht = -200;
3901
+					$line->multicurrency_total_ttc = -239.2;
3902
+					$line->multicurrency_total_tva = -39.2;
3903 3903
 				}
3904 3904
 				else if ($xnbp == 2)    // UP is negative (free line)
3905 3905
 				{
3906
-					$line->subprice=-100;
3907
-					$line->total_ht=-100;
3908
-					$line->total_ttc=-119.6;
3909
-					$line->total_tva=-19.6;
3910
-					$line->remise_percent=0;
3911
-					$line->multicurrency_total_ht=-200;
3912
-					$line->multicurrency_total_ttc=-239.2;
3913
-					$line->multicurrency_total_tva=-39.2;
3906
+					$line->subprice = -100;
3907
+					$line->total_ht = -100;
3908
+					$line->total_ttc = -119.6;
3909
+					$line->total_tva = -19.6;
3910
+					$line->remise_percent = 0;
3911
+					$line->multicurrency_total_ht = -200;
3912
+					$line->multicurrency_total_ttc = -239.2;
3913
+					$line->multicurrency_total_tva = -39.2;
3914 3914
 				}
3915 3915
 				else if ($xnbp == 3)    // Discount is 50% (product line)
3916 3916
 				{
3917 3917
 					$prodid = mt_rand(1, $num_prods);
3918
-					$line->fk_product=$prodids[$prodid];
3919
-					$line->total_ht=50;
3920
-					$line->total_ttc=59.8;
3921
-					$line->total_tva=9.8;
3922
-					$line->multicurrency_total_ht=100;
3923
-					$line->multicurrency_total_ttc=119.6;
3924
-					$line->multicurrency_total_tva=19.6;
3925
-					$line->remise_percent=50;
3918
+					$line->fk_product = $prodids[$prodid];
3919
+					$line->total_ht = 50;
3920
+					$line->total_ttc = 59.8;
3921
+					$line->total_tva = 9.8;
3922
+					$line->multicurrency_total_ht = 100;
3923
+					$line->multicurrency_total_ttc = 119.6;
3924
+					$line->multicurrency_total_tva = 19.6;
3925
+					$line->remise_percent = 50;
3926 3926
 				}
3927 3927
 				else    // (product line)
3928 3928
 				{
3929 3929
 					$prodid = mt_rand(1, $num_prods);
3930
-					$line->fk_product=$prodids[$prodid];
3931
-					$line->total_ht=100;
3932
-					$line->total_ttc=119.6;
3933
-					$line->total_tva=19.6;
3934
-					$line->multicurrency_total_ht=200;
3935
-					$line->multicurrency_total_ttc=239.2;
3936
-					$line->multicurrency_total_tva=39.2;
3937
-					$line->remise_percent=0;
3930
+					$line->fk_product = $prodids[$prodid];
3931
+					$line->total_ht = 100;
3932
+					$line->total_ttc = 119.6;
3933
+					$line->total_tva = 19.6;
3934
+					$line->multicurrency_total_ht = 200;
3935
+					$line->multicurrency_total_ttc = 239.2;
3936
+					$line->multicurrency_total_tva = 39.2;
3937
+					$line->remise_percent = 0;
3938 3938
 				}
3939 3939
 
3940
-				$this->lines[$xnbp]=$line;
3940
+				$this->lines[$xnbp] = $line;
3941 3941
 
3942 3942
 
3943 3943
 				$this->total_ht       += $line->total_ht;
@@ -3953,24 +3953,24 @@  discard block
 block discarded – undo
3953 3953
 			$this->revenuestamp = 0;
3954 3954
 
3955 3955
 			// Add a line "offered"
3956
-			$line=new FactureLigne($this->db);
3957
-			$line->desc=$langs->trans("Description")." (offered line)";
3958
-			$line->qty=1;
3959
-			$line->subprice=100;
3960
-			$line->tva_tx=19.6;
3961
-			$line->localtax1_tx=0;
3962
-			$line->localtax2_tx=0;
3963
-			$line->remise_percent=100;
3964
-			$line->total_ht=0;
3965
-			$line->total_ttc=0;    // 90 * 1.196
3966
-			$line->total_tva=0;
3967
-			$line->multicurrency_total_ht=0;
3968
-			$line->multicurrency_total_ttc=0;
3969
-			$line->multicurrency_total_tva=0;
3956
+			$line = new FactureLigne($this->db);
3957
+			$line->desc = $langs->trans("Description")." (offered line)";
3958
+			$line->qty = 1;
3959
+			$line->subprice = 100;
3960
+			$line->tva_tx = 19.6;
3961
+			$line->localtax1_tx = 0;
3962
+			$line->localtax2_tx = 0;
3963
+			$line->remise_percent = 100;
3964
+			$line->total_ht = 0;
3965
+			$line->total_ttc = 0; // 90 * 1.196
3966
+			$line->total_tva = 0;
3967
+			$line->multicurrency_total_ht = 0;
3968
+			$line->multicurrency_total_ttc = 0;
3969
+			$line->multicurrency_total_tva = 0;
3970 3970
 			$prodid = mt_rand(1, $num_prods);
3971
-			$line->fk_product=$prodids[$prodid];
3971
+			$line->fk_product = $prodids[$prodid];
3972 3972
 
3973
-			$this->lines[$xnbp]=$line;
3973
+			$this->lines[$xnbp] = $line;
3974 3974
 			$xnbp++;
3975 3975
 		}
3976 3976
 	}
@@ -3984,27 +3984,27 @@  discard block
 block discarded – undo
3984 3984
 	{
3985 3985
 		global $conf, $user;
3986 3986
 
3987
-		$this->nb=array();
3987
+		$this->nb = array();
3988 3988
 
3989 3989
 		$clause = "WHERE";
3990 3990
 
3991 3991
 		$sql = "SELECT count(f.rowid) as nb";
3992
-		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
3993
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
3992
+		$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3993
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
3994 3994
 		if (!$user->rights->societe->client->voir && !$user->societe_id)
3995 3995
 		{
3996
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3997
-			$sql.= " WHERE sc.fk_user = " .$user->id;
3996
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3997
+			$sql .= " WHERE sc.fk_user = ".$user->id;
3998 3998
 			$clause = "AND";
3999 3999
 		}
4000
-		$sql.= " ".$clause." f.entity = ".$conf->entity;
4000
+		$sql .= " ".$clause." f.entity = ".$conf->entity;
4001 4001
 
4002
-		$resql=$this->db->query($sql);
4002
+		$resql = $this->db->query($sql);
4003 4003
 		if ($resql)
4004 4004
 		{
4005
-			while ($obj=$this->db->fetch_object($resql))
4005
+			while ($obj = $this->db->fetch_object($resql))
4006 4006
 			{
4007
-				$this->nb["invoices"]=$obj->nb;
4007
+				$this->nb["invoices"] = $obj->nb;
4008 4008
 			}
4009 4009
             $this->db->free($resql);
4010 4010
 			return 1;
@@ -4012,7 +4012,7 @@  discard block
 block discarded – undo
4012 4012
 		else
4013 4013
 		{
4014 4014
 			dol_print_error($this->db);
4015
-			$this->error=$this->db->error();
4015
+			$this->error = $this->db->error();
4016 4016
 			return -1;
4017 4017
 		}
4018 4018
 	}
@@ -4037,19 +4037,19 @@  discard block
 block discarded – undo
4037 4037
 	 *  @param  int			$hideref        Hide ref
4038 4038
 	 *	@return int        					<0 if KO, >0 if OK
4039 4039
 	 */
4040
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
4040
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
4041 4041
 	{
4042
-		global $conf,$langs;
4042
+		global $conf, $langs;
4043 4043
 
4044 4044
 		$langs->load("bills");
4045 4045
 
4046
-		if (! dol_strlen($modele)) {
4046
+		if (!dol_strlen($modele)) {
4047 4047
 
4048 4048
 			$modele = 'crabe';
4049 4049
 
4050 4050
 			if ($this->modelpdf) {
4051 4051
 				$modele = $this->modelpdf;
4052
-			} elseif (! empty($conf->global->FACTURE_ADDON_PDF)) {
4052
+			} elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
4053 4053
 				$modele = $conf->global->FACTURE_ADDON_PDF;
4054 4054
 			}
4055 4055
 		}
@@ -4066,8 +4066,8 @@  discard block
 block discarded – undo
4066 4066
 	 */
4067 4067
 	function newCycle()
4068 4068
 	{
4069
-		$sql = 'SELECT max(situation_cycle_ref) FROM ' . MAIN_DB_PREFIX . 'facture as f';
4070
-		$sql.= " WHERE f.entity in (".getEntity('facture', 0).")";
4069
+		$sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
4070
+		$sql .= " WHERE f.entity in (".getEntity('facture', 0).")";
4071 4071
 		$resql = $this->db->query($sql);
4072 4072
 		if ($resql) {
4073 4073
 			if ($resql->num_rows > 0)
@@ -4082,7 +4082,7 @@  discard block
 block discarded – undo
4082 4082
 			return $ref;
4083 4083
 		} else {
4084 4084
 			$this->error = $this->db->lasterror();
4085
-			dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
4085
+			dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
4086 4086
 			return -1;
4087 4087
 		}
4088 4088
 	}
@@ -4106,10 +4106,10 @@  discard block
 block discarded – undo
4106 4106
 	{
4107 4107
 		global $conf;
4108 4108
 
4109
-		$sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'facture';
4110
-		$sql .= ' where situation_cycle_ref = ' . $this->situation_cycle_ref;
4111
-		$sql .= ' and situation_counter < ' . $this->situation_counter;
4112
-		$sql .= ' AND entity = '. ($this->entity > 0 ? $this->entity : $conf->entity);
4109
+		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
4110
+		$sql .= ' where situation_cycle_ref = '.$this->situation_cycle_ref;
4111
+		$sql .= ' and situation_counter < '.$this->situation_counter;
4112
+		$sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
4113 4113
 		$resql = $this->db->query($sql);
4114 4114
 		$res = array();
4115 4115
 		if ($resql && $resql->num_rows > 0) {
@@ -4121,7 +4121,7 @@  discard block
 block discarded – undo
4121 4121
 			}
4122 4122
 		} else {
4123 4123
 			$this->error = $this->db->error();
4124
-			dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
4124
+			dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
4125 4125
 			return -1;
4126 4126
 		}
4127 4127
 
@@ -4135,45 +4135,45 @@  discard block
 block discarded – undo
4135 4135
 	 *  @param     	int		$notrigger	1=Does not execute triggers, 0= execute triggers
4136 4136
 	 *	@return		int 				<0 if KO, >0 if OK
4137 4137
 	 */
4138
-	function setFinal(User $user, $notrigger=0)
4138
+	function setFinal(User $user, $notrigger = 0)
4139 4139
 	{
4140
-		$error=0;
4140
+		$error = 0;
4141 4141
 
4142 4142
 		$this->db->begin();
4143 4143
 
4144 4144
 		$this->situation_final = 1;
4145
-		$sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture SET situation_final = ' . $this->situation_final . ' where rowid = ' . $this->id;
4145
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.$this->situation_final.' where rowid = '.$this->id;
4146 4146
 
4147 4147
 		dol_syslog(__METHOD__, LOG_DEBUG);
4148
-		$resql=$this->db->query($sql);
4148
+		$resql = $this->db->query($sql);
4149 4149
 		if (!$resql)
4150 4150
 		{
4151
-			$this->errors[]=$this->db->error();
4151
+			$this->errors[] = $this->db->error();
4152 4152
 			$error++;
4153 4153
 		}
4154 4154
 
4155
-		if (! $notrigger && empty($error))
4155
+		if (!$notrigger && empty($error))
4156 4156
 		{
4157 4157
 			// Call trigger
4158
-			$result=$this->call_trigger('BILL_MODIFY',$user);
4158
+			$result = $this->call_trigger('BILL_MODIFY', $user);
4159 4159
 			if ($result < 0) $error++;
4160 4160
 			// End call triggers
4161 4161
 		}
4162 4162
 
4163
-		if (! $error)
4163
+		if (!$error)
4164 4164
 		{
4165 4165
 			$this->db->commit();
4166 4166
 			return 1;
4167 4167
 		}
4168 4168
 		else
4169 4169
 		{
4170
-			foreach($this->errors as $errmsg)
4170
+			foreach ($this->errors as $errmsg)
4171 4171
 			{
4172 4172
 				dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4173
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
4173
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4174 4174
 			}
4175 4175
 			$this->db->rollback();
4176
-			return -1*$error;
4176
+			return -1 * $error;
4177 4177
 		}
4178 4178
 	}
4179 4179
 
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
 
4190 4190
 		if (!empty($this->situation_cycle_ref)) {
4191 4191
 			// No point in testing anything if we're not inside a cycle
4192
-			$sql = 'SELECT max(situation_counter) FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_cycle_ref = ' . $this->situation_cycle_ref . ' AND entity = ' . ($this->entity > 0 ? $this->entity : $conf->entity);
4192
+			$sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture WHERE situation_cycle_ref = '.$this->situation_cycle_ref.' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
4193 4193
 			$resql = $this->db->query($sql);
4194 4194
 
4195 4195
 			if ($resql && $resql->num_rows > 0) {
@@ -4198,7 +4198,7 @@  discard block
 block discarded – undo
4198 4198
 				return ($last == $this->situation_counter);
4199 4199
 			} else {
4200 4200
 				$this->error = $this->db->lasterror();
4201
-				dol_syslog(get_class($this) . "::select Error " . $this->error, LOG_ERR);
4201
+				dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
4202 4202
 				return false;
4203 4203
 			}
4204 4204
 		} else {
@@ -4247,8 +4247,8 @@  discard block
 block discarded – undo
4247 4247
  */
4248 4248
 class FactureLigne extends CommonInvoiceLine
4249 4249
 {
4250
-    public $element='facturedet';
4251
-    public $table_element='facturedet';
4250
+    public $element = 'facturedet';
4251
+    public $table_element = 'facturedet';
4252 4252
 
4253 4253
 	var $oldline;
4254 4254
 
@@ -4264,9 +4264,9 @@  discard block
 block discarded – undo
4264 4264
 	//! Description ligne
4265 4265
 	var $desc;
4266 4266
 
4267
-	var $localtax1_type;	// Local tax 1 type
4268
-	var $localtax2_type;	// Local tax 2 type
4269
-	var $fk_remise_except;	// Link to line into llx_remise_except
4267
+	var $localtax1_type; // Local tax 1 type
4268
+	var $localtax2_type; // Local tax 2 type
4269
+	var $fk_remise_except; // Link to line into llx_remise_except
4270 4270
 	var $rang = 0;
4271 4271
 
4272 4272
 	var $fk_fournprice;
@@ -4274,7 +4274,7 @@  discard block
 block discarded – undo
4274 4274
 	var $marge_tx;
4275 4275
 	var $marque_tx;
4276 4276
 
4277
-	var $special_code;	// Liste d'options non cumulabels:
4277
+	var $special_code; // Liste d'options non cumulabels:
4278 4278
 	// 1: frais de port
4279 4279
 	// 2: ecotaxe
4280 4280
 	// 3: ??
@@ -4296,15 +4296,15 @@  discard block
 block discarded – undo
4296 4296
 	 * @deprecated
4297 4297
 	 * @see product_ref
4298 4298
 	 */
4299
-	var $ref;				// Product ref (deprecated)
4300
-	var $product_ref;       // Product ref
4299
+	var $ref; // Product ref (deprecated)
4300
+	var $product_ref; // Product ref
4301 4301
 	/**
4302 4302
 	 * @deprecated
4303 4303
 	 * @see product_label
4304 4304
 	 */
4305
-	var $libelle;      		// Product label (deprecated)
4306
-	var $product_label;     // Product label
4307
-	var $product_desc;  	// Description produit
4305
+	var $libelle; // Product label (deprecated)
4306
+	var $product_label; // Product label
4307
+	var $product_desc; // Description produit
4308 4308
 
4309 4309
 	var $skip_update_total; // Skip update price total for special lines
4310 4310
 
@@ -4335,20 +4335,20 @@  discard block
 block discarded – undo
4335 4335
 	function fetch($rowid)
4336 4336
 	{
4337 4337
 		$sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
4338
-		$sql.= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,';
4339
-		$sql.= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
4340
-		$sql.= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
4341
-		$sql.= ' fd.fk_code_ventilation,';
4342
-		$sql.= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
4343
-		$sql.= ' fd.situation_percent, fd.fk_prev_id,';
4344
-		$sql.= ' fd.multicurrency_subprice,';
4345
-		$sql.= ' fd.multicurrency_total_ht,';
4346
-		$sql.= ' fd.multicurrency_total_tva,';
4347
-		$sql.= ' fd.multicurrency_total_ttc,';
4348
-		$sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc';
4349
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
4350
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
4351
-		$sql.= ' WHERE fd.rowid = '.$rowid;
4338
+		$sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,';
4339
+		$sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
4340
+		$sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
4341
+		$sql .= ' fd.fk_code_ventilation,';
4342
+		$sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
4343
+		$sql .= ' fd.situation_percent, fd.fk_prev_id,';
4344
+		$sql .= ' fd.multicurrency_subprice,';
4345
+		$sql .= ' fd.multicurrency_total_ht,';
4346
+		$sql .= ' fd.multicurrency_total_tva,';
4347
+		$sql .= ' fd.multicurrency_total_ttc,';
4348
+		$sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc';
4349
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
4350
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
4351
+		$sql .= ' WHERE fd.rowid = '.$rowid;
4352 4352
 
4353 4353
 		$result = $this->db->query($sql);
4354 4354
 		if ($result)
@@ -4356,53 +4356,53 @@  discard block
 block discarded – undo
4356 4356
 			$objp = $this->db->fetch_object($result);
4357 4357
 
4358 4358
 			$this->rowid				= $objp->rowid;
4359
-			$this->fk_facture			= $objp->fk_facture;
4360
-			$this->fk_parent_line		= $objp->fk_parent_line;
4359
+			$this->fk_facture = $objp->fk_facture;
4360
+			$this->fk_parent_line = $objp->fk_parent_line;
4361 4361
 			$this->label				= $objp->custom_label;
4362 4362
 			$this->desc					= $objp->description;
4363
-			$this->qty					= $objp->qty;
4364
-			$this->subprice				= $objp->subprice;
4365
-			$this->vat_src_code  		= $objp->vat_src_code;
4366
-			$this->tva_tx				= $objp->tva_tx;
4363
+			$this->qty = $objp->qty;
4364
+			$this->subprice = $objp->subprice;
4365
+			$this->vat_src_code = $objp->vat_src_code;
4366
+			$this->tva_tx = $objp->tva_tx;
4367 4367
 			$this->localtax1_tx			= $objp->localtax1_tx;
4368 4368
 			$this->localtax2_tx			= $objp->localtax2_tx;
4369
-			$this->remise_percent		= $objp->remise_percent;
4370
-			$this->fk_remise_except		= $objp->fk_remise_except;
4369
+			$this->remise_percent = $objp->remise_percent;
4370
+			$this->fk_remise_except = $objp->fk_remise_except;
4371 4371
 			$this->fk_product			= $objp->fk_product;
4372
-			$this->product_type			= $objp->product_type;
4372
+			$this->product_type = $objp->product_type;
4373 4373
 			$this->date_start			= $this->db->jdate($objp->date_start);
4374 4374
 			$this->date_end				= $this->db->jdate($objp->date_end);
4375 4375
 			$this->info_bits			= $objp->info_bits;
4376
-			$this->special_code			= $objp->special_code;
4376
+			$this->special_code = $objp->special_code;
4377 4377
 			$this->total_ht				= $objp->total_ht;
4378 4378
 			$this->total_tva			= $objp->total_tva;
4379 4379
 			$this->total_localtax1		= $objp->total_localtax1;
4380 4380
 			$this->total_localtax2		= $objp->total_localtax2;
4381 4381
 			$this->total_ttc			= $objp->total_ttc;
4382
-			$this->fk_code_ventilation	= $objp->fk_code_ventilation;
4382
+			$this->fk_code_ventilation = $objp->fk_code_ventilation;
4383 4383
 			$this->rang					= $objp->rang;
4384
-			$this->fk_fournprice		= $objp->fk_fournprice;
4384
+			$this->fk_fournprice = $objp->fk_fournprice;
4385 4385
 			$marginInfos				= getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
4386 4386
 			$this->pa_ht				= $marginInfos[0];
4387 4387
 			$this->marge_tx				= $marginInfos[1];
4388 4388
 			$this->marque_tx			= $marginInfos[2];
4389 4389
 
4390
-			$this->ref					= $objp->product_ref;      // deprecated
4391
-			$this->product_ref			= $objp->product_ref;
4392
-			$this->libelle				= $objp->product_libelle;  // deprecated
4390
+			$this->ref = $objp->product_ref; // deprecated
4391
+			$this->product_ref = $objp->product_ref;
4392
+			$this->libelle				= $objp->product_libelle; // deprecated
4393 4393
 			$this->product_label		= $objp->product_libelle;
4394 4394
 			$this->product_desc			= $objp->product_desc;
4395 4395
 			$this->fk_unit				= $objp->fk_unit;
4396 4396
 			$this->fk_user_modif		= $objp->fk_user_modif;
4397
-			$this->fk_user_author		= $objp->fk_user_author;
4397
+			$this->fk_user_author = $objp->fk_user_author;
4398 4398
 
4399 4399
 			$this->situation_percent    = $objp->situation_percent;
4400 4400
 			$this->fk_prev_id           = $objp->fk_prev_id;
4401 4401
 
4402 4402
 			$this->multicurrency_subprice = $objp->multicurrency_subprice;
4403 4403
 			$this->multicurrency_total_ht = $objp->multicurrency_total_ht;
4404
-			$this->multicurrency_total_tva= $objp->multicurrency_total_tva;
4405
-			$this->multicurrency_total_ttc= $objp->multicurrency_total_ttc;
4404
+			$this->multicurrency_total_tva = $objp->multicurrency_total_tva;
4405
+			$this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
4406 4406
 
4407 4407
 			$this->db->free($result);
4408 4408
 
@@ -4422,39 +4422,39 @@  discard block
 block discarded – undo
4422 4422
 	 *  @param      int     $noerrorifdiscountalreadylinked  1=Do not make error if lines is linked to a discount and discount already linked to another
4423 4423
 	 *	@return		int						                 <0 if KO, >0 if OK
4424 4424
 	 */
4425
-	function insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
4425
+	function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
4426 4426
 	{
4427
-		global $langs,$user,$conf;
4427
+		global $langs, $user, $conf;
4428 4428
 
4429
-		$error=0;
4429
+		$error = 0;
4430 4430
 
4431 4431
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4432 4432
 
4433 4433
         dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
4434 4434
 
4435 4435
 		// Clean parameters
4436
-		$this->desc=trim($this->desc);
4437
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4438
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4439
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4440
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4441
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4442
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4443
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4444
-		if (empty($this->rang)) $this->rang=0;
4445
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4446
-		if (empty($this->info_bits)) $this->info_bits=0;
4447
-		if (empty($this->subprice)) $this->subprice=0;
4448
-		if (empty($this->special_code)) $this->special_code=0;
4449
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4436
+		$this->desc = trim($this->desc);
4437
+		if (empty($this->tva_tx)) $this->tva_tx = 0;
4438
+		if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
4439
+		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
4440
+		if (empty($this->localtax1_type)) $this->localtax1_type = 0;
4441
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
4442
+		if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4443
+		if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4444
+		if (empty($this->rang)) $this->rang = 0;
4445
+		if (empty($this->remise_percent)) $this->remise_percent = 0;
4446
+		if (empty($this->info_bits)) $this->info_bits = 0;
4447
+		if (empty($this->subprice)) $this->subprice = 0;
4448
+		if (empty($this->special_code)) $this->special_code = 0;
4449
+		if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
4450 4450
 		if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null';
4451
-		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4451
+		if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4452 4452
 
4453
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4454
-		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
4455
-		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
4456
-		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
4457
-		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
4453
+		if (empty($this->pa_ht)) $this->pa_ht = 0;
4454
+		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0;
4455
+		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0;
4456
+		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
4457
+		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
4458 4458
 
4459 4459
 		// if buy price not defined, define buyprice as configured in margin admin
4460 4460
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -4472,16 +4472,16 @@  discard block
 block discarded – undo
4472 4472
 		// Check parameters
4473 4473
 		if ($this->product_type < 0)
4474 4474
 		{
4475
-			$this->error='ErrorProductTypeMustBe0orMore';
4475
+			$this->error = 'ErrorProductTypeMustBe0orMore';
4476 4476
 			return -1;
4477 4477
 		}
4478
-		if (! empty($this->fk_product))
4478
+		if (!empty($this->fk_product))
4479 4479
 		{
4480 4480
 			// Check product exists
4481
-			$result=Product::isExistingObject('product', $this->fk_product);
4481
+			$result = Product::isExistingObject('product', $this->fk_product);
4482 4482
 			if ($result <= 0)
4483 4483
 			{
4484
-				$this->error='ErrorProductIdDoesNotExists';
4484
+				$this->error = 'ErrorProductIdDoesNotExists';
4485 4485
 				return -1;
4486 4486
 			}
4487 4487
 		}
@@ -4490,68 +4490,68 @@  discard block
 block discarded – undo
4490 4490
 
4491 4491
 		// Insertion dans base de la ligne
4492 4492
 		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
4493
-		$sql.= ' (fk_facture, fk_parent_line, label, description, qty,';
4494
-		$sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4495
-		$sql.= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
4496
-		$sql.= ' date_start, date_end, fk_code_ventilation, ';
4497
-		$sql.= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
4498
-		$sql.= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
4499
-		$sql.= ' situation_percent, fk_prev_id,';
4500
-		$sql.= ' fk_unit, fk_user_author, fk_user_modif,';
4501
-		$sql.= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4502
-		$sql.= ')';
4503
-		$sql.= " VALUES (".$this->fk_facture.",";
4504
-		$sql.= " ".($this->fk_parent_line>0 ? $this->fk_parent_line:"null").",";
4505
-		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4506
-		$sql.= " '".$this->db->escape($this->desc)."',";
4507
-		$sql.= " ".price2num($this->qty).",";
4508
-        $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4509
-		$sql.= " ".price2num($this->tva_tx).",";
4510
-		$sql.= " ".price2num($this->localtax1_tx).",";
4511
-		$sql.= " ".price2num($this->localtax2_tx).",";
4512
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
4513
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
4514
-		$sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
4515
-		$sql.= " ".$this->product_type.",";
4516
-		$sql.= " ".price2num($this->remise_percent).",";
4517
-		$sql.= " ".price2num($this->subprice).",";
4518
-		$sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
4519
-		$sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").",";
4520
-		$sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").",";
4521
-		$sql.= ' '.$this->fk_code_ventilation.',';
4522
-		$sql.= ' '.$this->rang.',';
4523
-		$sql.= ' '.$this->special_code.',';
4524
-		$sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
4525
-		$sql.= ' '.price2num($this->pa_ht).',';
4526
-		$sql.= " '".$this->db->escape($this->info_bits)."',";
4527
-		$sql.= " ".price2num($this->total_ht).",";
4528
-		$sql.= " ".price2num($this->total_tva).",";
4529
-		$sql.= " ".price2num($this->total_ttc).",";
4530
-		$sql.= " ".price2num($this->total_localtax1).",";
4531
-		$sql.= " ".price2num($this->total_localtax2);
4532
-		$sql.= ", " . $this->situation_percent;
4533
-		$sql.= ", " . $this->fk_prev_id;
4534
-		$sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4535
-		$sql.= ", ".$user->id;
4536
-		$sql.= ", ".$user->id;
4537
-		$sql.= ", ".(int) $this->fk_multicurrency;
4538
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
4539
-		$sql.= ", ".price2num($this->multicurrency_subprice);
4540
-		$sql.= ", ".price2num($this->multicurrency_total_ht);
4541
-		$sql.= ", ".price2num($this->multicurrency_total_tva);
4542
-		$sql.= ", ".price2num($this->multicurrency_total_ttc);
4543
-		$sql.= ')';
4493
+		$sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
4494
+		$sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4495
+		$sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
4496
+		$sql .= ' date_start, date_end, fk_code_ventilation, ';
4497
+		$sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
4498
+		$sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
4499
+		$sql .= ' situation_percent, fk_prev_id,';
4500
+		$sql .= ' fk_unit, fk_user_author, fk_user_modif,';
4501
+		$sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4502
+		$sql .= ')';
4503
+		$sql .= " VALUES (".$this->fk_facture.",";
4504
+		$sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
4505
+		$sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
4506
+		$sql .= " '".$this->db->escape($this->desc)."',";
4507
+		$sql .= " ".price2num($this->qty).",";
4508
+        $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
4509
+		$sql .= " ".price2num($this->tva_tx).",";
4510
+		$sql .= " ".price2num($this->localtax1_tx).",";
4511
+		$sql .= " ".price2num($this->localtax2_tx).",";
4512
+		$sql .= " '".$this->db->escape($this->localtax1_type)."',";
4513
+		$sql .= " '".$this->db->escape($this->localtax2_type)."',";
4514
+		$sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").',';
4515
+		$sql .= " ".$this->product_type.",";
4516
+		$sql .= " ".price2num($this->remise_percent).",";
4517
+		$sql .= " ".price2num($this->subprice).",";
4518
+		$sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
4519
+		$sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
4520
+		$sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
4521
+		$sql .= ' '.$this->fk_code_ventilation.',';
4522
+		$sql .= ' '.$this->rang.',';
4523
+		$sql .= ' '.$this->special_code.',';
4524
+		$sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
4525
+		$sql .= ' '.price2num($this->pa_ht).',';
4526
+		$sql .= " '".$this->db->escape($this->info_bits)."',";
4527
+		$sql .= " ".price2num($this->total_ht).",";
4528
+		$sql .= " ".price2num($this->total_tva).",";
4529
+		$sql .= " ".price2num($this->total_ttc).",";
4530
+		$sql .= " ".price2num($this->total_localtax1).",";
4531
+		$sql .= " ".price2num($this->total_localtax2);
4532
+		$sql .= ", ".$this->situation_percent;
4533
+		$sql .= ", ".$this->fk_prev_id;
4534
+		$sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4535
+		$sql .= ", ".$user->id;
4536
+		$sql .= ", ".$user->id;
4537
+		$sql .= ", ".(int) $this->fk_multicurrency;
4538
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
4539
+		$sql .= ", ".price2num($this->multicurrency_subprice);
4540
+		$sql .= ", ".price2num($this->multicurrency_total_ht);
4541
+		$sql .= ", ".price2num($this->multicurrency_total_tva);
4542
+		$sql .= ", ".price2num($this->multicurrency_total_ttc);
4543
+		$sql .= ')';
4544 4544
 
4545 4545
 		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
4546
-		$resql=$this->db->query($sql);
4546
+		$resql = $this->db->query($sql);
4547 4547
 		if ($resql)
4548 4548
 		{
4549
-			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
4549
+			$this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
4550 4550
 
4551 4551
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4552 4552
             {
4553
-            	$this->id=$this->rowid;
4554
-            	$result=$this->insertExtraFields();
4553
+            	$this->id = $this->rowid;
4554
+            	$result = $this->insertExtraFields();
4555 4555
             	if ($result < 0)
4556 4556
             	{
4557 4557
             		$error++;
@@ -4562,8 +4562,8 @@  discard block
 block discarded – undo
4562 4562
 			// ce qui la flague comme "consommee".
4563 4563
 			if ($this->fk_remise_except)
4564 4564
 			{
4565
-				$discount=new DiscountAbsolute($this->db);
4566
-				$result=$discount->fetch($this->fk_remise_except);
4565
+				$discount = new DiscountAbsolute($this->db);
4566
+				$result = $discount->fetch($this->fk_remise_except);
4567 4567
 				if ($result >= 0)
4568 4568
 				{
4569 4569
 					// Check if discount was found
@@ -4574,7 +4574,7 @@  discard block
 block discarded – undo
4574 4574
 						{
4575 4575
 						    if (empty($noerrorifdiscountalreadylinked))
4576 4576
 						    {
4577
-    							$this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
4577
+    							$this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
4578 4578
     							dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4579 4579
     							$this->db->rollback();
4580 4580
     							return -3;
@@ -4582,10 +4582,10 @@  discard block
 block discarded – undo
4582 4582
 						}
4583 4583
 						else
4584 4584
 						{
4585
-							$result=$discount->link_to_invoice($this->rowid,0);
4585
+							$result = $discount->link_to_invoice($this->rowid, 0);
4586 4586
 							if ($result < 0)
4587 4587
 							{
4588
-								$this->error=$discount->error;
4588
+								$this->error = $discount->error;
4589 4589
 								dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4590 4590
 								$this->db->rollback();
4591 4591
 								return -3;
@@ -4594,7 +4594,7 @@  discard block
 block discarded – undo
4594 4594
 					}
4595 4595
 					else
4596 4596
 					{
4597
-						$this->error=$langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
4597
+						$this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
4598 4598
 						dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4599 4599
 						$this->db->rollback();
4600 4600
 						return -3;
@@ -4602,17 +4602,17 @@  discard block
 block discarded – undo
4602 4602
 				}
4603 4603
 				else
4604 4604
 				{
4605
-					$this->error=$discount->error;
4605
+					$this->error = $discount->error;
4606 4606
 					dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4607 4607
 					$this->db->rollback();
4608 4608
 					return -3;
4609 4609
 				}
4610 4610
 			}
4611 4611
 
4612
-			if (! $notrigger)
4612
+			if (!$notrigger)
4613 4613
 			{
4614 4614
                 // Call trigger
4615
-                $result=$this->call_trigger('LINEBILL_INSERT',$user);
4615
+                $result = $this->call_trigger('LINEBILL_INSERT', $user);
4616 4616
                 if ($result < 0)
4617 4617
                 {
4618 4618
 					$this->db->rollback();
@@ -4627,7 +4627,7 @@  discard block
 block discarded – undo
4627 4627
 		}
4628 4628
 		else
4629 4629
 		{
4630
-			$this->error=$this->db->error();
4630
+			$this->error = $this->db->error();
4631 4631
 			$this->db->rollback();
4632 4632
 			return -2;
4633 4633
 		}
@@ -4640,35 +4640,35 @@  discard block
 block discarded – undo
4640 4640
 	 *	@param		int		$notrigger	Disable triggers
4641 4641
 	 *	@return		int					<0 if KO, >0 if OK
4642 4642
 	 */
4643
-	function update($user='',$notrigger=0)
4643
+	function update($user = '', $notrigger = 0)
4644 4644
 	{
4645
-		global $user,$conf;
4645
+		global $user, $conf;
4646 4646
 
4647
-		$error=0;
4647
+		$error = 0;
4648 4648
 
4649 4649
 		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4650 4650
 
4651 4651
 		// Clean parameters
4652
-		$this->desc=trim($this->desc);
4653
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4654
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4655
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4656
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4657
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4658
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4659
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4660
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4661
-		if (empty($this->info_bits)) $this->info_bits=0;
4662
-		if (empty($this->special_code)) $this->special_code=0;
4663
-		if (empty($this->product_type)) $this->product_type=0;
4664
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4665
-		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4666
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4667
-
4668
-		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
4669
-		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
4670
-		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
4671
-		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
4652
+		$this->desc = trim($this->desc);
4653
+		if (empty($this->tva_tx)) $this->tva_tx = 0;
4654
+		if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
4655
+		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
4656
+		if (empty($this->localtax1_type)) $this->localtax1_type = 0;
4657
+		if (empty($this->localtax2_type)) $this->localtax2_type = 0;
4658
+		if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4659
+		if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4660
+		if (empty($this->remise_percent)) $this->remise_percent = 0;
4661
+		if (empty($this->info_bits)) $this->info_bits = 0;
4662
+		if (empty($this->special_code)) $this->special_code = 0;
4663
+		if (empty($this->product_type)) $this->product_type = 0;
4664
+		if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
4665
+		if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4666
+		if (empty($this->pa_ht)) $this->pa_ht = 0;
4667
+
4668
+		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0;
4669
+		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0;
4670
+		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
4671
+		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
4672 4672
 
4673 4673
 		// Check parameters
4674 4674
 		if ($this->product_type < 0) return -1;
@@ -4690,66 +4690,66 @@  discard block
 block discarded – undo
4690 4690
 
4691 4691
         // Mise a jour ligne en base
4692 4692
         $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
4693
-        $sql.= " description='".$this->db->escape($this->desc)."'";
4694
-        $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4695
-        $sql.= ", subprice=".price2num($this->subprice)."";
4696
-        $sql.= ", remise_percent=".price2num($this->remise_percent)."";
4697
-        if ($this->fk_remise_except) $sql.= ", fk_remise_except=".$this->fk_remise_except;
4698
-        else $sql.= ", fk_remise_except=null";
4699
-		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->db->escape($this->vat_src_code))."'";
4700
-        $sql.= ", tva_tx=".price2num($this->tva_tx)."";
4701
-        $sql.= ", localtax1_tx=".price2num($this->localtax1_tx)."";
4702
-        $sql.= ", localtax2_tx=".price2num($this->localtax2_tx)."";
4703
-		$sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4704
-		$sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4705
-        $sql.= ", qty=".price2num($this->qty);
4706
-        $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4707
-        $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4708
-        $sql.= ", product_type=".$this->product_type;
4709
-        $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
4710
-        $sql.= ", special_code='".$this->db->escape($this->special_code)."'";
4693
+        $sql .= " description='".$this->db->escape($this->desc)."'";
4694
+        $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
4695
+        $sql .= ", subprice=".price2num($this->subprice)."";
4696
+        $sql .= ", remise_percent=".price2num($this->remise_percent)."";
4697
+        if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except;
4698
+        else $sql .= ", fk_remise_except=null";
4699
+		$sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
4700
+        $sql .= ", tva_tx=".price2num($this->tva_tx)."";
4701
+        $sql .= ", localtax1_tx=".price2num($this->localtax1_tx)."";
4702
+        $sql .= ", localtax2_tx=".price2num($this->localtax2_tx)."";
4703
+		$sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4704
+		$sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4705
+        $sql .= ", qty=".price2num($this->qty);
4706
+        $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
4707
+        $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
4708
+        $sql .= ", product_type=".$this->product_type;
4709
+        $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
4710
+        $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
4711 4711
         if (empty($this->skip_update_total))
4712 4712
         {
4713
-        	$sql.= ", total_ht=".price2num($this->total_ht)."";
4714
-        	$sql.= ", total_tva=".price2num($this->total_tva)."";
4715
-        	$sql.= ", total_ttc=".price2num($this->total_ttc)."";
4716
-        	$sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
4717
-        	$sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
4713
+        	$sql .= ", total_ht=".price2num($this->total_ht)."";
4714
+        	$sql .= ", total_tva=".price2num($this->total_tva)."";
4715
+        	$sql .= ", total_ttc=".price2num($this->total_ttc)."";
4716
+        	$sql .= ", total_localtax1=".price2num($this->total_localtax1)."";
4717
+        	$sql .= ", total_localtax2=".price2num($this->total_localtax2)."";
4718 4718
         }
4719
-		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
4720
-		$sql.= ", buy_price_ht='".price2num($this->pa_ht)."'";
4721
-		$sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
4722
-		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
4723
-		$sql.= ", situation_percent=" . $this->situation_percent;
4724
-		$sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4725
-		$sql.= ", fk_user_modif =".$user->id;
4719
+		$sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
4720
+		$sql .= ", buy_price_ht='".price2num($this->pa_ht)."'";
4721
+		$sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
4722
+		if (!empty($this->rang)) $sql .= ", rang=".$this->rang;
4723
+		$sql .= ", situation_percent=".$this->situation_percent;
4724
+		$sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4725
+		$sql .= ", fk_user_modif =".$user->id;
4726 4726
 
4727 4727
 		// Multicurrency
4728
-		$sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4729
-        $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4730
-        $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4731
-        $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4728
+		$sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4729
+        $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4730
+        $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4731
+        $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4732 4732
 
4733
-		$sql.= " WHERE rowid = ".$this->rowid;
4733
+		$sql .= " WHERE rowid = ".$this->rowid;
4734 4734
 
4735 4735
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
4736
-		$resql=$this->db->query($sql);
4736
+		$resql = $this->db->query($sql);
4737 4737
 		if ($resql)
4738 4738
 		{
4739 4739
         	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4740 4740
         	{
4741
-        		$this->id=$this->rowid;
4742
-        		$result=$this->insertExtraFields();
4741
+        		$this->id = $this->rowid;
4742
+        		$result = $this->insertExtraFields();
4743 4743
         		if ($result < 0)
4744 4744
         		{
4745 4745
         			$error++;
4746 4746
         		}
4747 4747
         	}
4748 4748
 
4749
-			if (! $notrigger)
4749
+			if (!$notrigger)
4750 4750
 			{
4751 4751
                 // Call trigger
4752
-                $result=$this->call_trigger('LINEBILL_UPDATE',$user);
4752
+                $result = $this->call_trigger('LINEBILL_UPDATE', $user);
4753 4753
                 if ($result < 0)
4754 4754
  				{
4755 4755
 					$this->db->rollback();
@@ -4762,7 +4762,7 @@  discard block
 block discarded – undo
4762 4762
 		}
4763 4763
 		else
4764 4764
 		{
4765
-			$this->error=$this->db->error();
4765
+			$this->error = $this->db->error();
4766 4766
 			$this->db->rollback();
4767 4767
 			return -2;
4768 4768
 		}
@@ -4781,7 +4781,7 @@  discard block
 block discarded – undo
4781 4781
 		$this->db->begin();
4782 4782
 
4783 4783
 		// Call trigger
4784
-		$result=$this->call_trigger('LINEBILL_DELETE',$user);
4784
+		$result = $this->call_trigger('LINEBILL_DELETE', $user);
4785 4785
 		if ($result < 0)
4786 4786
 		{
4787 4787
 			$this->db->rollback();
@@ -4792,14 +4792,14 @@  discard block
 block discarded – undo
4792 4792
 
4793 4793
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid;
4794 4794
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
4795
-		if ($this->db->query($sql) )
4795
+		if ($this->db->query($sql))
4796 4796
 		{
4797 4797
 			$this->db->commit();
4798 4798
 			return 1;
4799 4799
 		}
4800 4800
 		else
4801 4801
 		{
4802
-			$this->error=$this->db->error()." sql=".$sql;
4802
+			$this->error = $this->db->error()." sql=".$sql;
4803 4803
 			$this->db->rollback();
4804 4804
 			return -1;
4805 4805
 		}
@@ -4816,21 +4816,21 @@  discard block
 block discarded – undo
4816 4816
 		dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
4817 4817
 
4818 4818
 		// Clean parameters
4819
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4820
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4819
+		if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4820
+		if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4821 4821
 
4822 4822
 		// Mise a jour ligne en base
4823 4823
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
4824
-		$sql.= " total_ht=".price2num($this->total_ht)."";
4825
-		$sql.= ",total_tva=".price2num($this->total_tva)."";
4826
-		$sql.= ",total_localtax1=".price2num($this->total_localtax1)."";
4827
-		$sql.= ",total_localtax2=".price2num($this->total_localtax2)."";
4828
-		$sql.= ",total_ttc=".price2num($this->total_ttc)."";
4829
-		$sql.= " WHERE rowid = ".$this->rowid;
4824
+		$sql .= " total_ht=".price2num($this->total_ht)."";
4825
+		$sql .= ",total_tva=".price2num($this->total_tva)."";
4826
+		$sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
4827
+		$sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
4828
+		$sql .= ",total_ttc=".price2num($this->total_ttc)."";
4829
+		$sql .= " WHERE rowid = ".$this->rowid;
4830 4830
 
4831 4831
 		dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
4832 4832
 
4833
-		$resql=$this->db->query($sql);
4833
+		$resql = $this->db->query($sql);
4834 4834
 		if ($resql)
4835 4835
 		{
4836 4836
 			$this->db->commit();
@@ -4838,7 +4838,7 @@  discard block
 block discarded – undo
4838 4838
 		}
4839 4839
 		else
4840 4840
 		{
4841
-			$this->error=$this->db->error();
4841
+			$this->error = $this->db->error();
4842 4842
 			$this->db->rollback();
4843 4843
 			return -2;
4844 4844
 		}
@@ -4857,18 +4857,18 @@  discard block
 block discarded – undo
4857 4857
 			return 0;
4858 4858
 		} else {
4859 4859
 		    // If invoice is a not a situation invoice, this->fk_prev_id is used for something else
4860
-            $tmpinvoice=new Facture($this->db);
4860
+            $tmpinvoice = new Facture($this->db);
4861 4861
             $tmpinvoice->fetch($invoiceid);
4862 4862
             if ($tmpinvoice->type != Facture::TYPE_SITUATION) return 0;
4863 4863
 
4864
-			$sql = 'SELECT situation_percent FROM ' . MAIN_DB_PREFIX . 'facturedet WHERE rowid=' . $this->fk_prev_id;
4864
+			$sql = 'SELECT situation_percent FROM '.MAIN_DB_PREFIX.'facturedet WHERE rowid='.$this->fk_prev_id;
4865 4865
 			$resql = $this->db->query($sql);
4866 4866
 			if ($resql && $resql->num_rows > 0) {
4867 4867
 				$res = $this->db->fetch_array($resql);
4868 4868
 				return $res['situation_percent'];
4869 4869
 			} else {
4870 4870
 				$this->error = $this->db->error();
4871
-				dol_syslog(get_class($this) . "::select Error " . $this->error, LOG_ERR);
4871
+				dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
4872 4872
 				$this->db->rollback();
4873 4873
 				return -1;
4874 4874
 			}
Please login to merge, or discard this patch.
Braces   +685 added lines, -361 removed lines patch added patch discarded remove patch
@@ -234,19 +234,30 @@  discard block
 block discarded – undo
234 234
 		$error=0;
235 235
 
236 236
 		// Clean parameters
237
-		if (empty($this->type)) $this->type = self::TYPE_STANDARD;
237
+		if (empty($this->type)) {
238
+			$this->type = self::TYPE_STANDARD;
239
+		}
238 240
 		$this->ref_client=trim($this->ref_client);
239 241
 		$this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
240 242
 		$this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
241 243
 		$this->note_public=trim($this->note_public);
242
-		if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
243
-		if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
244
+		if (! $this->cond_reglement_id) {
245
+			$this->cond_reglement_id = 0;
246
+		}
247
+		if (! $this->mode_reglement_id) {
248
+			$this->mode_reglement_id = 0;
249
+		}
244 250
 		$this->brouillon = 1;
245
-        if (empty($this->entity)) $this->entity = $conf->entity;
251
+        if (empty($this->entity)) {
252
+        	$this->entity = $conf->entity;
253
+        }
246 254
 
247 255
 		// Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
248
-		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
249
-		else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
256
+		if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
257
+			list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
258
+		} else {
259
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
260
+		}
250 261
 		if (empty($this->fk_multicurrency))
251 262
 		{
252 263
 			$this->multicurrency_code = $conf->currency;
@@ -311,7 +322,9 @@  discard block
 block discarded – undo
311 322
 			$this->location_incoterms= $_facrec->location_incoterms;
312 323
 
313 324
 			// Clean parameters
314
-			if (! $this->type) $this->type = self::TYPE_STANDARD;
325
+			if (! $this->type) {
326
+				$this->type = self::TYPE_STANDARD;
327
+			}
315 328
 			$this->ref_client=trim($this->ref_client);
316 329
 			$this->note_public=trim($this->note_public);
317 330
 			$this->note_private=trim($this->note_private);
@@ -320,7 +333,9 @@  discard block
 block discarded – undo
320 333
 		    $this->array_options=$_facrec->array_options;
321 334
 
322 335
 			//if (! $this->remise) $this->remise = 0;
323
-			if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
336
+			if (! $this->mode_reglement_id) {
337
+				$this->mode_reglement_id = 0;
338
+			}
324 339
 			$this->brouillon = 1;
325 340
 
326 341
 			$this->linked_objects = $_facrec->linkedObjectsIds;
@@ -331,7 +346,9 @@  discard block
 block discarded – undo
331 346
 			if ($_facrec->frequency > 0)
332 347
 			{
333 348
 			    dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
334
-			    if (empty($_facrec->date_when)) $_facrec->date_when = $now;
349
+			    if (empty($_facrec->date_when)) {
350
+			    	$_facrec->date_when = $now;
351
+			    }
335 352
                 $next_date = $_facrec->getNextDate();   // Calculate next date
336 353
                 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
337 354
                 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1);		// Not required, +1 already included into setNextDate when second param is 1.
@@ -342,8 +359,14 @@  discard block
 block discarded – undo
342 359
 			$outputlangs = $langs;
343 360
 			$newlang='';
344 361
 
345
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) $newlang=$this->thirdparty->default_lang;  // for proposal, order, invoice, ...
346
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang=$this->default_lang;                  // for thirdparty
362
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) {
363
+				$newlang=$this->thirdparty->default_lang;
364
+			}
365
+			// for proposal, order, invoice, ...
366
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) {
367
+				$newlang=$this->default_lang;
368
+			}
369
+			// for thirdparty
347 370
 			if (! empty($newlang))
348 371
 			{
349 372
 			    $outputlangs = new Translate("",$conf);
@@ -449,26 +472,29 @@  discard block
 block discarded – undo
449 472
 			$sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET facnumber='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
450 473
 
451 474
 			$resql=$this->db->query($sql);
452
-			if (! $resql) $error++;
475
+			if (! $resql) {
476
+				$error++;
477
+			}
453 478
 
454 479
 			// Add object linked
455 480
 			if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
456 481
 			{
457 482
 				foreach($this->linked_objects as $origin => $tmp_origin_id)
458 483
 				{
459
-				    if (is_array($tmp_origin_id))       // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
484
+				    if (is_array($tmp_origin_id)) {
485
+				    	// New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
460 486
 				    {
461 487
 				        foreach($tmp_origin_id as $origin_id)
462 488
 				        {
463 489
 				            $ret = $this->add_object_linked($origin, $origin_id);
490
+				    }
464 491
 				            if (! $ret)
465 492
 				            {
466 493
 				                dol_print_error($this->db);
467 494
 				                $error++;
468 495
 				            }
469 496
 				        }
470
-				    }
471
-				    else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
497
+				    } else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
472 498
 				    {
473 499
 				        $origin_id = $tmp_origin_id;
474 500
     					$ret = $this->add_object_linked($origin, $origin_id);
@@ -481,13 +507,17 @@  discard block
 block discarded – undo
481 507
 				}
482 508
 			}
483 509
 
484
-			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
510
+			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) {
511
+				// Get contact from origin object
485 512
 			{
486 513
 				$originforcontact = $this->origin;
514
+			}
487 515
 				$originidforcontact = $this->origin_id;
488
-				if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
516
+				if ($originforcontact == 'shipping') {
517
+					// shipment and order share the same contacts. If creating from shipment we take data of order
489 518
 				{
490 519
 				    require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
520
+				}
491 521
 				    $exp = new Expedition($this->db);
492 522
 				    $exp->fetch($this->origin_id);
493 523
 				    $exp->fetchObjectLinked();
@@ -496,8 +526,11 @@  discard block
 block discarded – undo
496 526
 				        foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
497 527
 				        {
498 528
 				            $originforcontact = 'commande';
499
-				            if (is_object($value)) $originidforcontact = $value->id;
500
-				            else $originidforcontact = $value;
529
+				            if (is_object($value)) {
530
+				            	$originidforcontact = $value->id;
531
+				            } else {
532
+				            	$originidforcontact = $value;
533
+				            }
501 534
 				            break; // We take first one
502 535
 				        }
503 536
 				    }
@@ -514,16 +547,19 @@  discard block
 block discarded – undo
514 547
 				        //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
515 548
 				        $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);    // May failed because of duplicate key or because code of contact type does not exists for new object
516 549
 				    }
550
+				} else {
551
+					dol_print_error($resqlcontact);
517 552
 				}
518
-				else dol_print_error($resqlcontact);
519 553
 			}
520 554
 
521 555
 			/*
522 556
 			 *  Insert lines of invoices into database
523 557
 			 */
524
-			if (count($this->lines) && is_object($this->lines[0]))	// If this->lines is array of InvoiceLines (preferred mode)
558
+			if (count($this->lines) && is_object($this->lines[0])) {
559
+				// If this->lines is array of InvoiceLines (preferred mode)
525 560
 			{
526 561
 				$fk_parent_line = 0;
562
+			}
527 563
 
528 564
 				dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
529 565
 				foreach ($this->lines as $i => $val)
@@ -557,8 +593,7 @@  discard block
 block discarded – undo
557 593
 						break;
558 594
 					}
559 595
 				}
560
-			}
561
-			else	// If this->lines is an array of invoice line arrays
596
+			} else	// If this->lines is an array of invoice line arrays
562 597
 			{
563 598
 				$fk_parent_line = 0;
564 599
 
@@ -570,7 +605,9 @@  discard block
 block discarded – undo
570 605
 
571 606
                 	// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
572 607
 				    //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE);  // convert recursively array into object.
573
-                	if (! is_object($line)) $line = (object) $line;
608
+                	if (! is_object($line)) {
609
+                		$line = (object) $line;
610
+                	}
574 611
 
575 612
 				    if ($result >= 0)
576 613
 					{
@@ -639,7 +676,9 @@  discard block
 block discarded – undo
639 676
 					}
640 677
 					$tva_tx = get_default_tva($mysoc,$soc,$prod->id);
641 678
 					$tva_npr = get_default_npr($mysoc,$soc,$prod->id);
642
-					if (empty($tva_tx)) $tva_npr=0;
679
+					if (empty($tva_tx)) {
680
+						$tva_npr=0;
681
+					}
643 682
 					$localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
644 683
 					$localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
645 684
 
@@ -698,7 +737,9 @@  discard block
 block discarded – undo
698 737
 					if (! $error)
699 738
 					{
700 739
 					    $result=$this->insertExtraFields();
701
-					    if ($result < 0) $error++;
740
+					    if ($result < 0) {
741
+					    	$error++;
742
+					    }
702 743
 					}
703 744
 						/*}
704 745
 					}
@@ -706,35 +747,33 @@  discard block
 block discarded – undo
706 747
 
707 748
                     // Call trigger
708 749
                     $result=$this->call_trigger('BILL_CREATE',$user);
709
-                    if ($result < 0) $error++;
750
+                    if ($result < 0) {
751
+                    	$error++;
752
+                    }
710 753
                     // End call triggers
711 754
 
712 755
 					if (! $error)
713 756
 					{
714 757
 						$this->db->commit();
715 758
 						return $this->id;
716
-					}
717
-					else
759
+					} else
718 760
 					{
719 761
 						$this->db->rollback();
720 762
 						return -4;
721 763
 					}
722
-				}
723
-				else
764
+				} else
724 765
 				{
725 766
 					$this->error=$langs->trans('FailedToUpdatePrice');
726 767
 					$this->db->rollback();
727 768
 					return -3;
728 769
 				}
729
-			}
730
-			else
770
+			} else
731 771
 			{
732 772
 				dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
733 773
 				$this->db->rollback();
734 774
 				return -2;
735 775
 			}
736
-		}
737
-		else
776
+		} else
738 777
 		{
739 778
 			$this->error=$this->db->error();
740 779
 			$this->db->rollback();
@@ -812,8 +851,7 @@  discard block
 block discarded – undo
812 851
 		{
813 852
 			$this->error=$facture->error;
814 853
 			$this->errors=$facture->errors;
815
-		}
816
-		elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
854
+		} elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
817 855
 		{
818 856
 			$this->fetchObjectLinked('', '', $object->id, 'facture');
819 857
 
@@ -849,8 +887,9 @@  discard block
 block discarded – undo
849 887
 		$this->db->begin();
850 888
 
851 889
 		// get extrafields so they will be clone
852
-		foreach($this->lines as $line)
853
-			$line->fetch_optionals($line->rowid);
890
+		foreach($this->lines as $line) {
891
+					$line->fetch_optionals($line->rowid);
892
+		}
854 893
 
855 894
 		// Load source object
856 895
 		$objFrom = clone $this;
@@ -892,26 +931,31 @@  discard block
 block discarded – undo
892 931
 		// Loop on each line of new invoice
893 932
 		foreach($this->lines as $i => $line)
894 933
 		{
895
-			if (($this->lines[$i]->info_bits & 0x02) == 0x02)	// We do not clone line of discounts
934
+			if (($this->lines[$i]->info_bits & 0x02) == 0x02) {
935
+				// We do not clone line of discounts
896 936
 			{
897 937
 				unset($this->lines[$i]);
938
+			}
898 939
 				unset($this->products[$i]);	// Tant que products encore utilise
899 940
 			}
900 941
 		}
901 942
 
902 943
 		// Create clone
903 944
 		$result=$this->create($user);
904
-		if ($result < 0) $error++;
905
-		else {
945
+		if ($result < 0) {
946
+			$error++;
947
+		} else {
906 948
 			// copy internal contacts
907
-			if ($this->copy_linked_contact($objFrom, 'internal') < 0)
908
-				$error++;
949
+			if ($this->copy_linked_contact($objFrom, 'internal') < 0) {
950
+							$error++;
951
+			}
909 952
 
910 953
 			// copy external contacts if same company
911 954
 			elseif ($objFrom->socid == $this->socid)
912 955
 			{
913
-				if ($this->copy_linked_contact($objFrom, 'external') < 0)
914
-					$error++;
956
+				if ($this->copy_linked_contact($objFrom, 'external') < 0) {
957
+									$error++;
958
+				}
915 959
 			}
916 960
 		}
917 961
 
@@ -923,12 +967,16 @@  discard block
 block discarded – undo
923 967
 				$parameters=array('objFrom'=>$objFrom);
924 968
 				$action='';
925 969
 				$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
926
-				if ($reshook < 0) $error++;
970
+				if ($reshook < 0) {
971
+					$error++;
972
+				}
927 973
 			}
928 974
 
929 975
             // Call trigger
930 976
             $result=$this->call_trigger('BILL_CLONE',$user);
931
-            if ($result < 0) $error++;
977
+            if ($result < 0) {
978
+            	$error++;
979
+            }
932 980
             // End call triggers
933 981
 		}
934 982
 
@@ -939,8 +987,7 @@  discard block
 block discarded – undo
939 987
 		{
940 988
 			$this->db->commit();
941 989
 			return $this->id;
942
-		}
943
-		else
990
+		} else
944 991
 		{
945 992
 			$this->db->rollback();
946 993
 			return -1;
@@ -996,8 +1043,9 @@  discard block
 block discarded – undo
996 1043
 
997 1044
             // get extrafields from original line
998 1045
 			$object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
999
-			foreach($object->lines[$i]->array_options as $options_key => $value)
1000
-				$line->array_options[$options_key] = $value;
1046
+			foreach($object->lines[$i]->array_options as $options_key => $value) {
1047
+							$line->array_options[$options_key] = $value;
1048
+			}
1001 1049
 
1002 1050
 			$this->lines[$i] = $line;
1003 1051
 		}
@@ -1020,8 +1068,9 @@  discard block
 block discarded – undo
1020 1068
 
1021 1069
         // get extrafields from original line
1022 1070
 		$object->fetch_optionals($object->id);
1023
-		foreach($object->array_options as $options_key => $value)
1024
-			$this->array_options[$options_key] = $value;
1071
+		foreach($object->array_options as $options_key => $value) {
1072
+					$this->array_options[$options_key] = $value;
1073
+		}
1025 1074
 
1026 1075
 		// Possibility to add external linked objects with hooks
1027 1076
 		$this->linked_objects[$this->origin] = $this->origin_id;
@@ -1040,15 +1089,19 @@  discard block
 block discarded – undo
1040 1089
 			$parameters=array('objFrom'=>$object);
1041 1090
 			$action='';
1042 1091
 			$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1043
-			if ($reshook < 0) $error++;
1092
+			if ($reshook < 0) {
1093
+				$error++;
1094
+			}
1044 1095
 
1045 1096
 			if (! $error)
1046 1097
 			{
1047 1098
 				return 1;
1099
+			} else {
1100
+				return -1;
1048 1101
 			}
1049
-			else return -1;
1102
+		} else {
1103
+			return -1;
1050 1104
 		}
1051
-		else return -1;
1052 1105
 	}
1053 1106
 
1054 1107
 	/**
@@ -1092,46 +1145,82 @@  discard block
 block discarded – undo
1092 1145
 	{
1093 1146
 		global $langs, $conf, $user, $form;
1094 1147
 
1095
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1148
+        if (! empty($conf->dol_no_mouse_hover)) {
1149
+        	$notooltip=1;
1150
+        }
1151
+        // Force disable tooltips
1096 1152
 
1097 1153
 		$result='';
1098 1154
 
1099
-		if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1100
-		else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
1155
+		if ($option == 'withdraw') {
1156
+			$url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1157
+		} else {
1158
+			$url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
1159
+		}
1101 1160
 
1102
-		if ($short) return $url;
1161
+		if ($short) {
1162
+			return $url;
1163
+		}
1103 1164
 
1104 1165
 		if ($option !== 'nolink')
1105 1166
 		{
1106 1167
 			// Add param to save lastsearch_values or not
1107 1168
 			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1108
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1109
-			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1169
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
1170
+				$add_save_lastsearch_values=1;
1171
+			}
1172
+			if ($add_save_lastsearch_values) {
1173
+				$url.='&save_lastsearch_values=1';
1174
+			}
1110 1175
 		}
1111 1176
 
1112 1177
 		$picto='bill';
1113
-		if ($this->type == self::TYPE_REPLACEMENT) $picto.='r';	// Replacement invoice
1114
-		if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a';	// Credit note
1115
-		if ($this->type == self::TYPE_DEPOSIT) $picto.='d';	// Deposit invoice
1178
+		if ($this->type == self::TYPE_REPLACEMENT) {
1179
+			$picto.='r';
1180
+		}
1181
+		// Replacement invoice
1182
+		if ($this->type == self::TYPE_CREDIT_NOTE) {
1183
+			$picto.='a';
1184
+		}
1185
+		// Credit note
1186
+		if ($this->type == self::TYPE_DEPOSIT) {
1187
+			$picto.='d';
1188
+		}
1189
+		// Deposit invoice
1116 1190
         $label='';
1117 1191
 
1118 1192
         if ($user->rights->facture->lire) {
1119 1193
             $label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
1120
-            if (! empty($this->ref))
1121
-                $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
1122
-            if (! empty($this->ref_client))
1123
-                $label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
1124
-            if (! empty($this->total_ht))
1125
-                $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1126
-            if (! empty($this->total_tva))
1127
-                $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1128
-            if (! empty($this->total_ttc))
1129
-                $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1130
-    		if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1131
-    		if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1132
-    		if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1133
-    		if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1134
-    		if ($moretitle) $label.=' - '.$moretitle;
1194
+            if (! empty($this->ref)) {
1195
+                            $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
1196
+            }
1197
+            if (! empty($this->ref_client)) {
1198
+                            $label .= '<br><b>' . $langs->trans('RefCustomer') . ':</b> ' . $this->ref_client;
1199
+            }
1200
+            if (! empty($this->total_ht)) {
1201
+                            $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1202
+            }
1203
+            if (! empty($this->total_tva)) {
1204
+                            $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1205
+            }
1206
+            if (! empty($this->total_ttc)) {
1207
+                            $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1208
+            }
1209
+    		if ($this->type == self::TYPE_REPLACEMENT) {
1210
+    			$label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref;
1211
+    		}
1212
+    		if ($this->type == self::TYPE_CREDIT_NOTE) {
1213
+    			$label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref;
1214
+    		}
1215
+    		if ($this->type == self::TYPE_DEPOSIT) {
1216
+    			$label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref;
1217
+    		}
1218
+    		if ($this->type == self::TYPE_SITUATION) {
1219
+    			$label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref;
1220
+    		}
1221
+    		if ($moretitle) {
1222
+    			$label.=' - '.$moretitle;
1223
+    		}
1135 1224
         }
1136 1225
 
1137 1226
 		$linkclose='';
@@ -1150,9 +1239,15 @@  discard block
 block discarded – undo
1150 1239
         $linkstart.=$linkclose.'>';
1151 1240
 		$linkend='</a>';
1152 1241
 
1153
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
1154
-		if ($withpicto && $withpicto != 2) $result.=' ';
1155
-		if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
1242
+        if ($withpicto) {
1243
+        	$result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
1244
+        }
1245
+		if ($withpicto && $withpicto != 2) {
1246
+			$result.=' ';
1247
+		}
1248
+		if ($withpicto != 2) {
1249
+			$result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
1250
+		}
1156 1251
 
1157 1252
 		if ($addlinktonotes)
1158 1253
 		{
@@ -1185,7 +1280,9 @@  discard block
 block discarded – undo
1185 1280
 	{
1186 1281
 		global $conf;
1187 1282
 
1188
-		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1283
+		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) {
1284
+			return -1;
1285
+		}
1189 1286
 
1190 1287
 		$sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount';
1191 1288
 		$sql.= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp';
@@ -1210,10 +1307,18 @@  discard block
 block discarded – undo
1210 1307
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')';
1211 1308
 		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1212 1309
 		$sql.= ' WHERE f.entity = '.$conf->entity;
1213
-		if ($rowid)   $sql.= " AND f.rowid=".$rowid;
1214
-		if ($ref)     $sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
1215
-		if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1216
-		if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
1310
+		if ($rowid) {
1311
+			$sql.= " AND f.rowid=".$rowid;
1312
+		}
1313
+		if ($ref) {
1314
+			$sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
1315
+		}
1316
+		if ($ref_ext) {
1317
+			$sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1318
+		}
1319
+		if ($ref_int) {
1320
+			$sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
1321
+		}
1217 1322
 
1218 1323
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1219 1324
 		$result = $this->db->query($sql);
@@ -1287,7 +1392,9 @@  discard block
 block discarded – undo
1287 1392
 					$this->fetchPreviousNextSituationInvoice();
1288 1393
 				}
1289 1394
 
1290
-				if ($this->statut == self::STATUS_DRAFT)	$this->brouillon = 1;
1395
+				if ($this->statut == self::STATUS_DRAFT) {
1396
+					$this->brouillon = 1;
1397
+				}
1291 1398
 
1292 1399
 				// Retrieve all extrafield for invoice
1293 1400
 				// fetch optionals attributes and labels
@@ -1309,15 +1416,13 @@  discard block
 block discarded – undo
1309 1416
 					return -3;
1310 1417
 				}
1311 1418
 				return 1;
1312
-			}
1313
-			else
1419
+			} else
1314 1420
 			{
1315 1421
 				$this->error='Bill with id '.$rowid.' or ref '.$ref.' not found';
1316 1422
 				dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
1317 1423
 				return 0;
1318 1424
 			}
1319
-		}
1320
-		else
1425
+		} else
1321 1426
 		{
1322 1427
 			$this->error=$this->db->error();
1323 1428
 			return -1;
@@ -1421,8 +1526,7 @@  discard block
 block discarded – undo
1421 1526
 			}
1422 1527
 			$this->db->free($result);
1423 1528
 			return 1;
1424
-		}
1425
-		else
1529
+		} else
1426 1530
 		{
1427 1531
 			$this->error=$this->db->error();
1428 1532
 			return -3;
@@ -1452,8 +1556,11 @@  discard block
 block discarded – undo
1452 1556
 				$invoice = new Facture($this->db);
1453 1557
 				if ($invoice->fetch($objp->rowid) > 0)
1454 1558
 				{
1455
-					if ($objp->situation_counter < $this->situation_counter) $this->tab_previous_situation_invoice[] = $invoice;
1456
-					else $this->tab_next_situation_invoice[] = $invoice;
1559
+					if ($objp->situation_counter < $this->situation_counter) {
1560
+						$this->tab_previous_situation_invoice[] = $invoice;
1561
+					} else {
1562
+						$this->tab_next_situation_invoice[] = $invoice;
1563
+					}
1457 1564
 				}
1458 1565
 			}
1459 1566
 		}
@@ -1472,17 +1579,40 @@  discard block
 block discarded – undo
1472 1579
 		$error=0;
1473 1580
 
1474 1581
 		// Clean parameters
1475
-		if (empty($this->type)) $this->type= self::TYPE_STANDARD;
1476
-		if (isset($this->facnumber)) $this->facnumber=trim($this->ref);
1477
-		if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
1478
-		if (isset($this->increment)) $this->increment=trim($this->increment);
1479
-		if (isset($this->close_code)) $this->close_code=trim($this->close_code);
1480
-		if (isset($this->close_note)) $this->close_note=trim($this->close_note);
1481
-		if (isset($this->note) || isset($this->note_private)) $this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private));		// deprecated
1482
-		if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1483
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1484
-		if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
1485
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1582
+		if (empty($this->type)) {
1583
+			$this->type= self::TYPE_STANDARD;
1584
+		}
1585
+		if (isset($this->facnumber)) {
1586
+			$this->facnumber=trim($this->ref);
1587
+		}
1588
+		if (isset($this->ref_client)) {
1589
+			$this->ref_client=trim($this->ref_client);
1590
+		}
1591
+		if (isset($this->increment)) {
1592
+			$this->increment=trim($this->increment);
1593
+		}
1594
+		if (isset($this->close_code)) {
1595
+			$this->close_code=trim($this->close_code);
1596
+		}
1597
+		if (isset($this->close_note)) {
1598
+			$this->close_note=trim($this->close_note);
1599
+		}
1600
+		if (isset($this->note) || isset($this->note_private)) {
1601
+			$this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private));
1602
+		}
1603
+		// deprecated
1604
+		if (isset($this->note) || isset($this->note_private)) {
1605
+			$this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1606
+		}
1607
+		if (isset($this->note_public)) {
1608
+			$this->note_public=trim($this->note_public);
1609
+		}
1610
+		if (isset($this->modelpdf)) {
1611
+			$this->modelpdf=trim($this->modelpdf);
1612
+		}
1613
+		if (isset($this->import_key)) {
1614
+			$this->import_key=trim($this->import_key);
1615
+		}
1486 1616
 		if (empty($this->situation_cycle_ref)) {
1487 1617
 			$this->situation_cycle_ref = 'null';
1488 1618
 		}
@@ -1553,7 +1683,9 @@  discard block
 block discarded – undo
1553 1683
 			{
1554 1684
 	            // Call trigger
1555 1685
 	            $result=$this->call_trigger('BILL_MODIFY',$user);
1556
-	            if ($result < 0) $error++;
1686
+	            if ($result < 0) {
1687
+	            	$error++;
1688
+	            }
1557 1689
 	            // End call triggers
1558 1690
 			}
1559 1691
 		}
@@ -1568,8 +1700,7 @@  discard block
 block discarded – undo
1568 1700
 			}
1569 1701
 			$this->db->rollback();
1570 1702
 			return -1*$error;
1571
-		}
1572
-		else
1703
+		} else
1573 1704
 		{
1574 1705
 			$this->db->commit();
1575 1706
 			return 1;
@@ -1597,9 +1728,11 @@  discard block
 block discarded – undo
1597 1728
 
1598 1729
 		if ($result > 0)
1599 1730
 		{
1600
-			if ($remise->fk_facture)	// Protection against multiple submission
1731
+			if ($remise->fk_facture) {
1732
+				// Protection against multiple submission
1601 1733
 			{
1602 1734
 				$this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1735
+			}
1603 1736
 				$this->db->rollback();
1604 1737
 				return -5;
1605 1738
 			}
@@ -1655,22 +1788,19 @@  discard block
 block discarded – undo
1655 1788
 
1656 1789
 					$this->db->commit();
1657 1790
 					return 1;
1658
-				}
1659
-				else
1791
+				} else
1660 1792
 				{
1661 1793
 					$this->error=$facligne->error;
1662 1794
 					$this->db->rollback();
1663 1795
 					return -1;
1664 1796
 				}
1665
-			}
1666
-			else
1797
+			} else
1667 1798
 			{
1668 1799
 				$this->error=$facligne->error;
1669 1800
 				$this->db->rollback();
1670 1801
 				return -2;
1671 1802
 			}
1672
-		}
1673
-		else
1803
+		} else
1674 1804
 		{
1675 1805
 			$this->db->rollback();
1676 1806
 			return -3;
@@ -1693,10 +1823,11 @@  discard block
 block discarded – undo
1693 1823
 		$this->db->begin();
1694 1824
 
1695 1825
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
1696
-		if (empty($ref_client))
1697
-			$sql .= ' SET ref_client = NULL';
1698
-		else
1699
-			$sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
1826
+		if (empty($ref_client)) {
1827
+					$sql .= ' SET ref_client = NULL';
1828
+		} else {
1829
+					$sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
1830
+		}
1700 1831
 		$sql .= ' WHERE rowid = '.$this->id;
1701 1832
 
1702 1833
 		dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
@@ -1716,7 +1847,9 @@  discard block
 block discarded – undo
1716 1847
 		{
1717 1848
 			// Call trigger
1718 1849
 			$result=$this->call_trigger('BILL_MODIFY',$user);
1719
-			if ($result < 0) $error++;
1850
+			if ($result < 0) {
1851
+				$error++;
1852
+			}
1720 1853
 			// End call triggers
1721 1854
 		}
1722 1855
 
@@ -1727,8 +1860,7 @@  discard block
 block discarded – undo
1727 1860
 
1728 1861
 			$this->db->commit();
1729 1862
 			return 1;
1730
-		}
1731
-		else
1863
+		} else
1732 1864
 		{
1733 1865
 			foreach($this->errors as $errmsg)
1734 1866
 			{
@@ -1760,7 +1892,9 @@  discard block
 block discarded – undo
1760 1892
 		// Test to avoid invoice deletion (allowed if draft)
1761 1893
 		$test = $this->is_erasable();
1762 1894
 
1763
-		if ($test <= 0) return $test;
1895
+		if ($test <= 0) {
1896
+			return $test;
1897
+		}
1764 1898
 
1765 1899
 		$error=0;
1766 1900
 
@@ -1770,7 +1904,9 @@  discard block
 block discarded – undo
1770 1904
 		{
1771 1905
             // Call trigger
1772 1906
             $result=$this->call_trigger('BILL_DELETE',$user);
1773
-            if ($result < 0) $error++;
1907
+            if ($result < 0) {
1908
+            	$error++;
1909
+            }
1774 1910
             // End call triggers
1775 1911
 		}
1776 1912
 
@@ -1788,7 +1924,9 @@  discard block
 block discarded – undo
1788 1924
 		{
1789 1925
 			// Delete linked object
1790 1926
 			$res = $this->deleteObjectLinked();
1791
-			if ($res < 0) $error++;
1927
+			if ($res < 0) {
1928
+				$error++;
1929
+			}
1792 1930
 		}
1793 1931
 
1794 1932
 		if (! $error)
@@ -1837,8 +1975,12 @@  discard block
 block discarded – undo
1837 1975
 						$mouvP = new MouvementStock($this->db);
1838 1976
 						$mouvP->origin = &$this;
1839 1977
 						// We decrease stock for product
1840
-						if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr",$this->ref));
1841
-						else $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr",$this->ref));	// we use 0 for price, to not change the weighted average value
1978
+						if ($this->type == self::TYPE_CREDIT_NOTE) {
1979
+							$result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr",$this->ref));
1980
+						} else {
1981
+							$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr",$this->ref));
1982
+						}
1983
+						// we use 0 for price, to not change the weighted average value
1842 1984
 					}
1843 1985
 				}
1844 1986
 			}
@@ -1864,22 +2006,28 @@  discard block
 block discarded – undo
1864 2006
 					{
1865 2007
 						$dir = $conf->facture->dir_output . "/" . $ref;
1866 2008
 						$file = $conf->facture->dir_output . "/" . $ref . "/" . $ref . ".pdf";
1867
-						if (file_exists($file))	// We must delete all files before deleting directory
2009
+						if (file_exists($file)) {
2010
+							// We must delete all files before deleting directory
1868 2011
 						{
1869 2012
 							$ret=dol_delete_preview($this);
2013
+						}
1870 2014
 
1871
-							if (! dol_delete_file($file,0,0,0,$this)) // For triggers
2015
+							if (! dol_delete_file($file,0,0,0,$this)) {
2016
+								// For triggers
1872 2017
 							{
1873 2018
 								$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
2019
+							}
1874 2020
 								$this->db->rollback();
1875 2021
 								return 0;
1876 2022
 							}
1877 2023
 						}
1878 2024
 						if (file_exists($dir))
1879 2025
 						{
1880
-							if (! dol_delete_dir_recursive($dir)) // For remove dir and meta
2026
+							if (! dol_delete_dir_recursive($dir)) {
2027
+								// For remove dir and meta
1881 2028
 							{
1882 2029
 								$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
2030
+							}
1883 2031
 								$this->db->rollback();
1884 2032
 								return 0;
1885 2033
 							}
@@ -1888,22 +2036,19 @@  discard block
 block discarded – undo
1888 2036
 
1889 2037
 					$this->db->commit();
1890 2038
 					return 1;
1891
-				}
1892
-				else
2039
+				} else
1893 2040
 				{
1894 2041
 					$this->error=$this->db->lasterror()." sql=".$sql;
1895 2042
 					$this->db->rollback();
1896 2043
 					return -6;
1897 2044
 				}
1898
-			}
1899
-			else
2045
+			} else
1900 2046
 			{
1901 2047
 				$this->error=$this->db->lasterror()." sql=".$sql;
1902 2048
 				$this->db->rollback();
1903 2049
 				return -4;
1904 2050
 			}
1905
-		}
1906
-		else
2051
+		} else
1907 2052
 		{
1908 2053
 			$this->db->rollback();
1909 2054
 			return -2;
@@ -1930,9 +2075,15 @@  discard block
 block discarded – undo
1930 2075
 			dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG);
1931 2076
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
1932 2077
 			$sql.= ' fk_statut='.self::STATUS_CLOSED;
1933
-			if (! $close_code) $sql.= ', paye=1';
1934
-			if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
1935
-			if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
2078
+			if (! $close_code) {
2079
+				$sql.= ', paye=1';
2080
+			}
2081
+			if ($close_code) {
2082
+				$sql.= ", close_code='".$this->db->escape($close_code)."'";
2083
+			}
2084
+			if ($close_note) {
2085
+				$sql.= ", close_note='".$this->db->escape($close_note)."'";
2086
+			}
1936 2087
 			$sql.= ' WHERE rowid = '.$this->id;
1937 2088
 
1938 2089
 			dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
@@ -1941,10 +2092,11 @@  discard block
 block discarded – undo
1941 2092
 			{
1942 2093
 	            // Call trigger
1943 2094
 	            $result=$this->call_trigger('BILL_PAYED',$user);
1944
-	            if ($result < 0) $error++;
2095
+	            if ($result < 0) {
2096
+	            	$error++;
2097
+	            }
1945 2098
 	            // End call triggers
1946
-			}
1947
-			else
2099
+			} else
1948 2100
 			{
1949 2101
 				$error++;
1950 2102
 				$this->error=$this->db->lasterror();
@@ -1954,14 +2106,12 @@  discard block
 block discarded – undo
1954 2106
 			{
1955 2107
 				$this->db->commit();
1956 2108
 				return 1;
1957
-			}
1958
-			else
2109
+			} else
1959 2110
 			{
1960 2111
 				$this->db->rollback();
1961 2112
 				return -1;
1962 2113
 			}
1963
-		}
1964
-		else
2114
+		} else
1965 2115
 		{
1966 2116
 			return 0;
1967 2117
 		}
@@ -1992,10 +2142,11 @@  discard block
 block discarded – undo
1992 2142
 		{
1993 2143
             // Call trigger
1994 2144
             $result=$this->call_trigger('BILL_UNPAYED',$user);
1995
-            if ($result < 0) $error++;
2145
+            if ($result < 0) {
2146
+            	$error++;
2147
+            }
1996 2148
             // End call triggers
1997
-		}
1998
-		else
2149
+		} else
1999 2150
 		{
2000 2151
 			$error++;
2001 2152
 			$this->error=$this->db->error();
@@ -2006,8 +2157,7 @@  discard block
 block discarded – undo
2006 2157
 		{
2007 2158
 			$this->db->commit();
2008 2159
 			return 1;
2009
-		}
2010
-		else
2160
+		} else
2011 2161
 		{
2012 2162
 			$this->db->rollback();
2013 2163
 			return -1;
@@ -2034,8 +2184,12 @@  discard block
 block discarded – undo
2034 2184
 
2035 2185
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2036 2186
 		$sql.= ' fk_statut='.self::STATUS_ABANDONED;
2037
-		if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
2038
-		if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
2187
+		if ($close_code) {
2188
+			$sql.= ", close_code='".$this->db->escape($close_code)."'";
2189
+		}
2190
+		if ($close_note) {
2191
+			$sql.= ", close_note='".$this->db->escape($close_note)."'";
2192
+		}
2039 2193
 		$sql.= ' WHERE rowid = '.$this->id;
2040 2194
 
2041 2195
 		$resql = $this->db->query($sql);
@@ -2061,15 +2215,13 @@  discard block
 block discarded – undo
2061 2215
 
2062 2216
 				$this->db->commit();
2063 2217
 				return 1;
2064
-			}
2065
-			else
2218
+			} else
2066 2219
 			{
2067 2220
 				$this->error=$this->db->error()." sql=".$sql;
2068 2221
 				$this->db->rollback();
2069 2222
 				return -1;
2070 2223
 			}
2071
-		}
2072
-		else
2224
+		} else
2073 2225
 		{
2074 2226
 			$this->error=$this->db->error()." sql=".$sql;
2075 2227
 			$this->db->rollback();
@@ -2124,12 +2276,14 @@  discard block
 block discarded – undo
2124 2276
 		$this->db->begin();
2125 2277
 
2126 2278
 		// Check parameters
2127
-		if ($this->type == self::TYPE_REPLACEMENT)		// si facture de remplacement
2279
+		if ($this->type == self::TYPE_REPLACEMENT) {
2280
+			// si facture de remplacement
2128 2281
 		{
2129 2282
 			// Controle que facture source connue
2130 2283
 			if ($this->fk_facture_source <= 0)
2131 2284
 			{
2132 2285
 				$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("InvoiceReplacement"));
2286
+		}
2133 2287
 				$this->db->rollback();
2134 2288
 				return -10;
2135 2289
 			}
@@ -2168,17 +2322,17 @@  discard block
 block discarded – undo
2168 2322
 		if ($force_number)
2169 2323
 		{
2170 2324
 			$num = $force_number;
2171
-		}
2172
-		else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
2325
+		} else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) {
2326
+			// empty should not happened, but when it occurs, the test save life
2173 2327
 		{
2174 2328
 			if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2175 2329
 			{
2176 2330
 				$this->date=dol_now();
2331
+		}
2177 2332
 				$this->date_lim_reglement=$this->calculate_date_lim_reglement();
2178 2333
 			}
2179 2334
 			$num = $this->getNextNumRef($this->thirdparty);
2180
-		}
2181
-		else
2335
+		} else
2182 2336
 		{
2183 2337
 			$num = $this->ref;
2184 2338
 		}
@@ -2191,9 +2345,11 @@  discard block
 block discarded – undo
2191 2345
 			// Validate
2192 2346
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2193 2347
 			$sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
2194
-			if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))	// If option enabled, we force invoice date
2348
+			if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
2349
+				// If option enabled, we force invoice date
2195 2350
 			{
2196 2351
 				$sql.= ", datef='".$this->db->idate($this->date)."'";
2352
+			}
2197 2353
 				$sql.= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
2198 2354
 			}
2199 2355
 			$sql.= ' WHERE rowid = '.$this->id;
@@ -2232,8 +2388,11 @@  discard block
 block discarded – undo
2232 2388
 							$mouvP = new MouvementStock($this->db);
2233 2389
 							$mouvP->origin = &$this;
2234 2390
 							// We decrease stock for product
2235
-							if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr",$num));
2236
-							else $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
2391
+							if ($this->type == self::TYPE_CREDIT_NOTE) {
2392
+								$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr",$num));
2393
+							} else {
2394
+								$result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
2395
+							}
2237 2396
 							if ($result < 0) {
2238 2397
 								$error++;
2239 2398
 							}
@@ -2247,7 +2406,9 @@  discard block
 block discarded – undo
2247 2406
 			{
2248 2407
 	            // Call trigger
2249 2408
 	            $result=$this->call_trigger('BILL_VALIDATE',$user);
2250
-	            if ($result < 0) $error++;
2409
+	            if ($result < 0) {
2410
+	            	$error++;
2411
+	            }
2251 2412
 	            // End call triggers
2252 2413
 			}
2253 2414
 
@@ -2317,8 +2478,7 @@  discard block
 block discarded – undo
2317 2478
     				}
2318 2479
                 }
2319 2480
 			}
2320
-		}
2321
-		else
2481
+		} else
2322 2482
 		{
2323 2483
 			$error++;
2324 2484
 		}
@@ -2327,8 +2487,7 @@  discard block
 block discarded – undo
2327 2487
 		{
2328 2488
 			$this->db->commit();
2329 2489
 			return 1;
2330
-		}
2331
-		else
2490
+		} else
2332 2491
 		{
2333 2492
 			$this->db->rollback();
2334 2493
 			return -1;
@@ -2417,8 +2576,12 @@  discard block
 block discarded – undo
2417 2576
 						$mouvP = new MouvementStock($this->db);
2418 2577
 						$mouvP->origin = &$this;
2419 2578
 						// We decrease stock for product
2420
-						if ($this->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
2421
-						else $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));	// we use 0 for price, to not change the weighted average value
2579
+						if ($this->type == self::TYPE_CREDIT_NOTE) {
2580
+							$result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
2581
+						} else {
2582
+							$result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
2583
+						}
2584
+						// we use 0 for price, to not change the weighted average value
2422 2585
 					}
2423 2586
 				}
2424 2587
 			}
@@ -2446,14 +2609,12 @@  discard block
 block discarded – undo
2446 2609
 			{
2447 2610
 				$this->db->commit();
2448 2611
 				return 1;
2449
-			}
2450
-			else
2612
+			} else
2451 2613
 			{
2452 2614
 				$this->db->rollback();
2453 2615
 				return -1;
2454 2616
 			}
2455
-		}
2456
-		else
2617
+		} else
2457 2618
 		{
2458 2619
 			$this->error=$this->db->error();
2459 2620
 			$this->db->rollback();
@@ -2513,17 +2674,39 @@  discard block
 block discarded – undo
2513 2674
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2514 2675
 
2515 2676
 		// Clean parameters
2516
-		if (empty($remise_percent)) $remise_percent=0;
2517
-		if (empty($qty)) $qty=0;
2518
-		if (empty($info_bits)) $info_bits=0;
2519
-		if (empty($rang)) $rang=0;
2520
-		if (empty($ventil)) $ventil=0;
2521
-		if (empty($txtva)) $txtva=0;
2522
-		if (empty($txlocaltax1)) $txlocaltax1=0;
2523
-		if (empty($txlocaltax2)) $txlocaltax2=0;
2524
-		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
2525
-		if (empty($fk_prev_id)) $fk_prev_id = 'null';
2526
-		if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2677
+		if (empty($remise_percent)) {
2678
+			$remise_percent=0;
2679
+		}
2680
+		if (empty($qty)) {
2681
+			$qty=0;
2682
+		}
2683
+		if (empty($info_bits)) {
2684
+			$info_bits=0;
2685
+		}
2686
+		if (empty($rang)) {
2687
+			$rang=0;
2688
+		}
2689
+		if (empty($ventil)) {
2690
+			$ventil=0;
2691
+		}
2692
+		if (empty($txtva)) {
2693
+			$txtva=0;
2694
+		}
2695
+		if (empty($txlocaltax1)) {
2696
+			$txlocaltax1=0;
2697
+		}
2698
+		if (empty($txlocaltax2)) {
2699
+			$txlocaltax2=0;
2700
+		}
2701
+		if (empty($fk_parent_line) || $fk_parent_line < 0) {
2702
+			$fk_parent_line=0;
2703
+		}
2704
+		if (empty($fk_prev_id)) {
2705
+			$fk_prev_id = 'null';
2706
+		}
2707
+		if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
2708
+			$situation_percent = 100;
2709
+		}
2527 2710
 
2528 2711
 		$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2529 2712
 
@@ -2547,14 +2730,15 @@  discard block
 block discarded – undo
2547 2730
 		if ($price_base_type=='HT')
2548 2731
 		{
2549 2732
 			$pu=$pu_ht;
2550
-		}
2551
-		else
2733
+		} else
2552 2734
 		{
2553 2735
 			$pu=$pu_ttc;
2554 2736
 		}
2555 2737
 
2556 2738
 		// Check parameters
2557
-		if ($type < 0) return -1;
2739
+		if ($type < 0) {
2740
+			return -1;
2741
+		}
2558 2742
 
2559 2743
 		if (! empty($this->brouillon))
2560 2744
 		{
@@ -2666,7 +2850,9 @@  discard block
 block discarded – undo
2666 2850
 			if ($result > 0)
2667 2851
 			{
2668 2852
 				// Reorder if child line
2669
-				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
2853
+				if (! empty($fk_parent_line)) {
2854
+					$this->line_order(true,'DESC');
2855
+				}
2670 2856
 
2671 2857
 				// Mise a jour informations denormalisees au niveau de la facture meme
2672 2858
 				$result=$this->update_price(1,'auto',0,$mysoc);	// The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
@@ -2674,15 +2860,13 @@  discard block
 block discarded – undo
2674 2860
 				{
2675 2861
 					$this->db->commit();
2676 2862
 					return $this->line->rowid;
2677
-				}
2678
-				else
2863
+				} else
2679 2864
 				{
2680 2865
 					$this->error=$this->db->error();
2681 2866
 					$this->db->rollback();
2682 2867
 					return -1;
2683 2868
 				}
2684
-			}
2685
-			else
2869
+			} else
2686 2870
 			{
2687 2871
 				$this->error=$this->line->error;
2688 2872
 				$this->db->rollback();
@@ -2740,7 +2924,9 @@  discard block
 block discarded – undo
2740 2924
 			{
2741 2925
 				if (!$this->checkProgressLine($rowid, $situation_percent))
2742 2926
 				{
2743
-					if (!$this->error) $this->error=$langs->trans('invoiceLineProgressError');
2927
+					if (!$this->error) {
2928
+						$this->error=$langs->trans('invoiceLineProgressError');
2929
+					}
2744 2930
 					return -3;
2745 2931
 				}
2746 2932
 			}
@@ -2748,10 +2934,18 @@  discard block
 block discarded – undo
2748 2934
 			$this->db->begin();
2749 2935
 
2750 2936
 			// Clean parameters
2751
-			if (empty($qty)) $qty=0;
2752
-			if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
2753
-			if (empty($special_code) || $special_code == 3) $special_code=0;
2754
-			if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
2937
+			if (empty($qty)) {
2938
+				$qty=0;
2939
+			}
2940
+			if (empty($fk_parent_line) || $fk_parent_line < 0) {
2941
+				$fk_parent_line=0;
2942
+			}
2943
+			if (empty($special_code) || $special_code == 3) {
2944
+				$special_code=0;
2945
+			}
2946
+			if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
2947
+				$situation_percent = 100;
2948
+			}
2755 2949
 
2756 2950
 			$remise_percent	= price2num($remise_percent);
2757 2951
 			$qty			= price2num($qty);
@@ -2762,7 +2956,9 @@  discard block
 block discarded – undo
2762 2956
 			$txlocaltax2	= price2num($txlocaltax2);
2763 2957
 
2764 2958
 			// Check parameters
2765
-			if ($type < 0) return -1;
2959
+			if ($type < 0) {
2960
+				return -1;
2961
+			}
2766 2962
 
2767 2963
 			// Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
2768 2964
 			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
@@ -2882,21 +3078,21 @@  discard block
 block discarded – undo
2882 3078
 			if ($result > 0)
2883 3079
 			{
2884 3080
 				// Reorder if child line
2885
-				if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
3081
+				if (! empty($fk_parent_line)) {
3082
+					$this->line_order(true,'DESC');
3083
+				}
2886 3084
 
2887 3085
 				// Mise a jour info denormalisees au niveau facture
2888 3086
 				$this->update_price(1);
2889 3087
 				$this->db->commit();
2890 3088
 				return $result;
2891
-			}
2892
-			else
3089
+			} else
2893 3090
 			{
2894 3091
 			    $this->error=$this->line->error;
2895 3092
 				$this->db->rollback();
2896 3093
 				return -1;
2897 3094
 			}
2898
-		}
2899
-		else
3095
+		} else
2900 3096
 		{
2901 3097
 			$this->error="Invoice statut makes operation forbidden";
2902 3098
 			return -2;
@@ -2926,8 +3122,11 @@  discard block
 block discarded – undo
2926 3122
 
2927 3123
 		$obj = $this->db->fetch_object($result);
2928 3124
 
2929
-		if ($obj === null) return true;
2930
-		else return $situation_percent < $obj->situation_percent;
3125
+		if ($obj === null) {
3126
+			return true;
3127
+		} else {
3128
+			return $situation_percent < $obj->situation_percent;
3129
+		}
2931 3130
 	}
2932 3131
 
2933 3132
 	/**
@@ -2944,7 +3143,9 @@  discard block
 block discarded – undo
2944 3143
 		include_once(DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php');
2945 3144
 
2946 3145
 		// Cap percentages to 100
2947
-		if ($percent > 100) $percent = 100;
3146
+		if ($percent > 100) {
3147
+			$percent = 100;
3148
+		}
2948 3149
 		$line->situation_percent = $percent;
2949 3150
 		$tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $percent);
2950 3151
 		$line->total_ht = $tabprice[0];
@@ -2997,7 +3198,9 @@  discard block
 block discarded – undo
2997 3198
 
2998 3199
 		// For triggers
2999 3200
 		$result = $line->fetch($rowid);
3000
-		if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors);
3201
+		if (! ($result > 0)) {
3202
+			dol_print_error($db, $line->error, $line->errors);
3203
+		}
3001 3204
 
3002 3205
 		if ($line->delete($user) > 0)
3003 3206
 		{
@@ -3007,15 +3210,13 @@  discard block
 block discarded – undo
3007 3210
 			{
3008 3211
 				$this->db->commit();
3009 3212
 				return 1;
3010
-			}
3011
-			else
3213
+			} else
3012 3214
 			{
3013 3215
 				$this->db->rollback();
3014 3216
 				$this->error=$this->db->lasterror();
3015 3217
 				return -1;
3016 3218
 			}
3017
-		}
3018
-		else
3219
+		} else
3019 3220
 		{
3020 3221
 			$this->db->rollback();
3021 3222
 			$this->error=$line->error;
@@ -3034,7 +3235,9 @@  discard block
 block discarded – undo
3034 3235
 	function set_remise($user, $remise, $notrigger=0)
3035 3236
 	{
3036 3237
 		// Clean parameters
3037
-		if (empty($remise)) $remise=0;
3238
+		if (empty($remise)) {
3239
+			$remise=0;
3240
+		}
3038 3241
 
3039 3242
 		if ($user->rights->facture->creer)
3040 3243
 		{
@@ -3061,7 +3264,9 @@  discard block
 block discarded – undo
3061 3264
 			{
3062 3265
 				// Call trigger
3063 3266
 				$result=$this->call_trigger('BILL_MODIFY',$user);
3064
-				if ($result < 0) $error++;
3267
+				if ($result < 0) {
3268
+					$error++;
3269
+				}
3065 3270
 				// End call triggers
3066 3271
 			}
3067 3272
 
@@ -3072,8 +3277,7 @@  discard block
 block discarded – undo
3072 3277
 
3073 3278
 				$this->db->commit();
3074 3279
 				return 1;
3075
-			}
3076
-			else
3280
+			} else
3077 3281
 			{
3078 3282
 				foreach($this->errors as $errmsg)
3079 3283
 				{
@@ -3097,7 +3301,9 @@  discard block
 block discarded – undo
3097 3301
 	 */
3098 3302
 	function set_remise_absolue($user, $remise, $notrigger=0)
3099 3303
 	{
3100
-		if (empty($remise)) $remise=0;
3304
+		if (empty($remise)) {
3305
+			$remise=0;
3306
+		}
3101 3307
 
3102 3308
 		if ($user->rights->facture->creer)
3103 3309
 		{
@@ -3131,7 +3337,9 @@  discard block
 block discarded – undo
3131 3337
 			{
3132 3338
 				// Call trigger
3133 3339
 				$result=$this->call_trigger('BILL_MODIFY',$user);
3134
-				if ($result < 0) $error++;
3340
+				if ($result < 0) {
3341
+					$error++;
3342
+				}
3135 3343
 				// End call triggers
3136 3344
 			}
3137 3345
 
@@ -3139,8 +3347,7 @@  discard block
 block discarded – undo
3139 3347
 			{
3140 3348
 				$this->db->commit();
3141 3349
 				return 1;
3142
-			}
3143
-			else
3350
+			} else
3144 3351
 			{
3145 3352
 				foreach($this->errors as $errmsg)
3146 3353
 				{
@@ -3182,7 +3389,9 @@  discard block
 block discarded – undo
3182 3389
 		$sql.= ' AND pf.'.$field2.' = p.rowid';
3183 3390
 		$sql.= ' AND p.fk_paiement = t.id';
3184 3391
 		$sql.= ' AND t.entity IN (' . getEntity('c_paiement').')';
3185
-		if ($filtertype) $sql.=" AND t.code='PRE'";
3392
+		if ($filtertype) {
3393
+			$sql.=" AND t.code='PRE'";
3394
+		}
3186 3395
 
3187 3396
 		dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
3188 3397
 		$resql=$this->db->query($sql);
@@ -3198,8 +3407,7 @@  discard block
 block discarded – undo
3198 3407
 			}
3199 3408
 			$this->db->free($resql);
3200 3409
 			return $retarray;
3201
-		}
3202
-		else
3410
+		} else
3203 3411
 		{
3204 3412
 			$this->error=$this->db->lasterror();
3205 3413
 			dol_print_error($this->db);
@@ -3222,9 +3430,13 @@  discard block
 block discarded – undo
3222 3430
 		$langs->load("bills");
3223 3431
 
3224 3432
 		// Clean parameters (if not defined or using deprecated value)
3225
-		if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON='mod_facture_terre';
3226
-		else if ($conf->global->FACTURE_ADDON=='terre') $conf->global->FACTURE_ADDON='mod_facture_terre';
3227
-		else if ($conf->global->FACTURE_ADDON=='mercure') $conf->global->FACTURE_ADDON='mod_facture_mercure';
3433
+		if (empty($conf->global->FACTURE_ADDON)) {
3434
+			$conf->global->FACTURE_ADDON='mod_facture_terre';
3435
+		} else if ($conf->global->FACTURE_ADDON=='terre') {
3436
+			$conf->global->FACTURE_ADDON='mod_facture_terre';
3437
+		} else if ($conf->global->FACTURE_ADDON=='mercure') {
3438
+			$conf->global->FACTURE_ADDON='mod_facture_mercure';
3439
+		}
3228 3440
 
3229 3441
 		if (! empty($conf->global->FACTURE_ADDON))
3230 3442
 		{
@@ -3288,8 +3500,7 @@  discard block
 block discarded – undo
3288 3500
 			}
3289 3501
 
3290 3502
 			return $numref;
3291
-		}
3292
-		else
3503
+		} else
3293 3504
 		{
3294 3505
 			$langs->load("errors");
3295 3506
 			print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
@@ -3334,8 +3545,7 @@  discard block
 block discarded – undo
3334 3545
 				$this->date_validation   = $this->db->jdate($obj->datev);	// Should be in log table
3335 3546
 			}
3336 3547
 			$this->db->free($result);
3337
-		}
3338
-		else
3548
+		} else
3339 3549
 		{
3340 3550
 			dol_print_error($this->db);
3341 3551
 		}
@@ -3362,8 +3572,7 @@  discard block
 block discarded – undo
3362 3572
 		if ($ventilExportCompta <> 0)
3363 3573
 		{
3364 3574
 			return 1;
3365
-		}
3366
-		else
3575
+		} else
3367 3576
 		{
3368 3577
 			return 0;
3369 3578
 		}
@@ -3386,13 +3595,19 @@  discard block
 block discarded – undo
3386 3595
 		// we check if invoice is a temporary number (PROVxxxx)
3387 3596
 		$tmppart = substr($this->ref, 1, 4);
3388 3597
 
3389
-		if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined
3598
+		if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') {
3599
+			// If draft invoice and ref not yet defined
3390 3600
 		{
3391 3601
 			return 1;
3392 3602
 		}
3603
+		}
3393 3604
 
3394
-		if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2;
3395
-		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED))  return 0;
3605
+		if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) {
3606
+			return 2;
3607
+		}
3608
+		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) {
3609
+			return 0;
3610
+		}
3396 3611
 
3397 3612
 		// TODO Test if there is at least one payment. If yes, refuse to delete.
3398 3613
 		// ...
@@ -3401,15 +3616,21 @@  discard block
 block discarded – undo
3401 3616
 		if ($tmppart !== 'PROV')
3402 3617
 		{
3403 3618
 			// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
3404
-			if (empty($this->thirdparty)) $this->fetch_thirdparty();
3619
+			if (empty($this->thirdparty)) {
3620
+				$this->fetch_thirdparty();
3621
+			}
3405 3622
 
3406 3623
 			$maxfacnumber = $this->getNextNumRef($this->thirdparty,'last');
3407 3624
 			$ventilExportCompta = $this->getVentilExportCompta();
3408 3625
 
3409 3626
 			// If there is no invoice into the reset range and not already dispatched, we can delete
3410
-			if ($maxfacnumber == '' && $ventilExportCompta == 0) return 3;
3627
+			if ($maxfacnumber == '' && $ventilExportCompta == 0) {
3628
+				return 3;
3629
+			}
3411 3630
 			// If invoice to delete is last one and not already dispatched, we can delete
3412
-			if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 4;
3631
+			if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) {
3632
+				return 4;
3633
+			}
3413 3634
 
3414 3635
 			if ($this->situation_cycle_ref) {
3415 3636
 				$last = $this->is_last_in_cycle();
@@ -3442,18 +3663,30 @@  discard block
 block discarded – undo
3442 3663
 
3443 3664
 		$sql = "SELECT s.rowid, s.nom as name, s.client,";
3444 3665
 		$sql.= " f.rowid as fid, f.facnumber as ref, f.datef as df";
3445
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
3666
+		if (! $user->rights->societe->client->voir && ! $socid) {
3667
+			$sql .= ", sc.fk_soc, sc.fk_user";
3668
+		}
3446 3669
 		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
3447
-		if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3670
+		if (! $user->rights->societe->client->voir && ! $socid) {
3671
+			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3672
+		}
3448 3673
 		$sql.= " WHERE f.entity = ".$conf->entity;
3449 3674
 		$sql.= " AND f.fk_soc = s.rowid";
3450
-		if (! $user->rights->societe->client->voir && ! $socid) //restriction
3675
+		if (! $user->rights->societe->client->voir && ! $socid) {
3676
+			//restriction
3451 3677
 		{
3452 3678
 			$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
3453 3679
 		}
3454
-		if ($socid) $sql.= " AND s.rowid = ".$socid;
3455
-		if ($draft) $sql.= " AND f.fk_statut = ".self::STATUS_DRAFT;
3456
-		if (is_object($excluser)) $sql.= " AND f.fk_user_author <> ".$excluser->id;
3680
+		}
3681
+		if ($socid) {
3682
+			$sql.= " AND s.rowid = ".$socid;
3683
+		}
3684
+		if ($draft) {
3685
+			$sql.= " AND f.fk_statut = ".self::STATUS_DRAFT;
3686
+		}
3687
+		if (is_object($excluser)) {
3688
+			$sql.= " AND f.fk_user_author <> ".$excluser->id;
3689
+		}
3457 3690
 		$sql.= $this->db->order($sortfield,$sortorder);
3458 3691
 		$sql.= $this->db->plimit($limit,$offset);
3459 3692
 
@@ -3471,12 +3704,10 @@  discard block
 block discarded – undo
3471 3704
 					if ($shortlist == 1)
3472 3705
 					{
3473 3706
 						$ga[$obj->fid] = $obj->ref;
3474
-					}
3475
-					else if ($shortlist == 2)
3707
+					} else if ($shortlist == 2)
3476 3708
 					{
3477 3709
 						$ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
3478
-					}
3479
-					else
3710
+					} else
3480 3711
 					{
3481 3712
 						$ga[$i]['id']	= $obj->fid;
3482 3713
 						$ga[$i]['ref'] 	= $obj->ref;
@@ -3486,8 +3717,7 @@  discard block
 block discarded – undo
3486 3717
 				}
3487 3718
 			}
3488 3719
 			return $ga;
3489
-		}
3490
-		else
3720
+		} else
3491 3721
 		{
3492 3722
 			dol_print_error($this->db);
3493 3723
 			return -1;
@@ -3518,7 +3748,9 @@  discard block
 block discarded – undo
3518 3748
 		$sql.= " AND f.paye = 0";					// Pas classee payee completement
3519 3749
 		$sql.= " AND pf.fk_paiement IS NULL";		// Aucun paiement deja fait
3520 3750
 		$sql.= " AND ff.fk_statut IS NULL";			// Renvoi vrai si pas facture de remplacement
3521
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
3751
+		if ($socid > 0) {
3752
+			$sql.=" AND f.fk_soc = ".$socid;
3753
+		}
3522 3754
 		$sql.= " ORDER BY f.facnumber";
3523 3755
 
3524 3756
 		dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
@@ -3533,8 +3765,7 @@  discard block
 block discarded – undo
3533 3765
 			}
3534 3766
 			//print_r($return);
3535 3767
 			return $return;
3536
-		}
3537
-		else
3768
+		} else
3538 3769
 		{
3539 3770
 			$this->error=$this->db->error();
3540 3771
 			return -1;
@@ -3567,7 +3798,9 @@  discard block
 block discarded – undo
3567 3798
 		//	$sql.= " OR f.close_code IS NOT NULL)";	// Classee payee partiellement
3568 3799
 		$sql.= " AND ff.type IS NULL";			// Renvoi vrai si pas facture de remplacement
3569 3800
 		$sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE;				// Type non 2 si facture non avoir
3570
-		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
3801
+		if ($socid > 0) {
3802
+			$sql.=" AND f.fk_soc = ".$socid;
3803
+		}
3571 3804
 		$sql.= " ORDER BY f.facnumber";
3572 3805
 
3573 3806
 		dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
@@ -3577,8 +3810,12 @@  discard block
 block discarded – undo
3577 3810
 			while ($obj=$this->db->fetch_object($resql))
3578 3811
 			{
3579 3812
 				$qualified=0;
3580
-				if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified=1;
3581
-				if ($obj->fk_statut == self::STATUS_CLOSED) $qualified=1;
3813
+				if ($obj->fk_statut == self::STATUS_VALIDATED) {
3814
+					$qualified=1;
3815
+				}
3816
+				if ($obj->fk_statut == self::STATUS_CLOSED) {
3817
+					$qualified=1;
3818
+				}
3582 3819
 				if ($qualified)
3583 3820
 				{
3584 3821
 					//$ref=$obj->facnumber;
@@ -3588,8 +3825,7 @@  discard block
 block discarded – undo
3588 3825
 			}
3589 3826
 
3590 3827
 			return $return;
3591
-		}
3592
-		else
3828
+		} else
3593 3829
 		{
3594 3830
 			$this->error=$this->db->error();
3595 3831
 			return -1;
@@ -3641,7 +3877,9 @@  discard block
 block discarded – undo
3641 3877
                     // For example print 239.2 - 229.3 - 9.9; does not return 0.
3642 3878
                     //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
3643 3879
                     //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3644
-					if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
3880
+					if (empty($amount)) {
3881
+						$amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
3882
+					}
3645 3883
 
3646 3884
 					if (is_numeric($amount) && $amount != 0)
3647 3885
 					{
@@ -3664,8 +3902,7 @@  discard block
 block discarded – undo
3664 3902
 						    dol_syslog(get_class($this).'::demandeprelevement Erreur');
3665 3903
 						    $error++;
3666 3904
 						}
3667
-					}
3668
-					else
3905
+					} else
3669 3906
 					{
3670 3907
 						$this->error='WithdrawRequestErrorNilAmount';
3671 3908
 	                    dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
@@ -3682,24 +3919,23 @@  discard block
 block discarded – undo
3682 3919
         				}
3683 3920
         			}
3684 3921
 
3685
-                    if ($error) return -1;
3922
+                    if ($error) {
3923
+                    	return -1;
3924
+                    }
3686 3925
                     return 1;
3687
-                }
3688
-                else
3926
+                } else
3689 3927
                 {
3690 3928
                     $this->error="A request already exists";
3691 3929
                     dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
3692 3930
                     return 0;
3693 3931
                 }
3694
-            }
3695
-            else
3932
+            } else
3696 3933
             {
3697 3934
                 $this->error=$this->db->error();
3698 3935
                 dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
3699 3936
                 return -2;
3700 3937
             }
3701
-        }
3702
-        else
3938
+        } else
3703 3939
         {
3704 3940
             $this->error="Status of invoice does not allow this";
3705 3941
             dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
@@ -3722,8 +3958,7 @@  discard block
 block discarded – undo
3722 3958
 		if ( $this->db->query($sql) )
3723 3959
 		{
3724 3960
 			return 0;
3725
-		}
3726
-		else
3961
+		} else
3727 3962
 		{
3728 3963
 			$this->error=$this->db->lasterror();
3729 3964
 			dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
@@ -3755,7 +3990,9 @@  discard block
 block discarded – undo
3755 3990
 		$sql.= $clause." f.paye=0";
3756 3991
 		$sql.= " AND f.entity = ".$conf->entity;
3757 3992
 		$sql.= " AND f.fk_statut = ".self::STATUS_VALIDATED;
3758
-		if ($user->societe_id) $sql.= " AND f.fk_soc = ".$user->societe_id;
3993
+		if ($user->societe_id) {
3994
+			$sql.= " AND f.fk_soc = ".$user->societe_id;
3995
+		}
3759 3996
 
3760 3997
 		$resql=$this->db->query($sql);
3761 3998
 		if ($resql)
@@ -3784,8 +4021,7 @@  discard block
 block discarded – undo
3784 4021
 			}
3785 4022
 
3786 4023
 			return $response;
3787
-		}
3788
-		else
4024
+		} else
3789 4025
 		{
3790 4026
 			dol_print_error($this->db);
3791 4027
 			$this->error=$this->db->error();
@@ -3889,9 +4125,11 @@  discard block
 block discarded – undo
3889 4125
 				$line->localtax1_tx=0;
3890 4126
 				$line->localtax2_tx=0;
3891 4127
 				$line->remise_percent=0;
3892
-				if ($xnbp == 1)        // Qty is negative (product line)
4128
+				if ($xnbp == 1) {
4129
+					// Qty is negative (product line)
3893 4130
 				{
3894 4131
 					$prodid = mt_rand(1, $num_prods);
4132
+				}
3895 4133
 					$line->fk_product=$prodids[$prodid];
3896 4134
 					$line->qty=-1;
3897 4135
 					$line->total_ht=-100;
@@ -3900,10 +4138,11 @@  discard block
 block discarded – undo
3900 4138
 					$line->multicurrency_total_ht=-200;
3901 4139
 					$line->multicurrency_total_ttc=-239.2;
3902 4140
 					$line->multicurrency_total_tva=-39.2;
3903
-				}
3904
-				else if ($xnbp == 2)    // UP is negative (free line)
4141
+				} else if ($xnbp == 2) {
4142
+					// UP is negative (free line)
3905 4143
 				{
3906 4144
 					$line->subprice=-100;
4145
+				}
3907 4146
 					$line->total_ht=-100;
3908 4147
 					$line->total_ttc=-119.6;
3909 4148
 					$line->total_tva=-19.6;
@@ -3911,10 +4150,11 @@  discard block
 block discarded – undo
3911 4150
 					$line->multicurrency_total_ht=-200;
3912 4151
 					$line->multicurrency_total_ttc=-239.2;
3913 4152
 					$line->multicurrency_total_tva=-39.2;
3914
-				}
3915
-				else if ($xnbp == 3)    // Discount is 50% (product line)
4153
+				} else if ($xnbp == 3) {
4154
+					// Discount is 50% (product line)
3916 4155
 				{
3917 4156
 					$prodid = mt_rand(1, $num_prods);
4157
+				}
3918 4158
 					$line->fk_product=$prodids[$prodid];
3919 4159
 					$line->total_ht=50;
3920 4160
 					$line->total_ttc=59.8;
@@ -3923,8 +4163,7 @@  discard block
 block discarded – undo
3923 4163
 					$line->multicurrency_total_ttc=119.6;
3924 4164
 					$line->multicurrency_total_tva=19.6;
3925 4165
 					$line->remise_percent=50;
3926
-				}
3927
-				else    // (product line)
4166
+				} else    // (product line)
3928 4167
 				{
3929 4168
 					$prodid = mt_rand(1, $num_prods);
3930 4169
 					$line->fk_product=$prodids[$prodid];
@@ -4008,8 +4247,7 @@  discard block
 block discarded – undo
4008 4247
 			}
4009 4248
             $this->db->free($resql);
4010 4249
 			return 1;
4011
-		}
4012
-		else
4250
+		} else
4013 4251
 		{
4014 4252
 			dol_print_error($this->db);
4015 4253
 			$this->error=$this->db->error();
@@ -4156,7 +4394,9 @@  discard block
 block discarded – undo
4156 4394
 		{
4157 4395
 			// Call trigger
4158 4396
 			$result=$this->call_trigger('BILL_MODIFY',$user);
4159
-			if ($result < 0) $error++;
4397
+			if ($result < 0) {
4398
+				$error++;
4399
+			}
4160 4400
 			// End call triggers
4161 4401
 		}
4162 4402
 
@@ -4164,8 +4404,7 @@  discard block
 block discarded – undo
4164 4404
 		{
4165 4405
 			$this->db->commit();
4166 4406
 			return 1;
4167
-		}
4168
-		else
4407
+		} else
4169 4408
 		{
4170 4409
 			foreach($this->errors as $errmsg)
4171 4410
 			{
@@ -4235,7 +4474,9 @@  discard block
 block discarded – undo
4235 4474
 		$now = dol_now();
4236 4475
 
4237 4476
 		// Paid invoices have status STATUS_CLOSED
4238
-		if ($this->statut != Facture::STATUS_VALIDATED) return false;
4477
+		if ($this->statut != Facture::STATUS_VALIDATED) {
4478
+			return false;
4479
+		}
4239 4480
 
4240 4481
 		return $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
4241 4482
 	}
@@ -4407,8 +4648,7 @@  discard block
 block discarded – undo
4407 4648
 			$this->db->free($result);
4408 4649
 
4409 4650
 			return 1;
4410
-		}
4411
-		else
4651
+		} else
4412 4652
 		{
4413 4653
 		    $this->error = $this->db->lasterror();
4414 4654
 			return -1;
@@ -4434,27 +4674,67 @@  discard block
 block discarded – undo
4434 4674
 
4435 4675
 		// Clean parameters
4436 4676
 		$this->desc=trim($this->desc);
4437
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4438
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4439
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4440
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4441
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4442
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4443
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4444
-		if (empty($this->rang)) $this->rang=0;
4445
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4446
-		if (empty($this->info_bits)) $this->info_bits=0;
4447
-		if (empty($this->subprice)) $this->subprice=0;
4448
-		if (empty($this->special_code)) $this->special_code=0;
4449
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4450
-		if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null';
4451
-		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4452
-
4453
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4454
-		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
4455
-		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
4456
-		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
4457
-		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
4677
+		if (empty($this->tva_tx)) {
4678
+			$this->tva_tx=0;
4679
+		}
4680
+		if (empty($this->localtax1_tx)) {
4681
+			$this->localtax1_tx=0;
4682
+		}
4683
+		if (empty($this->localtax2_tx)) {
4684
+			$this->localtax2_tx=0;
4685
+		}
4686
+		if (empty($this->localtax1_type)) {
4687
+			$this->localtax1_type=0;
4688
+		}
4689
+		if (empty($this->localtax2_type)) {
4690
+			$this->localtax2_type=0;
4691
+		}
4692
+		if (empty($this->total_localtax1)) {
4693
+			$this->total_localtax1=0;
4694
+		}
4695
+		if (empty($this->total_localtax2)) {
4696
+			$this->total_localtax2=0;
4697
+		}
4698
+		if (empty($this->rang)) {
4699
+			$this->rang=0;
4700
+		}
4701
+		if (empty($this->remise_percent)) {
4702
+			$this->remise_percent=0;
4703
+		}
4704
+		if (empty($this->info_bits)) {
4705
+			$this->info_bits=0;
4706
+		}
4707
+		if (empty($this->subprice)) {
4708
+			$this->subprice=0;
4709
+		}
4710
+		if (empty($this->special_code)) {
4711
+			$this->special_code=0;
4712
+		}
4713
+		if (empty($this->fk_parent_line)) {
4714
+			$this->fk_parent_line=0;
4715
+		}
4716
+		if (empty($this->fk_prev_id)) {
4717
+			$this->fk_prev_id = 'null';
4718
+		}
4719
+		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
4720
+			$this->situation_percent = 100;
4721
+		}
4722
+
4723
+		if (empty($this->pa_ht)) {
4724
+			$this->pa_ht=0;
4725
+		}
4726
+		if (empty($this->multicurrency_subprice)) {
4727
+			$this->multicurrency_subprice=0;
4728
+		}
4729
+		if (empty($this->multicurrency_total_ht)) {
4730
+			$this->multicurrency_total_ht=0;
4731
+		}
4732
+		if (empty($this->multicurrency_total_tva)) {
4733
+			$this->multicurrency_total_tva=0;
4734
+		}
4735
+		if (empty($this->multicurrency_total_ttc)) {
4736
+			$this->multicurrency_total_ttc=0;
4737
+		}
4458 4738
 
4459 4739
 		// if buy price not defined, define buyprice as configured in margin admin
4460 4740
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -4462,8 +4742,7 @@  discard block
 block discarded – undo
4462 4742
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4463 4743
 			{
4464 4744
 				return $result;
4465
-			}
4466
-			else
4745
+			} else
4467 4746
 			{
4468 4747
 				$this->pa_ht = $result;
4469 4748
 			}
@@ -4548,9 +4827,11 @@  discard block
 block discarded – undo
4548 4827
 		{
4549 4828
 			$this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
4550 4829
 
4551
-            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4830
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
4831
+            	// For avoid conflicts if trigger used
4552 4832
             {
4553 4833
             	$this->id=$this->rowid;
4834
+            }
4554 4835
             	$result=$this->insertExtraFields();
4555 4836
             	if ($result < 0)
4556 4837
             	{
@@ -4579,8 +4860,7 @@  discard block
 block discarded – undo
4579 4860
     							$this->db->rollback();
4580 4861
     							return -3;
4581 4862
 						    }
4582
-						}
4583
-						else
4863
+						} else
4584 4864
 						{
4585 4865
 							$result=$discount->link_to_invoice($this->rowid,0);
4586 4866
 							if ($result < 0)
@@ -4591,16 +4871,14 @@  discard block
 block discarded – undo
4591 4871
 								return -3;
4592 4872
 							}
4593 4873
 						}
4594
-					}
4595
-					else
4874
+					} else
4596 4875
 					{
4597 4876
 						$this->error=$langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
4598 4877
 						dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4599 4878
 						$this->db->rollback();
4600 4879
 						return -3;
4601 4880
 					}
4602
-				}
4603
-				else
4881
+				} else
4604 4882
 				{
4605 4883
 					$this->error=$discount->error;
4606 4884
 					dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
@@ -4624,8 +4902,7 @@  discard block
 block discarded – undo
4624 4902
 			$this->db->commit();
4625 4903
 			return $this->rowid;
4626 4904
 
4627
-		}
4628
-		else
4905
+		} else
4629 4906
 		{
4630 4907
 			$this->error=$this->db->error();
4631 4908
 			$this->db->rollback();
@@ -4650,28 +4927,66 @@  discard block
 block discarded – undo
4650 4927
 
4651 4928
 		// Clean parameters
4652 4929
 		$this->desc=trim($this->desc);
4653
-		if (empty($this->tva_tx)) $this->tva_tx=0;
4654
-		if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4655
-		if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4656
-		if (empty($this->localtax1_type)) $this->localtax1_type=0;
4657
-		if (empty($this->localtax2_type)) $this->localtax2_type=0;
4658
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4659
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
4660
-		if (empty($this->remise_percent)) $this->remise_percent=0;
4661
-		if (empty($this->info_bits)) $this->info_bits=0;
4662
-		if (empty($this->special_code)) $this->special_code=0;
4663
-		if (empty($this->product_type)) $this->product_type=0;
4664
-		if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4665
-		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4666
-		if (empty($this->pa_ht)) $this->pa_ht=0;
4667
-
4668
-		if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
4669
-		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
4670
-		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
4671
-		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
4930
+		if (empty($this->tva_tx)) {
4931
+			$this->tva_tx=0;
4932
+		}
4933
+		if (empty($this->localtax1_tx)) {
4934
+			$this->localtax1_tx=0;
4935
+		}
4936
+		if (empty($this->localtax2_tx)) {
4937
+			$this->localtax2_tx=0;
4938
+		}
4939
+		if (empty($this->localtax1_type)) {
4940
+			$this->localtax1_type=0;
4941
+		}
4942
+		if (empty($this->localtax2_type)) {
4943
+			$this->localtax2_type=0;
4944
+		}
4945
+		if (empty($this->total_localtax1)) {
4946
+			$this->total_localtax1=0;
4947
+		}
4948
+		if (empty($this->total_localtax2)) {
4949
+			$this->total_localtax2=0;
4950
+		}
4951
+		if (empty($this->remise_percent)) {
4952
+			$this->remise_percent=0;
4953
+		}
4954
+		if (empty($this->info_bits)) {
4955
+			$this->info_bits=0;
4956
+		}
4957
+		if (empty($this->special_code)) {
4958
+			$this->special_code=0;
4959
+		}
4960
+		if (empty($this->product_type)) {
4961
+			$this->product_type=0;
4962
+		}
4963
+		if (empty($this->fk_parent_line)) {
4964
+			$this->fk_parent_line=0;
4965
+		}
4966
+		if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
4967
+			$this->situation_percent = 100;
4968
+		}
4969
+		if (empty($this->pa_ht)) {
4970
+			$this->pa_ht=0;
4971
+		}
4972
+
4973
+		if (empty($this->multicurrency_subprice)) {
4974
+			$this->multicurrency_subprice=0;
4975
+		}
4976
+		if (empty($this->multicurrency_total_ht)) {
4977
+			$this->multicurrency_total_ht=0;
4978
+		}
4979
+		if (empty($this->multicurrency_total_tva)) {
4980
+			$this->multicurrency_total_tva=0;
4981
+		}
4982
+		if (empty($this->multicurrency_total_ttc)) {
4983
+			$this->multicurrency_total_ttc=0;
4984
+		}
4672 4985
 
4673 4986
 		// Check parameters
4674
-		if ($this->product_type < 0) return -1;
4987
+		if ($this->product_type < 0) {
4988
+			return -1;
4989
+		}
4675 4990
 
4676 4991
 		// if buy price not defined, define buyprice as configured in margin admin
4677 4992
 		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
@@ -4679,8 +4994,7 @@  discard block
 block discarded – undo
4679 4994
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4680 4995
 			{
4681 4996
 				return $result;
4682
-			}
4683
-			else
4997
+			} else
4684 4998
 			{
4685 4999
 				$this->pa_ht = $result;
4686 5000
 			}
@@ -4694,8 +5008,11 @@  discard block
 block discarded – undo
4694 5008
         $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4695 5009
         $sql.= ", subprice=".price2num($this->subprice)."";
4696 5010
         $sql.= ", remise_percent=".price2num($this->remise_percent)."";
4697
-        if ($this->fk_remise_except) $sql.= ", fk_remise_except=".$this->fk_remise_except;
4698
-        else $sql.= ", fk_remise_except=null";
5011
+        if ($this->fk_remise_except) {
5012
+        	$sql.= ", fk_remise_except=".$this->fk_remise_except;
5013
+        } else {
5014
+        	$sql.= ", fk_remise_except=null";
5015
+        }
4699 5016
 		$sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->db->escape($this->vat_src_code))."'";
4700 5017
         $sql.= ", tva_tx=".price2num($this->tva_tx)."";
4701 5018
         $sql.= ", localtax1_tx=".price2num($this->localtax1_tx)."";
@@ -4719,7 +5036,9 @@  discard block
 block discarded – undo
4719 5036
 		$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
4720 5037
 		$sql.= ", buy_price_ht='".price2num($this->pa_ht)."'";
4721 5038
 		$sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
4722
-		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
5039
+		if (! empty($this->rang)) {
5040
+			$sql.= ", rang=".$this->rang;
5041
+		}
4723 5042
 		$sql.= ", situation_percent=" . $this->situation_percent;
4724 5043
 		$sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4725 5044
 		$sql.= ", fk_user_modif =".$user->id;
@@ -4736,9 +5055,11 @@  discard block
 block discarded – undo
4736 5055
 		$resql=$this->db->query($sql);
4737 5056
 		if ($resql)
4738 5057
 		{
4739
-        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
5058
+        	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
5059
+        		// For avoid conflicts if trigger used
4740 5060
         	{
4741 5061
         		$this->id=$this->rowid;
5062
+        	}
4742 5063
         		$result=$this->insertExtraFields();
4743 5064
         		if ($result < 0)
4744 5065
         		{
@@ -4759,8 +5080,7 @@  discard block
 block discarded – undo
4759 5080
 			}
4760 5081
 			$this->db->commit();
4761 5082
 			return 1;
4762
-		}
4763
-		else
5083
+		} else
4764 5084
 		{
4765 5085
 			$this->error=$this->db->error();
4766 5086
 			$this->db->rollback();
@@ -4796,8 +5116,7 @@  discard block
 block discarded – undo
4796 5116
 		{
4797 5117
 			$this->db->commit();
4798 5118
 			return 1;
4799
-		}
4800
-		else
5119
+		} else
4801 5120
 		{
4802 5121
 			$this->error=$this->db->error()." sql=".$sql;
4803 5122
 			$this->db->rollback();
@@ -4816,8 +5135,12 @@  discard block
 block discarded – undo
4816 5135
 		dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
4817 5136
 
4818 5137
 		// Clean parameters
4819
-		if (empty($this->total_localtax1)) $this->total_localtax1=0;
4820
-		if (empty($this->total_localtax2)) $this->total_localtax2=0;
5138
+		if (empty($this->total_localtax1)) {
5139
+			$this->total_localtax1=0;
5140
+		}
5141
+		if (empty($this->total_localtax2)) {
5142
+			$this->total_localtax2=0;
5143
+		}
4821 5144
 
4822 5145
 		// Mise a jour ligne en base
4823 5146
 		$sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
@@ -4835,8 +5158,7 @@  discard block
 block discarded – undo
4835 5158
 		{
4836 5159
 			$this->db->commit();
4837 5160
 			return 1;
4838
-		}
4839
-		else
5161
+		} else
4840 5162
 		{
4841 5163
 			$this->error=$this->db->error();
4842 5164
 			$this->db->rollback();
@@ -4859,7 +5181,9 @@  discard block
 block discarded – undo
4859 5181
 		    // If invoice is a not a situation invoice, this->fk_prev_id is used for something else
4860 5182
             $tmpinvoice=new Facture($this->db);
4861 5183
             $tmpinvoice->fetch($invoiceid);
4862
-            if ($tmpinvoice->type != Facture::TYPE_SITUATION) return 0;
5184
+            if ($tmpinvoice->type != Facture::TYPE_SITUATION) {
5185
+            	return 0;
5186
+            }
4863 5187
 
4864 5188
 			$sql = 'SELECT situation_percent FROM ' . MAIN_DB_PREFIX . 'facturedet WHERE rowid=' . $this->fk_prev_id;
4865 5189
 			$resql = $this->db->query($sql);
Please login to merge, or discard this patch.
htdocs/accountancy/class/bookkeeping.class.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1511,9 +1511,9 @@
 block discarded – undo
1511 1511
 	/**
1512 1512
 	 * Transform transaction
1513 1513
 	 *
1514
-	 * @param  number   $direction     If 0 tmp => real, if 1 real => tmp
1514
+	 * @param  integer   $direction     If 0 tmp => real, if 1 real => tmp
1515 1515
 	 * @param  string   $piece_num     Piece num
1516
-	 * @return void
1516
+	 * @return integer
1517 1517
 	 */
1518 1518
 	public function transformTransaction($direction=0,$piece_num='') {
1519 1519
 		$this->db->begin();
Please login to merge, or discard this patch.
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 
436 436
 		$now = dol_now();
437 437
 		if (empty($this->date_create)) {
438
-		    $this->date_create = $now;
438
+			$this->date_create = $now;
439 439
 		}
440 440
 
441 441
 		// Check parameters
@@ -1596,17 +1596,17 @@  discard block
 block discarded – undo
1596 1596
 	}
1597 1597
 
1598 1598
 	/**
1599
-	* Return list of accounts with label by chart of accounts
1600
-	*
1601
-	* @param string		$selectid	Preselected chart of accounts
1602
-	* @param string		$htmlname	Name of field in html form
1603
-	* @param int		$showempty	Add an empty field
1604
-	* @param array		$event		Event options
1605
-	* @param int		$select_in	Value is a aa.rowid (0 default) or aa.account_number (1)
1606
-	* @param int		$select_out	Set value returned by select 0=rowid (default), 1=account_number
1607
-	* @param int		$aabase		Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number
1608
-	* @return string	String with HTML select
1609
-	*/
1599
+	 * Return list of accounts with label by chart of accounts
1600
+	 *
1601
+	 * @param string		$selectid	Preselected chart of accounts
1602
+	 * @param string		$htmlname	Name of field in html form
1603
+	 * @param int		$showempty	Add an empty field
1604
+	 * @param array		$event		Event options
1605
+	 * @param int		$select_in	Value is a aa.rowid (0 default) or aa.account_number (1)
1606
+	 * @param int		$select_out	Set value returned by select 0=rowid (default), 1=account_number
1607
+	 * @param int		$aabase		Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number
1608
+	 * @return string	String with HTML select
1609
+	 */
1610 1610
 	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') {
1611 1611
 		global $conf;
1612 1612
 
Please login to merge, or discard this patch.
Braces   +27 added lines, -11 removed lines patch added patch discarded remove patch
@@ -172,8 +172,12 @@  discard block
 block discarded – undo
172 172
 		if (isset($this->piece_num)) {
173 173
 			$this->piece_num = trim($this->piece_num);
174 174
 		}
175
-		if (empty($this->debit)) $this->debit = 0;
176
-		if (empty($this->credit)) $this->credit = 0;
175
+		if (empty($this->debit)) {
176
+			$this->debit = 0;
177
+		}
178
+		if (empty($this->credit)) {
179
+			$this->credit = 0;
180
+		}
177 181
 
178 182
 		// Check parameters
179 183
 		if (empty($this->numero_compte) || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined')
@@ -182,8 +186,7 @@  discard block
 block discarded – undo
182 186
 			if (in_array($this->doc_type, array('bank', 'expense_report')))
183 187
 			{
184 188
 				$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet,  $this->doc_type);
185
-			}
186
-			else
189
+			} else
187 190
 			{
188 191
 				//$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->doc_ref,  $this->label_compte);
189 192
 				$mesg=$this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte;
@@ -427,8 +430,12 @@  discard block
 block discarded – undo
427 430
 		if (isset($this->piece_num)) {
428 431
 			$this->piece_num = trim($this->piece_num);
429 432
 		}
430
-		if (empty($this->debit)) $this->debit = 0;
431
-		if (empty($this->credit)) $this->credit = 0;
433
+		if (empty($this->debit)) {
434
+			$this->debit = 0;
435
+		}
436
+		if (empty($this->credit)) {
437
+			$this->credit = 0;
438
+		}
432 439
 
433 440
 		$this->debit = price2num($this->debit, 'MT');
434 441
 		$this->credit = price2num($this->credit, 'MT');
@@ -1195,8 +1202,13 @@  discard block
 block discarded – undo
1195 1202
 		$sql = "DELETE";
1196 1203
 		$sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode;
1197 1204
 		$sql.= " WHERE 1 = 1";
1198
-		if (! empty($delyear)) $sql.= " AND YEAR(doc_date) = " . $delyear;		 // FIXME Must use between
1199
-		if (! empty($journal)) $sql.= " AND code_journal = '".$journal."'";
1205
+		if (! empty($delyear)) {
1206
+			$sql.= " AND YEAR(doc_date) = " . $delyear;
1207
+		}
1208
+		// FIXME Must use between
1209
+		if (! empty($journal)) {
1210
+			$sql.= " AND code_journal = '".$journal."'";
1211
+		}
1200 1212
 		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
1201 1213
 		$resql = $this->db->query($sql);
1202 1214
 
@@ -1381,8 +1393,12 @@  discard block
 block discarded – undo
1381 1393
 
1382 1394
 		if ($result) {
1383 1395
 			$obj = $this->db->fetch_object($result);
1384
-			if ($obj) $result = $obj->max;
1385
-			if (empty($result)) $result = 1;
1396
+			if ($obj) {
1397
+				$result = $obj->max;
1398
+			}
1399
+			if (empty($result)) {
1400
+				$result = 1;
1401
+			}
1386 1402
 			return $result;
1387 1403
 		} else {
1388 1404
 			$this->error = "Error " . $this->db->lasterror();
@@ -1733,7 +1749,7 @@  discard block
 block discarded – undo
1733 1749
 			}
1734 1750
 			if(empty($obj->category)){
1735 1751
 				return $obj->label;
1736
-			}else{
1752
+			} else{
1737 1753
 				return $obj->label.' ('.$obj->category.')';
1738 1754
 			}
1739 1755
 		} else {
Please login to merge, or discard this patch.
Spacing   +341 added lines, -341 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  */
25 25
 
26 26
 // Class
27
-require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
27
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28 28
 
29 29
 /**
30 30
  * Class to manage Ledger (General Ledger and Subledger)
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 	 *
44 44
 	 * @var string[] Error codes (or messages)
45 45
 	 */
46
-	public $errors = array ();
46
+	public $errors = array();
47 47
 	/**
48 48
 	 *
49 49
 	 * @var string Id to identify managed objects
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 	 *
62 62
 	 * @var BookKeepingLine[] Lines
63 63
 	 */
64
-	public $lines = array ();
64
+	public $lines = array();
65 65
 
66 66
 	/**
67 67
 	 *
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 			$langs->load("errors");
183 183
 			if (in_array($this->doc_type, array('bank', 'expense_report')))
184 184
 			{
185
-				$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet,  $this->doc_type);
185
+				$this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type);
186 186
 			}
187 187
 			else
188 188
 			{
189 189
 				//$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->doc_ref,  $this->label_compte);
190
-				$mesg=$this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte;
190
+				$mesg = $this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte;
191 191
 				if ($this->subledger_account && $this->subledger_account != $this->numero_compte)
192 192
 				{
193
-					$mesg.=', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account;
193
+					$mesg .= ', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account;
194 194
 				}
195
-				$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg);
195
+				$this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg);
196 196
 			}
197 197
 
198 198
 			return -1;
@@ -204,12 +204,12 @@  discard block
 block discarded – undo
204 204
 
205 205
 		// First check if line not yet already in bookkeeping
206 206
 		$sql = "SELECT count(*) as nb";
207
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
208
-		$sql .= " WHERE doc_type = '" . $this->db->escape($this->doc_type) . "'";
209
-		$sql .= " AND fk_doc = " . $this->fk_doc;
210
-		$sql .= " AND fk_docdet = " . $this->fk_docdet;					// This field can be 0 is record is for several lines
211
-		$sql .= " AND numero_compte = '" . $this->db->escape($this->numero_compte) . "'";
212
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
207
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
208
+		$sql .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'";
209
+		$sql .= " AND fk_doc = ".$this->fk_doc;
210
+		$sql .= " AND fk_docdet = ".$this->fk_docdet; // This field can be 0 is record is for several lines
211
+		$sql .= " AND numero_compte = '".$this->db->escape($this->numero_compte)."'";
212
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
213 213
 
214 214
 		$resql = $this->db->query($sql);
215 215
 
@@ -219,32 +219,32 @@  discard block
 block discarded – undo
219 219
 			{
220 220
 				// Determine piece_num
221 221
 				$sqlnum = "SELECT piece_num";
222
-				$sqlnum .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
223
-				$sqlnum .= " WHERE doc_type = '" . $this->db->escape($this->doc_type) . "'";		// For example doc_type = 'bank'
224
-				$sqlnum .= " AND fk_docdet = " . $this->db->escape($this->fk_docdet);				// fk_docdet is rowid into llx_bank or llx_facturedet or llx_facturefourndet, or ...
225
-				$sqlnum .= " AND doc_ref = '" . $this->db->escape($this->doc_ref) . "'";			// ref of source object
226
-				$sqlnum .= " AND entity IN (" . getEntity('accountancy') . ")";
222
+				$sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
223
+				$sqlnum .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'"; // For example doc_type = 'bank'
224
+				$sqlnum .= " AND fk_docdet = ".$this->db->escape($this->fk_docdet); // fk_docdet is rowid into llx_bank or llx_facturedet or llx_facturefourndet, or ...
225
+				$sqlnum .= " AND doc_ref = '".$this->db->escape($this->doc_ref)."'"; // ref of source object
226
+				$sqlnum .= " AND entity IN (".getEntity('accountancy').")";
227 227
 
228
-				dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG);
228
+				dol_syslog(get_class($this).":: create sqlnum=".$sqlnum, LOG_DEBUG);
229 229
 				$resqlnum = $this->db->query($sqlnum);
230 230
 				if ($resqlnum) {
231 231
 					$objnum = $this->db->fetch_object($resqlnum);
232 232
 					$this->piece_num = $objnum->piece_num;
233 233
 				}
234
-				dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG);
234
+				dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG);
235 235
 				if (empty($this->piece_num)) {
236 236
 					$sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum";
237
-					$sqlnum .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
238
-					$sqlnum .= " WHERE entity IN (" . getEntity('accountancy') . ")";
237
+					$sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
238
+					$sqlnum .= " WHERE entity IN (".getEntity('accountancy').")";
239 239
 
240
-					dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG);
240
+					dol_syslog(get_class($this).":: create sqlnum=".$sqlnum, LOG_DEBUG);
241 241
 					$resqlnum = $this->db->query($sqlnum);
242 242
 					if ($resqlnum) {
243 243
 						$objnum = $this->db->fetch_object($resqlnum);
244 244
 						$this->piece_num = $objnum->maxpiecenum;
245 245
 					}
246 246
 				}
247
-				dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG);
247
+				dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG);
248 248
 				if (empty($this->piece_num)) {
249 249
 					$this->piece_num = 1;
250 250
 				}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 					$this->date_create = $now;
255 255
 				}
256 256
 
257
-				$sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " (";
257
+				$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
258 258
 				$sql .= "doc_date";
259 259
 				$sql .= ", date_lim_reglement";
260 260
 				$sql .= ", doc_type";
@@ -278,66 +278,66 @@  discard block
 block discarded – undo
278 278
 				$sql .= ", piece_num";
279 279
 				$sql .= ', entity';
280 280
 				$sql .= ") VALUES (";
281
-				$sql .= "'" . $this->db->idate($this->doc_date) . "'";
282
-				$sql .= ",'" . $this->db->idate($this->date_lim_reglement) . "'";
283
-				$sql .= ",'" . $this->db->escape($this->doc_type) . "'";
284
-				$sql .= ",'" . $this->db->escape($this->doc_ref) . "'";
285
-				$sql .= "," . $this->fk_doc;
286
-				$sql .= "," . $this->fk_docdet;
287
-				$sql .= ",'" . $this->db->escape($this->thirdparty_code) . "'";
288
-				$sql .= ",'" . $this->db->escape($this->subledger_account) . "'";
289
-				$sql .= ",'" . $this->db->escape($this->subledger_label) . "'";
290
-				$sql .= ",'" . $this->db->escape($this->numero_compte) . "'";
291
-				$sql .= ",'" . $this->db->escape($this->label_compte) . "'";
292
-				$sql .= ",'" . $this->db->escape($this->label_operation) . "'";
293
-				$sql .= "," . $this->debit;
294
-				$sql .= "," . $this->credit;
295
-				$sql .= "," . $this->montant;
296
-				$sql .= ",'" . $this->db->escape($this->sens) . "'";
297
-				$sql .= ",'" . $this->db->escape($this->fk_user_author) . "'";
298
-				$sql .= ",'" . $this->db->idate($this->date_create). "'";
299
-				$sql .= ",'" . $this->db->escape($this->code_journal) . "'";
300
-				$sql .= ",'" . $this->db->escape($this->journal_label) . "'";
301
-				$sql .= "," . $this->db->escape($this->piece_num);
302
-				$sql .= ", " . (! isset($this->entity) ? '1' : $this->entity);
281
+				$sql .= "'".$this->db->idate($this->doc_date)."'";
282
+				$sql .= ",'".$this->db->idate($this->date_lim_reglement)."'";
283
+				$sql .= ",'".$this->db->escape($this->doc_type)."'";
284
+				$sql .= ",'".$this->db->escape($this->doc_ref)."'";
285
+				$sql .= ",".$this->fk_doc;
286
+				$sql .= ",".$this->fk_docdet;
287
+				$sql .= ",'".$this->db->escape($this->thirdparty_code)."'";
288
+				$sql .= ",'".$this->db->escape($this->subledger_account)."'";
289
+				$sql .= ",'".$this->db->escape($this->subledger_label)."'";
290
+				$sql .= ",'".$this->db->escape($this->numero_compte)."'";
291
+				$sql .= ",'".$this->db->escape($this->label_compte)."'";
292
+				$sql .= ",'".$this->db->escape($this->label_operation)."'";
293
+				$sql .= ",".$this->debit;
294
+				$sql .= ",".$this->credit;
295
+				$sql .= ",".$this->montant;
296
+				$sql .= ",'".$this->db->escape($this->sens)."'";
297
+				$sql .= ",'".$this->db->escape($this->fk_user_author)."'";
298
+				$sql .= ",'".$this->db->idate($this->date_create)."'";
299
+				$sql .= ",'".$this->db->escape($this->code_journal)."'";
300
+				$sql .= ",'".$this->db->escape($this->journal_label)."'";
301
+				$sql .= ",".$this->db->escape($this->piece_num);
302
+				$sql .= ", ".(!isset($this->entity) ? '1' : $this->entity);
303 303
 				$sql .= ")";
304 304
 
305
-				dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG);
305
+				dol_syslog(get_class($this).":: create sql=".$sql, LOG_DEBUG);
306 306
 				$resql = $this->db->query($sql);
307 307
 				if ($resql) {
308
-					$id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
308
+					$id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
309 309
 
310 310
 					if ($id > 0) {
311 311
 						$this->id = $id;
312 312
 						$result = 0;
313 313
 					} else {
314 314
 						$result = -2;
315
-						$error ++;
316
-						$this->errors[] = 'Error Create Error ' . $result . ' lecture ID';
317
-						dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
315
+						$error++;
316
+						$this->errors[] = 'Error Create Error '.$result.' lecture ID';
317
+						dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
318 318
 					}
319 319
 				} else {
320 320
 					$result = -1;
321
-					$error ++;
322
-					$this->errors[] = 'Error ' . $this->db->lasterror();
323
-					dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
321
+					$error++;
322
+					$this->errors[] = 'Error '.$this->db->lasterror();
323
+					dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
324 324
 				}
325 325
 			} else {	// Already exists
326 326
 				$result = -3;
327 327
 				$error++;
328
-				$this->error='BookkeepingRecordAlreadyExists';
329
-				dol_syslog(__METHOD__ . ' ' . $this->error, LOG_WARNING);
328
+				$this->error = 'BookkeepingRecordAlreadyExists';
329
+				dol_syslog(__METHOD__.' '.$this->error, LOG_WARNING);
330 330
 			}
331 331
 		} else {
332 332
 			$result = -5;
333
-			$error ++;
334
-			$this->errors[] = 'Error ' . $this->db->lasterror();
335
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
333
+			$error++;
334
+			$this->errors[] = 'Error '.$this->db->lasterror();
335
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
336 336
 		}
337 337
 
338
-		if (! $error) {
338
+		if (!$error) {
339 339
 
340
-			if (! $notrigger) {
340
+			if (!$notrigger) {
341 341
 				// Uncomment this and change MYOBJECT to your own tag if you
342 342
 				// want this action to call a trigger.
343 343
 
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 	 * @param  string  $mode 	   Mode
367 367
 	 * @return int				 <0 if KO, Id of created object if OK
368 368
 	 */
369
-	public function createStd(User $user, $notrigger = false, $mode='') {
369
+	public function createStd(User $user, $notrigger = false, $mode = '') {
370 370
 		dol_syslog(__METHOD__, LOG_DEBUG);
371 371
 
372 372
 		$error = 0;
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 		// Put here code to add control on parameters values
446 446
 
447 447
 		// Insert request
448
-		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . $mode.'(';
448
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.'(';
449 449
 		$sql .= 'doc_date,';
450 450
 		$sql .= 'date_lim_reglement,';
451 451
 		$sql .= 'doc_type,';
@@ -469,43 +469,43 @@  discard block
 block discarded – undo
469 469
 		$sql .= 'piece_num,';
470 470
 		$sql .= 'entity';
471 471
 		$sql .= ') VALUES (';
472
-		$sql .= ' ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'" . $this->db->idate($this->doc_date) . "'") . ',';
473
-		$sql .= ' ' . (! isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_lim_reglement) . "'") . ',';
474
-		$sql .= ' ' . (! isset($this->doc_type) ? 'NULL' : "'" . $this->db->escape($this->doc_type) . "'") . ',';
475
-		$sql .= ' ' . (! isset($this->doc_ref) ? 'NULL' : "'" . $this->db->escape($this->doc_ref) . "'") . ',';
476
-		$sql .= ' ' . (empty($this->fk_doc) ? '0' : $this->fk_doc) . ',';
477
-		$sql .= ' ' . (empty($this->fk_docdet) ? '0' : $this->fk_docdet) . ',';
478
-		$sql .= ' ' . (! isset($this->thirdparty_code) ? 'NULL' : "'" . $this->db->escape($this->thirdparty_code) . "'") . ',';
479
-		$sql .= ' ' . (! isset($this->subledger_account) ? 'NULL' : "'" . $this->db->escape($this->subledger_account) . "'") . ',';
480
-		$sql .= ' ' . (! isset($this->subledger_label) ? 'NULL' : "'" . $this->db->escape($this->subledger_label) . "'") . ',';
481
-		$sql .= ' ' . (! isset($this->numero_compte) ? 'NULL' : "'" . $this->db->escape($this->numero_compte) . "'") . ',';
482
-		$sql .= ' ' . (! isset($this->label_compte) ? 'NULL' : "'" . $this->db->escape($this->label_compte) . "'") . ',';
483
-		$sql .= ' ' . (! isset($this->label_operation) ? 'NULL' : "'" . $this->db->escape($this->label_operation) . "'") . ',';
484
-		$sql .= ' ' . (! isset($this->debit) ? 'NULL' : $this->debit ). ',';
485
-		$sql .= ' ' . (! isset($this->credit) ? 'NULL' : $this->credit ). ',';
486
-		$sql .= ' ' . (! isset($this->montant) ? 'NULL' : $this->montant ). ',';
487
-		$sql .= ' ' . (! isset($this->sens) ? 'NULL' : "'" . $this->db->escape($this->sens) . "'") . ',';
488
-		$sql .= ' ' . $user->id . ',';
489
-		$sql .= ' ' . "'" . $this->db->idate($this->date_create) . "',";
490
-		$sql .= ' ' . (empty($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ',';
491
-		$sql .= ' ' . (empty($this->journal_label) ? 'NULL' : "'" . $this->db->escape($this->journal_label) . "'") . ',';
492
-		$sql .= ' ' . (empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).',';
493
-		$sql .= ' ' . (! isset($this->entity) ? '1' : $this->entity);
472
+		$sql .= ' '.(!isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'".$this->db->idate($this->doc_date)."'").',';
473
+		$sql .= ' '.(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'").',';
474
+		$sql .= ' '.(!isset($this->doc_type) ? 'NULL' : "'".$this->db->escape($this->doc_type)."'").',';
475
+		$sql .= ' '.(!isset($this->doc_ref) ? 'NULL' : "'".$this->db->escape($this->doc_ref)."'").',';
476
+		$sql .= ' '.(empty($this->fk_doc) ? '0' : $this->fk_doc).',';
477
+		$sql .= ' '.(empty($this->fk_docdet) ? '0' : $this->fk_docdet).',';
478
+		$sql .= ' '.(!isset($this->thirdparty_code) ? 'NULL' : "'".$this->db->escape($this->thirdparty_code)."'").',';
479
+		$sql .= ' '.(!isset($this->subledger_account) ? 'NULL' : "'".$this->db->escape($this->subledger_account)."'").',';
480
+		$sql .= ' '.(!isset($this->subledger_label) ? 'NULL' : "'".$this->db->escape($this->subledger_label)."'").',';
481
+		$sql .= ' '.(!isset($this->numero_compte) ? 'NULL' : "'".$this->db->escape($this->numero_compte)."'").',';
482
+		$sql .= ' '.(!isset($this->label_compte) ? 'NULL' : "'".$this->db->escape($this->label_compte)."'").',';
483
+		$sql .= ' '.(!isset($this->label_operation) ? 'NULL' : "'".$this->db->escape($this->label_operation)."'").',';
484
+		$sql .= ' '.(!isset($this->debit) ? 'NULL' : $this->debit).',';
485
+		$sql .= ' '.(!isset($this->credit) ? 'NULL' : $this->credit).',';
486
+		$sql .= ' '.(!isset($this->montant) ? 'NULL' : $this->montant).',';
487
+		$sql .= ' '.(!isset($this->sens) ? 'NULL' : "'".$this->db->escape($this->sens)."'").',';
488
+		$sql .= ' '.$user->id.',';
489
+		$sql .= ' '."'".$this->db->idate($this->date_create)."',";
490
+		$sql .= ' '.(empty($this->code_journal) ? 'NULL' : "'".$this->db->escape($this->code_journal)."'").',';
491
+		$sql .= ' '.(empty($this->journal_label) ? 'NULL' : "'".$this->db->escape($this->journal_label)."'").',';
492
+		$sql .= ' '.(empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).',';
493
+		$sql .= ' '.(!isset($this->entity) ? '1' : $this->entity);
494 494
 		$sql .= ')';
495 495
 
496 496
 		$this->db->begin();
497 497
 
498 498
 		$resql = $this->db->query($sql);
499
-		if (! $resql) {
500
-			$error ++;
501
-			$this->errors[] = 'Error ' . $this->db->lasterror();
502
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
499
+		if (!$resql) {
500
+			$error++;
501
+			$this->errors[] = 'Error '.$this->db->lasterror();
502
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
503 503
 		}
504 504
 
505
-		if (! $error) {
506
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
505
+		if (!$error) {
506
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
507 507
 
508
-			if (! $notrigger) {
508
+			if (!$notrigger) {
509 509
 				// Uncomment this and change MYOBJECT to your own tag if you
510 510
 				// want this action to call a trigger.
511 511
 
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
 		if ($error) {
521 521
 			$this->db->rollback();
522 522
 
523
-			return - 1 * $error;
523
+			return -1 * $error;
524 524
 		} else {
525 525
 			$this->db->commit();
526 526
 
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
 	 *
538 538
 	 * @return int <0 if KO, 0 if not found, >0 if OK
539 539
 	 */
540
-	public function fetch($id, $ref = null, $mode='') {
540
+	public function fetch($id, $ref = null, $mode = '') {
541 541
 		global $conf;
542 542
 
543 543
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -565,13 +565,13 @@  discard block
 block discarded – undo
565 565
 		$sql .= " t.code_journal,";
566 566
 		$sql .= " t.journal_label,";
567 567
 		$sql .= " t.piece_num";
568
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element.$mode. ' as t';
568
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.$mode.' as t';
569 569
 		$sql .= ' WHERE 1 = 1';
570
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
570
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
571 571
 		if (null !== $ref) {
572
-			$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
572
+			$sql .= ' AND t.ref = '.'\''.$ref.'\'';
573 573
 		} else {
574
-			$sql .= ' AND t.rowid = ' . $id;
574
+			$sql .= ' AND t.rowid = '.$id;
575 575
 		}
576 576
 
577 577
 		$resql = $this->db->query($sql);
@@ -612,10 +612,10 @@  discard block
 block discarded – undo
612 612
 				return 0;
613 613
 			}
614 614
 		} else {
615
-			$this->errors[] = 'Error ' . $this->db->lasterror();
616
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
615
+			$this->errors[] = 'Error '.$this->db->lasterror();
616
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
617 617
 
618
-			return - 1;
618
+			return -1;
619 619
 		}
620 620
 	}
621 621
 
@@ -660,47 +660,47 @@  discard block
 block discarded – undo
660 660
 		$sql .= " t.journal_label,";
661 661
 		$sql .= " t.piece_num";
662 662
 		// Manage filter
663
-		$sqlwhere = array ();
663
+		$sqlwhere = array();
664 664
 		if (count($filter) > 0) {
665
-			foreach ( $filter as $key => $value ) {
665
+			foreach ($filter as $key => $value) {
666 666
 				if ($key == 't.doc_date') {
667
-					$sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\'';
667
+					$sqlwhere[] = $key.'=\''.$this->db->idate($value).'\'';
668 668
 				} elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') {
669
-					$sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\'';
669
+					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
670 670
 				} elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
671
-					$sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\'';
671
+					$sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
672 672
 				} elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
673
-					$sqlwhere[] = $key . '=' . $value;
673
+					$sqlwhere[] = $key.'='.$value;
674 674
 				} elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
675
-					$sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\'';
675
+					$sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
676 676
 				} elseif ($key == 't.label_operation') {
677
-					$sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\'';
677
+					$sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
678 678
 				} else {
679
-					$sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
679
+					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
680 680
 				}
681 681
 			}
682 682
 		}
683
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
683
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
684 684
 		$sql .= ' WHERE 1 = 1';
685
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
685
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
686 686
 		if (count($sqlwhere) > 0) {
687
-			$sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere);
687
+			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
688 688
 		}
689 689
 		// Affichage par compte comptable
690 690
 		$sql .= ' ORDER BY t.numero_compte ASC';
691
-		if (! empty($sortfield)) {
692
-			$sql .= ', ' . $sortfield . ' ' .$sortorder;
691
+		if (!empty($sortfield)) {
692
+			$sql .= ', '.$sortfield.' '.$sortorder;
693 693
 		}
694
-		if (! empty($limit)) {
695
-			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
694
+		if (!empty($limit)) {
695
+			$sql .= ' '.$this->db->plimit($limit + 1, $offset);
696 696
 		}
697
-		$this->lines = array ();
697
+		$this->lines = array();
698 698
 
699 699
 		$resql = $this->db->query($sql);
700 700
 		if ($resql) {
701 701
 			$num = $this->db->num_rows($resql);
702 702
 
703
-			while ( $obj = $this->db->fetch_object($resql) ) {
703
+			while ($obj = $this->db->fetch_object($resql)) {
704 704
 				$line = new BookKeepingLine();
705 705
 
706 706
 				$line->id = $obj->rowid;
@@ -732,10 +732,10 @@  discard block
 block discarded – undo
732 732
 
733 733
 			return $num;
734 734
 		} else {
735
-			$this->errors[] = 'Error ' . $this->db->lasterror();
736
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
735
+			$this->errors[] = 'Error '.$this->db->lasterror();
736
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
737 737
 
738
-			return - 1;
738
+			return -1;
739 739
 		}
740 740
 	}
741 741
 
@@ -778,37 +778,37 @@  discard block
 block discarded – undo
778 778
 		$sql .= " t.code_journal,";
779 779
 		$sql .= " t.journal_label,";
780 780
 		$sql .= " t.piece_num";
781
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
781
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
782 782
 		// Manage filter
783
-		$sqlwhere = array ();
783
+		$sqlwhere = array();
784 784
 		if (count($filter) > 0) {
785
-			foreach ( $filter as $key => $value ) {
785
+			foreach ($filter as $key => $value) {
786 786
 				if ($key == 't.doc_date') {
787
-					$sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\'';
787
+					$sqlwhere[] = $key.'=\''.$this->db->idate($value).'\'';
788 788
 				} elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') {
789
-					$sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\'';
789
+					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
790 790
 				} elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
791
-					$sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\'';
791
+					$sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
792 792
 				} elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
793
-					$sqlwhere[] = $key . '=' . $value;
793
+					$sqlwhere[] = $key.'='.$value;
794 794
 				} elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
795
-					$sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\'';
795
+					$sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
796 796
 				} else {
797
-					$sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
797
+					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
798 798
 				}
799 799
 			}
800 800
 		}
801
-		$sql.= ' WHERE 1 = 1';
802
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
801
+		$sql .= ' WHERE 1 = 1';
802
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
803 803
 		if (count($sqlwhere) > 0) {
804
-			$sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere);
804
+			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
805 805
 		}
806 806
 
807
-		if (! empty($sortfield)) {
807
+		if (!empty($sortfield)) {
808 808
 			$sql .= $this->db->order($sortfield, $sortorder);
809 809
 		}
810
-		if (! empty($limit)) {
811
-			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
810
+		if (!empty($limit)) {
811
+			$sql .= ' '.$this->db->plimit($limit + 1, $offset);
812 812
 		}
813 813
 		$this->lines = array();
814 814
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
 		if ($resql) {
817 817
 			$num = $this->db->num_rows($resql);
818 818
 
819
-			while ( $obj = $this->db->fetch_object($resql) ) {
819
+			while ($obj = $this->db->fetch_object($resql)) {
820 820
 				$line = new BookKeepingLine();
821 821
 
822 822
 				$line->id = $obj->rowid;
@@ -848,10 +848,10 @@  discard block
 block discarded – undo
848 848
 
849 849
 			return $num;
850 850
 		} else {
851
-			$this->errors[] = 'Error ' . $this->db->lasterror();
852
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
851
+			$this->errors[] = 'Error '.$this->db->lasterror();
852
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
853 853
 
854
-			return - 1;
854
+			return -1;
855 855
 		}
856 856
 	}
857 857
 
@@ -876,49 +876,49 @@  discard block
 block discarded – undo
876 876
 		$sql .= " t.numero_compte,";
877 877
 		$sql .= " SUM(t.debit) as debit,";
878 878
 		$sql .= " SUM(t.credit) as credit";
879
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
879
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
880 880
 		// Manage filter
881
-		$sqlwhere = array ();
881
+		$sqlwhere = array();
882 882
 		if (count($filter) > 0) {
883
-			foreach ( $filter as $key => $value ) {
883
+			foreach ($filter as $key => $value) {
884 884
 				if ($key == 't.doc_date') {
885
-					$sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\'';
885
+					$sqlwhere[] = $key.'=\''.$this->db->idate($value).'\'';
886 886
 				} elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') {
887
-					$sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\'';
887
+					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
888 888
 				} elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
889
-					$sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\'';
889
+					$sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
890 890
 				} elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
891
-					$sqlwhere[] = $key . '=' . $value;
891
+					$sqlwhere[] = $key.'='.$value;
892 892
 				} elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
893
-					$sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\'';
893
+					$sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
894 894
 				} elseif ($key == 't.subledger_label') {
895
-					$sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\'';
895
+					$sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
896 896
 				} else {
897
-					$sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
897
+					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
898 898
 				}
899 899
 			}
900 900
 		}
901
-		$sql.= ' WHERE 1 = 1';
902
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
901
+		$sql .= ' WHERE 1 = 1';
902
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
903 903
 		if (count($sqlwhere) > 0) {
904
-			$sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere);
904
+			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
905 905
 		}
906 906
 
907 907
 		$sql .= ' GROUP BY t.numero_compte';
908 908
 
909
-		if (! empty($sortfield)) {
909
+		if (!empty($sortfield)) {
910 910
 			$sql .= $this->db->order($sortfield, $sortorder);
911 911
 		}
912
-		if (! empty($limit)) {
913
-			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
912
+		if (!empty($limit)) {
913
+			$sql .= ' '.$this->db->plimit($limit + 1, $offset);
914 914
 		}
915
-		$this->lines = array ();
915
+		$this->lines = array();
916 916
 
917 917
 		$resql = $this->db->query($sql);
918 918
 		if ($resql) {
919 919
 			$num = $this->db->num_rows($resql);
920 920
 
921
-			while ( $obj = $this->db->fetch_object($resql) ) {
921
+			while ($obj = $this->db->fetch_object($resql)) {
922 922
 				$line = new BookKeepingLine();
923 923
 
924 924
 				$line->numero_compte = $obj->numero_compte;
@@ -930,10 +930,10 @@  discard block
 block discarded – undo
930 930
 
931 931
 			return $num;
932 932
 		} else {
933
-			$this->errors[] = 'Error ' . $this->db->lasterror();
934
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
933
+			$this->errors[] = 'Error '.$this->db->lasterror();
934
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
935 935
 
936
-			return - 1;
936
+			return -1;
937 937
 		}
938 938
 	}
939 939
 
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 	 * @param  string  $mode       Mode
946 946
 	 * @return int                 <0 if KO, >0 if OK
947 947
 	 */
948
-	public function update(User $user, $notrigger = false, $mode='') {
948
+	public function update(User $user, $notrigger = false, $mode = '') {
949 949
 		$error = 0;
950 950
 
951 951
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -1016,39 +1016,39 @@  discard block
 block discarded – undo
1016 1016
 		// Put here code to add a control on parameters values
1017 1017
 
1018 1018
 		// Update request
1019
-		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . $mode.' SET';
1020
-		$sql .= ' doc_date = ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'" . $this->db->idate($this->doc_date) . "'" : 'null') . ',';
1021
-		$sql .= ' doc_type = ' . (isset($this->doc_type) ? "'" . $this->db->escape($this->doc_type) . "'" : "null") . ',';
1022
-		$sql .= ' doc_ref = ' . (isset($this->doc_ref) ? "'" . $this->db->escape($this->doc_ref) . "'" : "null") . ',';
1023
-		$sql .= ' fk_doc = ' . (isset($this->fk_doc) ? $this->fk_doc : "null") . ',';
1024
-		$sql .= ' fk_docdet = ' . (isset($this->fk_docdet) ? $this->fk_docdet : "null") . ',';
1025
-		$sql .= ' thirdparty_code = ' . (isset($this->thirdparty_code) ? "'" . $this->db->escape($this->thirdparty_code) . "'" : "null") . ',';
1026
-		$sql .= ' subledger_account = ' . (isset($this->subledger_account) ? "'" . $this->db->escape($this->subledger_account) . "'" : "null") . ',';
1027
-		$sql .= ' subledger_label = ' . (isset($this->subledger_label) ? "'" . $this->db->escape($this->subledger_label) . "'" : "null") . ',';
1028
-		$sql .= ' numero_compte = ' . (isset($this->numero_compte) ? "'" . $this->db->escape($this->numero_compte) . "'" : "null") . ',';
1029
-		$sql .= ' label_compte = ' . (isset($this->label_compte) ? "'" . $this->db->escape($this->label_compte) . "'" : "null") . ',';
1030
-		$sql .= ' label_operation = ' . (isset($this->label_operation) ? "'" . $this->db->escape($this->label_operation) . "'" : "null") . ',';
1031
-		$sql .= ' debit = ' . (isset($this->debit) ? $this->debit : "null") . ',';
1032
-		$sql .= ' credit = ' . (isset($this->credit) ? $this->credit : "null") . ',';
1033
-		$sql .= ' montant = ' . (isset($this->montant) ? $this->montant : "null") . ',';
1034
-		$sql .= ' sens = ' . (isset($this->sens) ? "'" . $this->db->escape($this->sens) . "'" : "null") . ',';
1035
-		$sql .= ' fk_user_author = ' . (isset($this->fk_user_author) ? $this->fk_user_author : "null") . ',';
1036
-		$sql .= ' import_key = ' . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ',';
1037
-		$sql .= ' code_journal = ' . (isset($this->code_journal) ? "'" . $this->db->escape($this->code_journal) . "'" : "null") . ',';
1038
-		$sql .= ' journal_label = ' . (isset($this->journal_label) ? "'" . $this->db->escape($this->journal_label) . "'" : "null") . ',';
1039
-		$sql .= ' piece_num = ' . (isset($this->piece_num) ? $this->piece_num : "null");
1040
-		$sql .= ' WHERE rowid=' . $this->id;
1019
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.$mode.' SET';
1020
+		$sql .= ' doc_date = '.(!isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'".$this->db->idate($this->doc_date)."'" : 'null').',';
1021
+		$sql .= ' doc_type = '.(isset($this->doc_type) ? "'".$this->db->escape($this->doc_type)."'" : "null").',';
1022
+		$sql .= ' doc_ref = '.(isset($this->doc_ref) ? "'".$this->db->escape($this->doc_ref)."'" : "null").',';
1023
+		$sql .= ' fk_doc = '.(isset($this->fk_doc) ? $this->fk_doc : "null").',';
1024
+		$sql .= ' fk_docdet = '.(isset($this->fk_docdet) ? $this->fk_docdet : "null").',';
1025
+		$sql .= ' thirdparty_code = '.(isset($this->thirdparty_code) ? "'".$this->db->escape($this->thirdparty_code)."'" : "null").',';
1026
+		$sql .= ' subledger_account = '.(isset($this->subledger_account) ? "'".$this->db->escape($this->subledger_account)."'" : "null").',';
1027
+		$sql .= ' subledger_label = '.(isset($this->subledger_label) ? "'".$this->db->escape($this->subledger_label)."'" : "null").',';
1028
+		$sql .= ' numero_compte = '.(isset($this->numero_compte) ? "'".$this->db->escape($this->numero_compte)."'" : "null").',';
1029
+		$sql .= ' label_compte = '.(isset($this->label_compte) ? "'".$this->db->escape($this->label_compte)."'" : "null").',';
1030
+		$sql .= ' label_operation = '.(isset($this->label_operation) ? "'".$this->db->escape($this->label_operation)."'" : "null").',';
1031
+		$sql .= ' debit = '.(isset($this->debit) ? $this->debit : "null").',';
1032
+		$sql .= ' credit = '.(isset($this->credit) ? $this->credit : "null").',';
1033
+		$sql .= ' montant = '.(isset($this->montant) ? $this->montant : "null").',';
1034
+		$sql .= ' sens = '.(isset($this->sens) ? "'".$this->db->escape($this->sens)."'" : "null").',';
1035
+		$sql .= ' fk_user_author = '.(isset($this->fk_user_author) ? $this->fk_user_author : "null").',';
1036
+		$sql .= ' import_key = '.(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").',';
1037
+		$sql .= ' code_journal = '.(isset($this->code_journal) ? "'".$this->db->escape($this->code_journal)."'" : "null").',';
1038
+		$sql .= ' journal_label = '.(isset($this->journal_label) ? "'".$this->db->escape($this->journal_label)."'" : "null").',';
1039
+		$sql .= ' piece_num = '.(isset($this->piece_num) ? $this->piece_num : "null");
1040
+		$sql .= ' WHERE rowid='.$this->id;
1041 1041
 
1042 1042
 		$this->db->begin();
1043 1043
 
1044 1044
 		$resql = $this->db->query($sql);
1045
-		if (! $resql) {
1046
-			$error ++;
1047
-			$this->errors[] = 'Error ' . $this->db->lasterror();
1048
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1045
+		if (!$resql) {
1046
+			$error++;
1047
+			$this->errors[] = 'Error '.$this->db->lasterror();
1048
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1049 1049
 		}
1050 1050
 
1051
-		if (! $error && ! $notrigger) {
1051
+		if (!$error && !$notrigger) {
1052 1052
 			// Uncomment this and change MYOBJECT to your own tag if you
1053 1053
 			// want this action calls a trigger.
1054 1054
 
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
 		if ($error) {
1063 1063
 			$this->db->rollback();
1064 1064
 
1065
-			return - 1 * $error;
1065
+			return -1 * $error;
1066 1066
 		} else {
1067 1067
 			$this->db->commit();
1068 1068
 
@@ -1079,22 +1079,22 @@  discard block
 block discarded – undo
1079 1079
 	 * @param  string  $mode           Mode
1080 1080
 	 * @return number                  <0 if KO, >0 if OK
1081 1081
 	 */
1082
-	public function updateByMvt($piece_num='', $field='', $value='', $mode='') {
1082
+	public function updateByMvt($piece_num = '', $field = '', $value = '', $mode = '') {
1083 1083
 		$this->db->begin();
1084
-		$sql = "UPDATE " . MAIN_DB_PREFIX .  $this->table_element . $mode . " as ab";
1085
-		$sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$value."'");
1086
-		$sql .= ' WHERE ab.piece_num=' . $piece_num ;
1084
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.$mode." as ab";
1085
+		$sql .= ' SET ab.'.$field.'='.(is_numeric($value) ? $value : "'".$value."'");
1086
+		$sql .= ' WHERE ab.piece_num='.$piece_num;
1087 1087
 		$resql = $this->db->query($sql);
1088 1088
 
1089
-		if (! $resql) {
1090
-			$error ++;
1091
-			$this->errors[] = 'Error ' . $this->db->lasterror();
1092
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1089
+		if (!$resql) {
1090
+			$error++;
1091
+			$this->errors[] = 'Error '.$this->db->lasterror();
1092
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1093 1093
 		}
1094 1094
 		if ($error) {
1095 1095
 			$this->db->rollback();
1096 1096
 
1097
-			return - 1 * $error;
1097
+			return -1 * $error;
1098 1098
 		} else {
1099 1099
 			$this->db->commit();
1100 1100
 
@@ -1110,15 +1110,15 @@  discard block
 block discarded – undo
1110 1110
 	 * @param string $mode Mode
1111 1111
 	 * @return int <0 if KO, >0 if OK
1112 1112
 	 */
1113
-	public function delete(User $user, $notrigger = false, $mode='') {
1113
+	public function delete(User $user, $notrigger = false, $mode = '') {
1114 1114
 		dol_syslog(__METHOD__, LOG_DEBUG);
1115 1115
 
1116 1116
 		$error = 0;
1117 1117
 
1118 1118
 		$this->db->begin();
1119 1119
 
1120
-		if (! $error) {
1121
-			if (! $notrigger) {
1120
+		if (!$error) {
1121
+			if (!$notrigger) {
1122 1122
 				// Uncomment this and change MYOBJECT to your own tag if you
1123 1123
 				// want this action calls a trigger.
1124 1124
 
@@ -1129,15 +1129,15 @@  discard block
 block discarded – undo
1129 1129
 			}
1130 1130
 		}
1131 1131
 
1132
-		if (! $error) {
1133
-			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element.$mode;
1134
-			$sql .= ' WHERE rowid=' . $this->id;
1132
+		if (!$error) {
1133
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.$mode;
1134
+			$sql .= ' WHERE rowid='.$this->id;
1135 1135
 
1136 1136
 			$resql = $this->db->query($sql);
1137
-			if (! $resql) {
1138
-				$error ++;
1139
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1140
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1137
+			if (!$resql) {
1138
+				$error++;
1139
+				$this->errors[] = 'Error '.$this->db->lasterror();
1140
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1141 1141
 			}
1142 1142
 		}
1143 1143
 
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 		if ($error) {
1146 1146
 			$this->db->rollback();
1147 1147
 
1148
-			return - 1 * $error;
1148
+			return -1 * $error;
1149 1149
 		} else {
1150 1150
 			$this->db->commit();
1151 1151
 
@@ -1164,16 +1164,16 @@  discard block
 block discarded – undo
1164 1164
 
1165 1165
 		// first check if line not yet in bookkeeping
1166 1166
 		$sql = "DELETE";
1167
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
1168
-		$sql .= " WHERE import_key = '" . $importkey . "'";
1167
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1168
+		$sql .= " WHERE import_key = '".$importkey."'";
1169 1169
 
1170 1170
 		$resql = $this->db->query($sql);
1171 1171
 
1172
-		if (! $resql) {
1173
-			$this->errors[] = "Error " . $this->db->lasterror();
1174
-			dol_syslog(get_class($this)."::delete Error " . $this->db->lasterror(), LOG_ERR);
1172
+		if (!$resql) {
1173
+			$this->errors[] = "Error ".$this->db->lasterror();
1174
+			dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
1175 1175
 			$this->db->rollback();
1176
-			return - 1;
1176
+			return -1;
1177 1177
 		}
1178 1178
 
1179 1179
 		$this->db->commit();
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
 	 * @param  string $mode 		Mode
1189 1189
 	 * @return int					<0 if KO, >0 if OK
1190 1190
 	 */
1191
-	function deleteByYearAndJournal($delyear='', $journal='', $mode='') {
1191
+	function deleteByYearAndJournal($delyear = '', $journal = '', $mode = '') {
1192 1192
 		global $conf;
1193 1193
 
1194 1194
 		if (empty($delyear) && empty($journal))
@@ -1200,18 +1200,18 @@  discard block
 block discarded – undo
1200 1200
 
1201 1201
 		// first check if line not yet in bookkeeping
1202 1202
 		$sql = "DELETE";
1203
-		$sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode;
1204
-		$sql.= " WHERE 1 = 1";
1205
-		if (! empty($delyear)) $sql.= " AND YEAR(doc_date) = " . $delyear;		 // FIXME Must use between
1206
-		if (! empty($journal)) $sql.= " AND code_journal = '".$journal."'";
1207
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
1203
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
1204
+		$sql .= " WHERE 1 = 1";
1205
+		if (!empty($delyear)) $sql .= " AND YEAR(doc_date) = ".$delyear; // FIXME Must use between
1206
+		if (!empty($journal)) $sql .= " AND code_journal = '".$journal."'";
1207
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
1208 1208
 		$resql = $this->db->query($sql);
1209 1209
 
1210
-		if (! $resql) {
1211
-			$this->errors[] = "Error " . $this->db->lasterror();
1212
-			foreach ( $this->errors as $errmsg ) {
1213
-				dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
1214
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
1210
+		if (!$resql) {
1211
+			$this->errors[] = "Error ".$this->db->lasterror();
1212
+			foreach ($this->errors as $errmsg) {
1213
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1214
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1215 1215
 			}
1216 1216
 			$this->db->rollback();
1217 1217
 			return -1;
@@ -1234,20 +1234,20 @@  discard block
 block discarded – undo
1234 1234
 
1235 1235
 		// first check if line not yet in bookkeeping
1236 1236
 		$sql = "DELETE";
1237
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
1238
-		$sql .= " WHERE piece_num = " . $piecenum;
1239
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
1237
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1238
+		$sql .= " WHERE piece_num = ".$piecenum;
1239
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
1240 1240
 
1241 1241
 		$resql = $this->db->query($sql);
1242 1242
 
1243
-		if (! $resql) {
1244
-			$this->errors[] = "Error " . $this->db->lasterror();
1245
-			foreach ( $this->errors as $errmsg ) {
1246
-				dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
1247
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
1243
+		if (!$resql) {
1244
+			$this->errors[] = "Error ".$this->db->lasterror();
1245
+			foreach ($this->errors as $errmsg) {
1246
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1247
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1248 1248
 			}
1249 1249
 			$this->db->rollback();
1250
-			return - 1;
1250
+			return -1;
1251 1251
 		}
1252 1252
 
1253 1253
 		$this->db->commit();
@@ -1283,20 +1283,20 @@  discard block
 block discarded – undo
1283 1283
 
1284 1284
 		// Other options
1285 1285
 		if ($result < 0) {
1286
-			$error ++;
1286
+			$error++;
1287 1287
 			$this->errors = $object->errors;
1288
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1288
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1289 1289
 		}
1290 1290
 
1291 1291
 		// End
1292
-		if (! $error) {
1292
+		if (!$error) {
1293 1293
 			$this->db->commit();
1294 1294
 
1295 1295
 			return $object->id;
1296 1296
 		} else {
1297 1297
 			$this->db->rollback();
1298 1298
 
1299
-			return - 1;
1299
+			return -1;
1300 1300
 		}
1301 1301
 	}
1302 1302
 
@@ -1309,7 +1309,7 @@  discard block
 block discarded – undo
1309 1309
 	public function initAsSpecimen() {
1310 1310
 		global $user;
1311 1311
 
1312
-		$now=dol_now();
1312
+		$now = dol_now();
1313 1313
 
1314 1314
 		$this->id = 0;
1315 1315
 		$this->doc_date = $now;
@@ -1341,15 +1341,15 @@  discard block
 block discarded – undo
1341 1341
 	 * @param string $mode Mode
1342 1342
 	 * @return int <0 if KO, >0 if OK
1343 1343
 	 */
1344
-	public function fetchPerMvt($piecenum, $mode='') {
1344
+	public function fetchPerMvt($piecenum, $mode = '') {
1345 1345
 		global $conf;
1346 1346
 
1347 1347
 		$sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type";
1348
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode;
1349
-		$sql .= " WHERE piece_num = " . $piecenum;
1350
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
1348
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
1349
+		$sql .= " WHERE piece_num = ".$piecenum;
1350
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
1351 1351
 
1352
-		dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG);
1352
+		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
1353 1353
 		$result = $this->db->query($sql);
1354 1354
 		if ($result) {
1355 1355
 			$obj = $this->db->fetch_object($result);
@@ -1361,9 +1361,9 @@  discard block
 block discarded – undo
1361 1361
 			$this->doc_ref = $obj->doc_ref;
1362 1362
 			$this->doc_type = $obj->doc_type;
1363 1363
 		} else {
1364
-			$this->error = "Error " . $this->db->lasterror();
1365
-			dol_syslog(get_class($this) . "::" . __METHOD__ . $this->error, LOG_ERR);
1366
-			return - 1;
1364
+			$this->error = "Error ".$this->db->lasterror();
1365
+			dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
1366
+			return -1;
1367 1367
 		}
1368 1368
 
1369 1369
 		return 1;
@@ -1375,14 +1375,14 @@  discard block
 block discarded – undo
1375 1375
 	 * @param	string	$mode	Mode
1376 1376
 	 * @return	string			Next numero to use
1377 1377
 	 */
1378
-	public function getNextNumMvt($mode='')
1378
+	public function getNextNumMvt($mode = '')
1379 1379
 	{
1380 1380
 		global $conf;
1381 1381
 
1382
-		$sql = "SELECT MAX(piece_num)+1 as max FROM " . MAIN_DB_PREFIX . $this->table_element.$mode;
1383
-		$sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
1382
+		$sql = "SELECT MAX(piece_num)+1 as max FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
1383
+		$sql .= " WHERE entity IN (".getEntity('accountancy').")";
1384 1384
 
1385
-		dol_syslog(get_class($this) . "getNextNumMvt sql=" . $sql, LOG_DEBUG);
1385
+		dol_syslog(get_class($this)."getNextNumMvt sql=".$sql, LOG_DEBUG);
1386 1386
 		$result = $this->db->query($sql);
1387 1387
 
1388 1388
 		if ($result) {
@@ -1391,9 +1391,9 @@  discard block
 block discarded – undo
1391 1391
 			if (empty($result)) $result = 1;
1392 1392
 			return $result;
1393 1393
 		} else {
1394
-			$this->error = "Error " . $this->db->lasterror();
1395
-			dol_syslog(get_class($this) . "::getNextNumMvt " . $this->error, LOG_ERR);
1396
-			return - 1;
1394
+			$this->error = "Error ".$this->db->lasterror();
1395
+			dol_syslog(get_class($this)."::getNextNumMvt ".$this->error, LOG_ERR);
1396
+			return -1;
1397 1397
 		}
1398 1398
 	}
1399 1399
 
@@ -1404,22 +1404,22 @@  discard block
 block discarded – undo
1404 1404
 	 * @param  string  $mode       Mode
1405 1405
 	 * @return int                 <0 if KO, >0 if OK
1406 1406
 	 */
1407
-	function fetchAllPerMvt($piecenum, $mode='') {
1407
+	function fetchAllPerMvt($piecenum, $mode = '') {
1408 1408
 		global $conf;
1409 1409
 
1410 1410
 		$sql = "SELECT rowid, doc_date, doc_type,";
1411 1411
 		$sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
1412 1412
 		$sql .= " numero_compte, label_compte, label_operation, debit, credit,";
1413 1413
 		$sql .= " montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num";
1414
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode;
1415
-		$sql .= " WHERE piece_num = " . $piecenum;
1416
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
1414
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
1415
+		$sql .= " WHERE piece_num = ".$piecenum;
1416
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
1417 1417
 
1418
-		dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG);
1418
+		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
1419 1419
 		$result = $this->db->query($sql);
1420 1420
 		if ($result) {
1421 1421
 
1422
-			while ( $obj = $this->db->fetch_object($result) ) {
1422
+			while ($obj = $this->db->fetch_object($result)) {
1423 1423
 
1424 1424
 				$line = new BookKeepingLine();
1425 1425
 
@@ -1447,9 +1447,9 @@  discard block
 block discarded – undo
1447 1447
 				$this->linesmvt[] = $line;
1448 1448
 			}
1449 1449
 		} else {
1450
-			$this->error = "Error " . $this->db->lasterror();
1451
-			dol_syslog(get_class($this) . "::" . __METHOD__ . $this->error, LOG_ERR);
1452
-			return - 1;
1450
+			$this->error = "Error ".$this->db->lasterror();
1451
+			dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
1452
+			return -1;
1453 1453
 		}
1454 1454
 
1455 1455
 		return 1;
@@ -1468,18 +1468,18 @@  discard block
 block discarded – undo
1468 1468
 		$sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
1469 1469
 		$sql .= " numero_compte, label_compte, label_operation, debit, credit,";
1470 1470
 		$sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num";
1471
-		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
1472
-		$sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
1471
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1472
+		$sql .= " WHERE entity IN (".getEntity('accountancy').")";
1473 1473
 
1474
-		dol_syslog(get_class($this) . "::export_bookkeping", LOG_DEBUG);
1474
+		dol_syslog(get_class($this)."::export_bookkeping", LOG_DEBUG);
1475 1475
 
1476 1476
 		$resql = $this->db->query($sql);
1477 1477
 
1478 1478
 		if ($resql) {
1479
-			$this->linesexport = array ();
1479
+			$this->linesexport = array();
1480 1480
 
1481 1481
 			$num = $this->db->num_rows($resql);
1482
-			while ( $obj = $this->db->fetch_object($resql) ) {
1482
+			while ($obj = $this->db->fetch_object($resql)) {
1483 1483
 				$line = new BookKeepingLine();
1484 1484
 
1485 1485
 				$line->id = $obj->rowid;
@@ -1508,9 +1508,9 @@  discard block
 block discarded – undo
1508 1508
 
1509 1509
 			return $num;
1510 1510
 		} else {
1511
-			$this->error = "Error " . $this->db->lasterror();
1512
-			dol_syslog(get_class($this) . "::export_bookkeping " . $this->error, LOG_ERR);
1513
-			return - 1;
1511
+			$this->error = "Error ".$this->db->lasterror();
1512
+			dol_syslog(get_class($this)."::export_bookkeping ".$this->error, LOG_ERR);
1513
+			return -1;
1514 1514
 		}
1515 1515
 	}
1516 1516
 
@@ -1521,14 +1521,14 @@  discard block
 block discarded – undo
1521 1521
 	 * @param  string   $piece_num     Piece num
1522 1522
 	 * @return void
1523 1523
 	 */
1524
-	public function transformTransaction($direction=0,$piece_num='') {
1524
+	public function transformTransaction($direction = 0, $piece_num = '') {
1525 1525
 		$this->db->begin();
1526
-		if ($direction==0) {
1527
-			$next_piecenum=$this->getNextNumMvt();
1526
+		if ($direction == 0) {
1527
+			$next_piecenum = $this->getNextNumMvt();
1528 1528
 			if ($result < 0) {
1529 1529
 				$error++;
1530 1530
 			}
1531
-			$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element.'(doc_date, doc_type,';
1531
+			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(doc_date, doc_type,';
1532 1532
 			$sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
1533 1533
 			$sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
1534 1534
 			$sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num)';
@@ -1536,30 +1536,30 @@  discard block
 block discarded – undo
1536 1536
 			$sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
1537 1537
 			$sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
1538 1538
 			$sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, '.$next_piecenum.'';
1539
-			$sql .= ' FROM '.MAIN_DB_PREFIX . $this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1539
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1540 1540
 			$resql = $this->db->query($sql);
1541
-			if (! $resql) {
1542
-				$error ++;
1543
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1544
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1541
+			if (!$resql) {
1542
+				$error++;
1543
+				$this->errors[] = 'Error '.$this->db->lasterror();
1544
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1545 1545
 			}
1546
-			$sql = 'DELETE FROM '.MAIN_DB_PREFIX . $this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1546
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1547 1547
 			$resql = $this->db->query($sql);
1548
-			if (! $resql) {
1549
-				$error ++;
1550
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1551
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1548
+			if (!$resql) {
1549
+				$error++;
1550
+				$this->errors[] = 'Error '.$this->db->lasterror();
1551
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1552 1552
 			}
1553 1553
 		}
1554
-		if ($direction==1) {
1555
-			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1554
+		if ($direction == 1) {
1555
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1556 1556
 			$resql = $this->db->query($sql);
1557
-			if (! $resql) {
1558
-				$error ++;
1559
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1560
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1557
+			if (!$resql) {
1558
+				$error++;
1559
+				$this->errors[] = 'Error '.$this->db->lasterror();
1560
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1561 1561
 			}
1562
-			$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element.'_tmp(doc_date, doc_type,';
1562
+			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'_tmp(doc_date, doc_type,';
1563 1563
 			$sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
1564 1564
 			$sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
1565 1565
 			$sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num)';
@@ -1567,27 +1567,27 @@  discard block
 block discarded – undo
1567 1567
 			$sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
1568 1568
 			$sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
1569 1569
 			$sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num';
1570
-			$sql .= ' FROM '.MAIN_DB_PREFIX . $this->table_element.' WHERE piece_num = '.$piece_num;
1570
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.$piece_num;
1571 1571
 			$resql = $this->db->query($sql);
1572
-			if (! $resql) {
1573
-				$error ++;
1574
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1575
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1572
+			if (!$resql) {
1573
+				$error++;
1574
+				$this->errors[] = 'Error '.$this->db->lasterror();
1575
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1576 1576
 			}
1577
-			$sql = 'DELETE FROM '.MAIN_DB_PREFIX . $this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1577
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num;
1578 1578
 			$resql = $this->db->query($sql);
1579
-			if (! $resql) {
1580
-				$error ++;
1581
-				$this->errors[] = 'Error ' . $this->db->lasterror();
1582
-				dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
1579
+			if (!$resql) {
1580
+				$error++;
1581
+				$this->errors[] = 'Error '.$this->db->lasterror();
1582
+				dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1583 1583
 			}
1584 1584
 		}
1585
-		if (! $error) {
1585
+		if (!$error) {
1586 1586
 			$this->db->commit();
1587 1587
 			return 1;
1588 1588
 		} else {
1589 1589
 			$this->db->rollback();
1590
-			return - 1;
1590
+			return -1;
1591 1591
 		}
1592 1592
 		/*
1593 1593
 		$sql = "DELETE FROM ";
@@ -1616,26 +1616,26 @@  discard block
 block discarded – undo
1616 1616
 	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') {
1617 1617
 		global $conf;
1618 1618
 
1619
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
1619
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1620 1620
 
1621 1621
 		$pcgver = $conf->global->CHARTOFACCOUNTS;
1622 1622
 
1623 1623
 		$sql = "SELECT DISTINCT ab.numero_compte as account_number, aa.label as label, aa.rowid as rowid, aa.fk_pcg_version";
1624
-		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab";
1625
-		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.account_number = ab.numero_compte";
1624
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab";
1625
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.account_number = ab.numero_compte";
1626 1626
 		$sql .= " AND aa.active = 1";
1627
-		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1628
-		$sql .= " AND asy.rowid = " . $pcgver;
1629
-		$sql .= " AND ab.entity IN (" . getEntity('accountancy') . ")";
1627
+		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1628
+		$sql .= " AND asy.rowid = ".$pcgver;
1629
+		$sql .= " AND ab.entity IN (".getEntity('accountancy').")";
1630 1630
 		$sql .= " ORDER BY account_number ASC";
1631 1631
 
1632
-		dol_syslog(get_class($this) . "::select_account", LOG_DEBUG);
1632
+		dol_syslog(get_class($this)."::select_account", LOG_DEBUG);
1633 1633
 		$resql = $this->db->query($sql);
1634 1634
 
1635
-		if (! $resql) {
1636
-			$this->error = "Error " . $this->db->lasterror();
1637
-			dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR);
1638
-			return - 1;
1635
+		if (!$resql) {
1636
+			$this->error = "Error ".$this->db->lasterror();
1637
+			dol_syslog(get_class($this)."::select_account ".$this->error, LOG_ERR);
1638
+			return -1;
1639 1639
 		}
1640 1640
 
1641 1641
 		$out = ajax_combobox($htmlname, $event);
@@ -1644,7 +1644,7 @@  discard block
 block discarded – undo
1644 1644
 		$selected = null;
1645 1645
 
1646 1646
 		while ($obj = $this->db->fetch_object($resql)) {
1647
-			$label = length_accountg($obj->account_number) . ' - ' . $obj->label;
1647
+			$label = length_accountg($obj->account_number).' - '.$obj->label;
1648 1648
 
1649 1649
 			$select_value_in = $obj->rowid;
1650 1650
 			$select_value_out = $obj->rowid;
@@ -1682,17 +1682,17 @@  discard block
 block discarded – undo
1682 1682
 		$pcgver = $conf->global->CHARTOFACCOUNTS;
1683 1683
 
1684 1684
 		$sql  = "SELECT root.account_number, root.label as label";
1685
-		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
1686
-		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1687
-		$sql .= " AND asy.rowid = " . $pcgver;
1688
-		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as parent ON aa.account_parent = parent.rowid";
1689
-		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as root ON parent.account_parent = root.rowid";
1690
-		$sql .= " WHERE aa.account_number = '" . $account . "'";
1685
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa";
1686
+		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1687
+		$sql .= " AND asy.rowid = ".$pcgver;
1688
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid";
1689
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid";
1690
+		$sql .= " WHERE aa.account_number = '".$account."'";
1691 1691
 		$sql .= " AND parent.active = 1";
1692 1692
 		$sql .= " AND root.active = 1";
1693
-		$sql .= " AND aa.entity IN (" . getEntity('accountancy') . ")";
1693
+		$sql .= " AND aa.entity IN (".getEntity('accountancy').")";
1694 1694
 
1695
-		dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG);
1695
+		dol_syslog(get_class($this)."::select_account sql=".$sql, LOG_DEBUG);
1696 1696
 		$resql = $this->db->query($sql);
1697 1697
 		if ($resql) {
1698 1698
 			$obj = '';
@@ -1703,8 +1703,8 @@  discard block
 block discarded – undo
1703 1703
 			return $obj->label;
1704 1704
 
1705 1705
 		} else {
1706
-			$this->error = "Error " . $this->db->lasterror();
1707
-			dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR);
1706
+			$this->error = "Error ".$this->db->lasterror();
1707
+			dol_syslog(__METHOD__." ".$this->error, LOG_ERR);
1708 1708
 
1709 1709
 			return -1;
1710 1710
 		}
@@ -1722,29 +1722,29 @@  discard block
 block discarded – undo
1722 1722
 
1723 1723
 		$pcgver = $conf->global->CHARTOFACCOUNTS;
1724 1724
 		$sql  = "SELECT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version, cat.label as category";
1725
-		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa ";
1726
-		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1727
-		$sql .= " AND aa.account_number = '" . $account . "'";
1728
-		$sql .= " AND asy.rowid = " . $pcgver;
1725
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa ";
1726
+		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
1727
+		$sql .= " AND aa.account_number = '".$account."'";
1728
+		$sql .= " AND asy.rowid = ".$pcgver;
1729 1729
 		$sql .= " AND aa.active = 1";
1730
-		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid";
1731
-		$sql .= " WHERE aa.entity IN (" . getEntity('accountancy') . ")";
1730
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid";
1731
+		$sql .= " WHERE aa.entity IN (".getEntity('accountancy').")";
1732 1732
 
1733
-		dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG);
1733
+		dol_syslog(get_class($this)."::select_account sql=".$sql, LOG_DEBUG);
1734 1734
 		$resql = $this->db->query($sql);
1735 1735
 		if ($resql) {
1736 1736
 			$obj = '';
1737 1737
 			if ($this->db->num_rows($resql)) {
1738 1738
 				$obj = $this->db->fetch_object($resql);
1739 1739
 			}
1740
-			if(empty($obj->category)){
1740
+			if (empty($obj->category)) {
1741 1741
 				return $obj->label;
1742
-			}else{
1742
+			} else {
1743 1743
 				return $obj->label.' ('.$obj->category.')';
1744 1744
 			}
1745 1745
 		} else {
1746
-			$this->error = "Error " . $this->db->lasterror();
1747
-			dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR);
1746
+			$this->error = "Error ".$this->db->lasterror();
1747
+			dol_syslog(__METHOD__." ".$this->error, LOG_ERR);
1748 1748
 			return -1;
1749 1749
 		}
1750 1750
 	}
Please login to merge, or discard this patch.
htdocs/public/agenda/agendaexport.php 3 patches
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -108,12 +108,12 @@  discard block
 block discarded – undo
108 108
 // Complete long filename
109 109
 foreach ($filters as $key => $value)
110 110
 {
111
-    //if ($key == 'notolderthan')    $filename.='-notolderthan'.$value; This filter key is already added before and does not need to be in filename
111
+	//if ($key == 'notolderthan')    $filename.='-notolderthan'.$value; This filter key is already added before and does not need to be in filename
112 112
 	if ($key == 'year')            $filename.='-year'.$value;
113
-    if ($key == 'id')              $filename.='-id'.$value;
114
-    if ($key == 'idfrom')          $filename.='-idfrom'.$value;
115
-    if ($key == 'idto')            $filename.='-idto'.$value;
116
-    if ($key == 'project')         $filename.='-project'.$value;
113
+	if ($key == 'id')              $filename.='-id'.$value;
114
+	if ($key == 'idfrom')          $filename.='-idfrom'.$value;
115
+	if ($key == 'idto')            $filename.='-idto'.$value;
116
+	if ($key == 'project')         $filename.='-project'.$value;
117 117
 	if ($key == 'logina')	       $filename.='-logina'.$value;	// Author
118 118
 	if ($key == 'logint')	       $filename.='-logint'.$value;	// Assigned to
119 119
 }
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	$langs->load("main");
128 128
 	$langs->load("errors");
129 129
 	llxHeaderVierge();
130
-    print '<div class="error">'.$langs->trans("ErrorWrongValueForParameterX",'format').'</div>';
130
+	print '<div class="error">'.$langs->trans("ErrorWrongValueForParameterX",'format').'</div>';
131 131
 	llxFooterVierge();
132 132
 	exit;
133 133
 }
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 		$result=readfile($outputfile);
163 163
 		if (! $result) print 'File '.$outputfile.' was empty.';
164 164
 
165
-	    //header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
165
+		//header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
166 166
 		exit;
167 167
 	}
168 168
 	else
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -32,12 +32,12 @@  discard block
 block discarded – undo
32 32
 //if (! defined('NOREQUIREDB'))    define('NOREQUIREDB','1');
33 33
 //if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
34 34
 //if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
35
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
36
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1'); // If there is no menu to show
37
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
38
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
39
-define("NOLOGIN",1);		// This means this output page does not require to be logged.
40
-define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
35
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
36
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1'); // If there is no menu to show
37
+if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
38
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
39
+define("NOLOGIN", 1); // This means this output page does not require to be logged.
40
+define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
41 41
 
42 42
 // C'est un wrapper, donc header vierge
43 43
 /**
@@ -57,27 +57,27 @@  discard block
 block discarded – undo
57 57
 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
58 58
 
59 59
 // Security check
60
-if (empty($conf->agenda->enabled)) accessforbidden('',0,0,1);
60
+if (empty($conf->agenda->enabled)) accessforbidden('', 0, 0, 1);
61 61
 
62 62
 // Not older than
63
-if (! isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY=100;	// default limit
63
+if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100; // default limit
64 64
 
65 65
 // Define format, type and filter
66
-$format='ical';
67
-$type='event';
68
-if (GETPOST("format",'alpha')) $format=GETPOST("format",'apha');
69
-if (GETPOST("type",'apha'))   $type=GETPOST("type",'alpha');
70
-
71
-$filters=array();
72
-if (GETPOST("year",'int')) 	        $filters['year']=GETPOST("year",'int');
73
-if (GETPOST("id",'int'))            $filters['id']=GETPOST("id",'int');
74
-if (GETPOST("idfrom",'int'))        $filters['idfrom']=GETPOST("idfrom",'int');
75
-if (GETPOST("idto",'int'))          $filters['idto']=GETPOST("idto",'int');
76
-if (GETPOST("project",'apha'))      $filters['project']=GETPOST("project",'apha');
77
-if (GETPOST("logina",'apha'))       $filters['logina']=GETPOST("logina",'apha');
78
-if (GETPOST("logint",'apha'))       $filters['logint']=GETPOST("logint",'apha');
79
-if (GETPOST("notolderthan",'int'))  $filters['notolderthan']=GETPOST("notolderthan","int");
80
-else $filters['notolderthan']=$conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY;
66
+$format = 'ical';
67
+$type = 'event';
68
+if (GETPOST("format", 'alpha')) $format = GETPOST("format", 'apha');
69
+if (GETPOST("type", 'apha'))   $type = GETPOST("type", 'alpha');
70
+
71
+$filters = array();
72
+if (GETPOST("year", 'int')) 	        $filters['year'] = GETPOST("year", 'int');
73
+if (GETPOST("id", 'int'))            $filters['id'] = GETPOST("id", 'int');
74
+if (GETPOST("idfrom", 'int'))        $filters['idfrom'] = GETPOST("idfrom", 'int');
75
+if (GETPOST("idto", 'int'))          $filters['idto'] = GETPOST("idto", 'int');
76
+if (GETPOST("project", 'apha'))      $filters['project'] = GETPOST("project", 'apha');
77
+if (GETPOST("logina", 'apha'))       $filters['logina'] = GETPOST("logina", 'apha');
78
+if (GETPOST("logint", 'apha'))       $filters['logint'] = GETPOST("logint", 'apha');
79
+if (GETPOST("notolderthan", 'int'))  $filters['notolderthan'] = GETPOST("notolderthan", "int");
80
+else $filters['notolderthan'] = $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY;
81 81
 
82 82
 // Check config
83 83
 if (empty($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY))
@@ -103,64 +103,64 @@  discard block
 block discarded – undo
103 103
 
104 104
 
105 105
 // Define filename with prefix on filters predica (each predica set must have on cache file)
106
-$shortfilename='dolibarrcalendar';
107
-$filename=$shortfilename;
106
+$shortfilename = 'dolibarrcalendar';
107
+$filename = $shortfilename;
108 108
 // Complete long filename
109 109
 foreach ($filters as $key => $value)
110 110
 {
111 111
     //if ($key == 'notolderthan')    $filename.='-notolderthan'.$value; This filter key is already added before and does not need to be in filename
112
-	if ($key == 'year')            $filename.='-year'.$value;
113
-    if ($key == 'id')              $filename.='-id'.$value;
114
-    if ($key == 'idfrom')          $filename.='-idfrom'.$value;
115
-    if ($key == 'idto')            $filename.='-idto'.$value;
116
-    if ($key == 'project')         $filename.='-project'.$value;
117
-	if ($key == 'logina')	       $filename.='-logina'.$value;	// Author
118
-	if ($key == 'logint')	       $filename.='-logint'.$value;	// Assigned to
112
+	if ($key == 'year')            $filename .= '-year'.$value;
113
+    if ($key == 'id')              $filename .= '-id'.$value;
114
+    if ($key == 'idfrom')          $filename .= '-idfrom'.$value;
115
+    if ($key == 'idto')            $filename .= '-idto'.$value;
116
+    if ($key == 'project')         $filename .= '-project'.$value;
117
+	if ($key == 'logina')	       $filename .= '-logina'.$value; // Author
118
+	if ($key == 'logint')	       $filename .= '-logint'.$value; // Assigned to
119 119
 }
120 120
 // Add extension
121
-if ($format == 'vcal') { $shortfilename.='.vcs'; $filename.='.vcs'; }
122
-if ($format == 'ical') { $shortfilename.='.ics'; $filename.='.ics'; }
123
-if ($format == 'rss')  { $shortfilename.='.rss'; $filename.='.rss'; }
121
+if ($format == 'vcal') { $shortfilename .= '.vcs'; $filename .= '.vcs'; }
122
+if ($format == 'ical') { $shortfilename .= '.ics'; $filename .= '.ics'; }
123
+if ($format == 'rss') { $shortfilename .= '.rss'; $filename .= '.rss'; }
124 124
 
125
-if ($shortfilename=='dolibarrcalendar')
125
+if ($shortfilename == 'dolibarrcalendar')
126 126
 {
127 127
 	$langs->load("main");
128 128
 	$langs->load("errors");
129 129
 	llxHeaderVierge();
130
-    print '<div class="error">'.$langs->trans("ErrorWrongValueForParameterX",'format').'</div>';
130
+    print '<div class="error">'.$langs->trans("ErrorWrongValueForParameterX", 'format').'</div>';
131 131
 	llxFooterVierge();
132 132
 	exit;
133 133
 }
134 134
 
135
-$agenda=new ActionComm($db);
135
+$agenda = new ActionComm($db);
136 136
 
137
-$cachedelay=0;
138
-if (! empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) $cachedelay=$conf->global->MAIN_AGENDA_EXPORT_CACHE;
137
+$cachedelay = 0;
138
+if (!empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) $cachedelay = $conf->global->MAIN_AGENDA_EXPORT_CACHE;
139 139
 
140 140
 // Build file
141 141
 if ($format == 'ical' || $format == 'vcal')
142 142
 {
143
-	$result=$agenda->build_exportfile($format,$type,$cachedelay,$filename,$filters);
143
+	$result = $agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters);
144 144
 	if ($result >= 0)
145 145
 	{
146 146
 		$attachment = true;
147
-		if (isset($_GET["attachment"])) $attachment=$_GET["attachment"];
147
+		if (isset($_GET["attachment"])) $attachment = $_GET["attachment"];
148 148
 		//$attachment = false;
149
-		$contenttype='text/calendar';
150
-		if (isset($_GET["contenttype"])) $contenttype=$_GET["contenttype"];
149
+		$contenttype = 'text/calendar';
150
+		if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"];
151 151
 		//$contenttype='text/plain';
152
-		$outputencoding='UTF-8';
152
+		$outputencoding = 'UTF-8';
153 153
 
154
-		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
154
+		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : ''));
155 155
 		if ($attachment) 		header('Content-Disposition: attachment; filename="'.$shortfilename.'"');
156 156
 
157 157
 		if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
158 158
 		else header('Cache-Control: private, must-revalidate');
159 159
 
160 160
 		// Clean parameters
161
-		$outputfile=$conf->agenda->dir_temp.'/'.$filename;
162
-		$result=readfile($outputfile);
163
-		if (! $result) print 'File '.$outputfile.' was empty.';
161
+		$outputfile = $conf->agenda->dir_temp.'/'.$filename;
162
+		$result = readfile($outputfile);
163
+		if (!$result) print 'File '.$outputfile.' was empty.';
164 164
 
165 165
 	    //header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
166 166
 		exit;
@@ -175,18 +175,18 @@  discard block
 block discarded – undo
175 175
 
176 176
 if ($format == 'rss')
177 177
 {
178
-	$result=$agenda->build_exportfile($format,$type,$cachedelay,$filename,$filters);
178
+	$result = $agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters);
179 179
 	if ($result >= 0)
180 180
 	{
181 181
 		$attachment = false;
182
-		if (isset($_GET["attachment"])) $attachment=$_GET["attachment"];
182
+		if (isset($_GET["attachment"])) $attachment = $_GET["attachment"];
183 183
 		//$attachment = false;
184
-		$contenttype='application/rss+xml';
185
-		if (isset($_GET["contenttype"])) $contenttype=$_GET["contenttype"];
184
+		$contenttype = 'application/rss+xml';
185
+		if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"];
186 186
 		//$contenttype='text/plain';
187
-		$outputencoding='UTF-8';
187
+		$outputencoding = 'UTF-8';
188 188
 
189
-		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
189
+		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : ''));
190 190
 		if ($attachment) 		header('Content-Disposition: attachment; filename="'.$filename.'"');
191 191
 
192 192
 		// Ajout directives pour resoudre bug IE
@@ -196,9 +196,9 @@  discard block
 block discarded – undo
196 196
 		else header('Cache-Control: private, must-revalidate');
197 197
 
198 198
 		// Clean parameters
199
-		$outputfile=$conf->agenda->dir_temp.'/'.$filename;
200
-		$result=readfile($outputfile);
201
-		if (! $result) print 'File '.$outputfile.' was empty.';
199
+		$outputfile = $conf->agenda->dir_temp.'/'.$filename;
200
+		$result = readfile($outputfile);
201
+		if (!$result) print 'File '.$outputfile.' was empty.';
202 202
 
203 203
 	//	header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
204 204
 		exit;
Please login to merge, or discard this patch.
Braces   +121 added lines, -43 removed lines patch added patch discarded remove patch
@@ -32,10 +32,20 @@  discard block
 block discarded – undo
32 32
 //if (! defined('NOREQUIREDB'))    define('NOREQUIREDB','1');
33 33
 //if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
34 34
 //if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
35
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
36
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1'); // If there is no menu to show
37
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
38
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
35
+if (! defined('NOTOKENRENEWAL')) {
36
+	define('NOTOKENRENEWAL','1');
37
+}
38
+if (! defined('NOREQUIREMENU')) {
39
+	define('NOREQUIREMENU','1');
40
+}
41
+// If there is no menu to show
42
+if (! defined('NOREQUIREHTML')) {
43
+	define('NOREQUIREHTML','1');
44
+}
45
+// If we don't need to load the html.form.class.php
46
+if (! defined('NOREQUIREAJAX')) {
47
+	define('NOREQUIREAJAX','1');
48
+}
39 49
 define("NOLOGIN",1);		// This means this output page does not require to be logged.
40 50
 define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
41 51
 
@@ -57,27 +67,53 @@  discard block
 block discarded – undo
57 67
 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
58 68
 
59 69
 // Security check
60
-if (empty($conf->agenda->enabled)) accessforbidden('',0,0,1);
70
+if (empty($conf->agenda->enabled)) {
71
+	accessforbidden('',0,0,1);
72
+}
61 73
 
62 74
 // Not older than
63
-if (! isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY=100;	// default limit
75
+if (! isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) {
76
+	$conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY=100;
77
+}
78
+// default limit
64 79
 
65 80
 // Define format, type and filter
66 81
 $format='ical';
67 82
 $type='event';
68
-if (GETPOST("format",'alpha')) $format=GETPOST("format",'apha');
69
-if (GETPOST("type",'apha'))   $type=GETPOST("type",'alpha');
83
+if (GETPOST("format",'alpha')) {
84
+	$format=GETPOST("format",'apha');
85
+}
86
+if (GETPOST("type",'apha')) {
87
+	$type=GETPOST("type",'alpha');
88
+}
70 89
 
71 90
 $filters=array();
72
-if (GETPOST("year",'int')) 	        $filters['year']=GETPOST("year",'int');
73
-if (GETPOST("id",'int'))            $filters['id']=GETPOST("id",'int');
74
-if (GETPOST("idfrom",'int'))        $filters['idfrom']=GETPOST("idfrom",'int');
75
-if (GETPOST("idto",'int'))          $filters['idto']=GETPOST("idto",'int');
76
-if (GETPOST("project",'apha'))      $filters['project']=GETPOST("project",'apha');
77
-if (GETPOST("logina",'apha'))       $filters['logina']=GETPOST("logina",'apha');
78
-if (GETPOST("logint",'apha'))       $filters['logint']=GETPOST("logint",'apha');
79
-if (GETPOST("notolderthan",'int'))  $filters['notolderthan']=GETPOST("notolderthan","int");
80
-else $filters['notolderthan']=$conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY;
91
+if (GETPOST("year",'int')) {
92
+	$filters['year']=GETPOST("year",'int');
93
+}
94
+if (GETPOST("id",'int')) {
95
+	$filters['id']=GETPOST("id",'int');
96
+}
97
+if (GETPOST("idfrom",'int')) {
98
+	$filters['idfrom']=GETPOST("idfrom",'int');
99
+}
100
+if (GETPOST("idto",'int')) {
101
+	$filters['idto']=GETPOST("idto",'int');
102
+}
103
+if (GETPOST("project",'apha')) {
104
+	$filters['project']=GETPOST("project",'apha');
105
+}
106
+if (GETPOST("logina",'apha')) {
107
+	$filters['logina']=GETPOST("logina",'apha');
108
+}
109
+if (GETPOST("logint",'apha')) {
110
+	$filters['logint']=GETPOST("logint",'apha');
111
+}
112
+if (GETPOST("notolderthan",'int')) {
113
+	$filters['notolderthan']=GETPOST("notolderthan","int");
114
+} else {
115
+	$filters['notolderthan']=$conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY;
116
+}
81 117
 
82 118
 // Check config
83 119
 if (empty($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY))
@@ -109,13 +145,29 @@  discard block
 block discarded – undo
109 145
 foreach ($filters as $key => $value)
110 146
 {
111 147
     //if ($key == 'notolderthan')    $filename.='-notolderthan'.$value; This filter key is already added before and does not need to be in filename
112
-	if ($key == 'year')            $filename.='-year'.$value;
113
-    if ($key == 'id')              $filename.='-id'.$value;
114
-    if ($key == 'idfrom')          $filename.='-idfrom'.$value;
115
-    if ($key == 'idto')            $filename.='-idto'.$value;
116
-    if ($key == 'project')         $filename.='-project'.$value;
117
-	if ($key == 'logina')	       $filename.='-logina'.$value;	// Author
118
-	if ($key == 'logint')	       $filename.='-logint'.$value;	// Assigned to
148
+	if ($key == 'year') {
149
+		$filename.='-year'.$value;
150
+	}
151
+    if ($key == 'id') {
152
+    	$filename.='-id'.$value;
153
+    }
154
+    if ($key == 'idfrom') {
155
+    	$filename.='-idfrom'.$value;
156
+    }
157
+    if ($key == 'idto') {
158
+    	$filename.='-idto'.$value;
159
+    }
160
+    if ($key == 'project') {
161
+    	$filename.='-project'.$value;
162
+    }
163
+	if ($key == 'logina') {
164
+		$filename.='-logina'.$value;
165
+	}
166
+	// Author
167
+	if ($key == 'logint') {
168
+		$filename.='-logint'.$value;
169
+	}
170
+	// Assigned to
119 171
 }
120 172
 // Add extension
121 173
 if ($format == 'vcal') { $shortfilename.='.vcs'; $filename.='.vcs'; }
@@ -135,7 +187,9 @@  discard block
 block discarded – undo
135 187
 $agenda=new ActionComm($db);
136 188
 
137 189
 $cachedelay=0;
138
-if (! empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) $cachedelay=$conf->global->MAIN_AGENDA_EXPORT_CACHE;
190
+if (! empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) {
191
+	$cachedelay=$conf->global->MAIN_AGENDA_EXPORT_CACHE;
192
+}
139 193
 
140 194
 // Build file
141 195
 if ($format == 'ical' || $format == 'vcal')
@@ -144,28 +198,40 @@  discard block
 block discarded – undo
144 198
 	if ($result >= 0)
145 199
 	{
146 200
 		$attachment = true;
147
-		if (isset($_GET["attachment"])) $attachment=$_GET["attachment"];
201
+		if (isset($_GET["attachment"])) {
202
+			$attachment=$_GET["attachment"];
203
+		}
148 204
 		//$attachment = false;
149 205
 		$contenttype='text/calendar';
150
-		if (isset($_GET["contenttype"])) $contenttype=$_GET["contenttype"];
206
+		if (isset($_GET["contenttype"])) {
207
+			$contenttype=$_GET["contenttype"];
208
+		}
151 209
 		//$contenttype='text/plain';
152 210
 		$outputencoding='UTF-8';
153 211
 
154
-		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
155
-		if ($attachment) 		header('Content-Disposition: attachment; filename="'.$shortfilename.'"');
212
+		if ($contenttype) {
213
+			header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
214
+		}
215
+		if ($attachment) {
216
+			header('Content-Disposition: attachment; filename="'.$shortfilename.'"');
217
+		}
156 218
 
157
-		if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
158
-		else header('Cache-Control: private, must-revalidate');
219
+		if ($cachedelay) {
220
+			header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
221
+		} else {
222
+			header('Cache-Control: private, must-revalidate');
223
+		}
159 224
 
160 225
 		// Clean parameters
161 226
 		$outputfile=$conf->agenda->dir_temp.'/'.$filename;
162 227
 		$result=readfile($outputfile);
163
-		if (! $result) print 'File '.$outputfile.' was empty.';
228
+		if (! $result) {
229
+			print 'File '.$outputfile.' was empty.';
230
+		}
164 231
 
165 232
 	    //header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
166 233
 		exit;
167
-	}
168
-	else
234
+	} else
169 235
 	{
170 236
 		print 'Error '.$agenda->error;
171 237
 
@@ -179,31 +245,43 @@  discard block
 block discarded – undo
179 245
 	if ($result >= 0)
180 246
 	{
181 247
 		$attachment = false;
182
-		if (isset($_GET["attachment"])) $attachment=$_GET["attachment"];
248
+		if (isset($_GET["attachment"])) {
249
+			$attachment=$_GET["attachment"];
250
+		}
183 251
 		//$attachment = false;
184 252
 		$contenttype='application/rss+xml';
185
-		if (isset($_GET["contenttype"])) $contenttype=$_GET["contenttype"];
253
+		if (isset($_GET["contenttype"])) {
254
+			$contenttype=$_GET["contenttype"];
255
+		}
186 256
 		//$contenttype='text/plain';
187 257
 		$outputencoding='UTF-8';
188 258
 
189
-		if ($contenttype)       header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
190
-		if ($attachment) 		header('Content-Disposition: attachment; filename="'.$filename.'"');
259
+		if ($contenttype) {
260
+			header('Content-Type: '.$contenttype.($outputencoding?'; charset='.$outputencoding:''));
261
+		}
262
+		if ($attachment) {
263
+			header('Content-Disposition: attachment; filename="'.$filename.'"');
264
+		}
191 265
 
192 266
 		// Ajout directives pour resoudre bug IE
193 267
 		//header('Cache-Control: Public, must-revalidate');
194 268
 		//header('Pragma: public');
195
-		if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
196
-		else header('Cache-Control: private, must-revalidate');
269
+		if ($cachedelay) {
270
+			header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
271
+		} else {
272
+			header('Cache-Control: private, must-revalidate');
273
+		}
197 274
 
198 275
 		// Clean parameters
199 276
 		$outputfile=$conf->agenda->dir_temp.'/'.$filename;
200 277
 		$result=readfile($outputfile);
201
-		if (! $result) print 'File '.$outputfile.' was empty.';
278
+		if (! $result) {
279
+			print 'File '.$outputfile.' was empty.';
280
+		}
202 281
 
203 282
 	//	header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
204 283
 		exit;
205
-	}
206
-	else
284
+	} else
207 285
 	{
208 286
 		print 'Error '.$agenda->error;
209 287
 
Please login to merge, or discard this patch.
htdocs/public/onlinesign/newonlinesign.php 3 patches
Braces   +84 added lines, -49 removed lines patch added patch discarded remove patch
@@ -33,7 +33,9 @@  discard block
 block discarded – undo
33 33
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
34 34
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
35 35
 $entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
36
-if (is_numeric($entity)) define("DOLENTITY", $entity);
36
+if (is_numeric($entity)) {
37
+	define("DOLENTITY", $entity);
38
+}
37 39
 
38 40
 require '../../main.inc.php';
39 41
 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
@@ -133,7 +135,9 @@  discard block
 block discarded – undo
133 135
  */
134 136
 
135 137
 $head='';
136
-if (! empty($conf->global->MAIN_SIGN_CSS_URL)) $head='<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
138
+if (! empty($conf->global->MAIN_SIGN_CSS_URL)) {
139
+	$head='<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
140
+}
137 141
 
138 142
 $conf->dol_hide_topmenu=1;
139 143
 $conf->dol_hide_leftmenu=1;
@@ -170,16 +174,18 @@  discard block
 block discarded – undo
170 174
 $logosmall=$mysoc->logo_small;
171 175
 $logo=$mysoc->logo;
172 176
 $paramlogo='ONLINE_SIGN_LOGO_'.$suffix;
173
-if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo;
174
-else if (! empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall=$conf->global->ONLINE_SIGN_LOGO;
177
+if (! empty($conf->global->$paramlogo)) {
178
+	$logosmall=$conf->global->$paramlogo;
179
+} else if (! empty($conf->global->ONLINE_SIGN_LOGO)) {
180
+	$logosmall=$conf->global->ONLINE_SIGN_LOGO;
181
+}
175 182
 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
176 183
 // Define urllogo
177 184
 $urllogo='';
178 185
 if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall))
179 186
 {
180 187
 	$urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('thumbs/'.$logosmall);
181
-}
182
-elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo))
188
+} elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo))
183 189
 {
184 190
 	$urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode($logo);
185 191
 	$width=96;
@@ -189,7 +195,9 @@  discard block
 block discarded – undo
189 195
 {
190 196
 	print '<tr>';
191 197
 	print '<td align="center"><img id="dolpaymentlogo" title="'.$title.'" src="'.$urllogo.'"';
192
-	if ($width) print ' width="'.$width.'"';
198
+	if ($width) {
199
+		print ' width="'.$width.'"';
200
+	}
193 201
 	print '></td>';
194 202
 	print '</tr>'."\n";
195 203
 }
@@ -199,8 +207,11 @@  discard block
 block discarded – undo
199 207
 if (! empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
200 208
 {
201 209
     $langs->load("members");
202
-    if (preg_match('/^\((.*)\)$/',$conf->global->ONLINE_SIGN_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n";
203
-    else $text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
210
+    if (preg_match('/^\((.*)\)$/',$conf->global->ONLINE_SIGN_NEWFORM_TEXT,$reg)) {
211
+    	$text.=$langs->trans($reg[1])."<br>\n";
212
+    } else {
213
+    	$text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
214
+    }
204 215
     $text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
205 216
 }
206 217
 if (empty($text))
@@ -254,8 +265,7 @@  discard block
 block discarded – undo
254 265
 	{
255 266
 		$mesg=$order->error;
256 267
 		$error++;
257
-	}
258
-	else
268
+	} else
259 269
 	{
260 270
 		$result=$order->fetch_thirdparty($order->socid);
261 271
 	}
@@ -299,16 +309,19 @@  discard block
 block discarded – undo
299 309
 	{
300 310
 		$mesg=$invoice->error;
301 311
 		$error++;
302
-	}
303
-	else
312
+	} else
304 313
 	{
305 314
 		$result=$invoice->fetch_thirdparty($invoice->socid);
306 315
 	}
307 316
 
308
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
317
+    if ($action != 'dosign') {
318
+    	// Do not change amount if we just click on first dosign
309 319
     {
310 320
     	$amount=price2num($invoice->total_ttc - $invoice->getSommePaiement());
311
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
321
+    }
322
+        if (GETPOST("amount",'int')) {
323
+        	$amount=GETPOST("amount",'int');
324
+        }
312 325
         $amount=price2num($amount);
313 326
     }
314 327
 
@@ -349,8 +362,7 @@  discard block
 block discarded – undo
349 362
 	{
350 363
 		$mesg=$contractline->error;
351 364
 		$error++;
352
-	}
353
-	else
365
+	} else
354 366
 	{
355 367
 		if ($contractline->fk_contrat > 0)
356 368
 		{
@@ -359,23 +371,23 @@  discard block
 block discarded – undo
359 371
 			if ($result > 0)
360 372
 			{
361 373
 				$result=$contract->fetch_thirdparty($contract->socid);
362
-			}
363
-			else
374
+			} else
364 375
 			{
365 376
 				$mesg=$contract->error;
366 377
 				$error++;
367 378
 			}
368
-		}
369
-		else
379
+		} else
370 380
 		{
371 381
 			$mesg='ErrorRecordNotFound';
372 382
 			$error++;
373 383
 		}
374 384
 	}
375 385
 
376
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
386
+    if ($action != 'dosign') {
387
+    	// Do not change amount if we just click on first dosign
377 388
     {
378 389
     	$amount=$contractline->total_ttc;
390
+    }
379 391
     	if ($contractline->fk_product)
380 392
     	{
381 393
     		$product=new Product($db);
@@ -387,8 +399,7 @@  discard block
 block discarded – undo
387 399
     			$pu_ht = $product->multiprices[$contract->thirdparty->price_level];
388 400
     			$pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level];
389 401
     			$price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level];
390
-    		}
391
-    		else
402
+    		} else
392 403
     		{
393 404
     			$pu_ht = $product->price;
394 405
     			$pu_ttc = $product->price_ttc;
@@ -402,12 +413,16 @@  discard block
 block discarded – undo
402 413
     			exit;
403 414
     		}
404 415
     	}
405
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
416
+        if (GETPOST("amount",'int')) {
417
+        	$amount=GETPOST("amount",'int');
418
+        }
406 419
         $amount=price2num($amount);
407 420
     }
408 421
 
409 422
 	$qty=1;
410
-	if (GETPOST('qty')) $qty=GETPOST('qty');
423
+	if (GETPOST('qty')) {
424
+		$qty=GETPOST('qty');
425
+	}
411 426
 
412 427
 	// Creditor
413 428
 
@@ -428,7 +443,9 @@  discard block
 block discarded – undo
428 443
 	{
429 444
 		$text.='<br>'.$product->ref.($product->label?' - '.$product->label:'');
430 445
 	}
431
-	if ($contractline->description) $text.='<br>'.dol_htmlentitiesbr($contractline->description);
446
+	if ($contractline->description) {
447
+		$text.='<br>'.dol_htmlentitiesbr($contractline->description);
448
+	}
432 449
 	//if ($contractline->date_fin_validite) {
433 450
 	//	$text.='<br>'.$langs->trans("DateEndPlanned").': ';
434 451
 	//	$text.=dol_print_date($contractline->date_fin_validite);
@@ -459,8 +476,7 @@  discard block
 block discarded – undo
459 476
 			if ($product->duration_value > 1)
460 477
 			{
461 478
 				$dur=array("h"=>$langs->trans("Hours"),"d"=>$langs->trans("DurationDays"),"w"=>$langs->trans("DurationWeeks"),"m"=>$langs->trans("DurationMonths"),"y"=>$langs->trans("DurationYears"));
462
-			}
463
-			else
479
+			} else
464 480
 			{
465 481
 				$dur=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("DurationDay"),"w"=>$langs->trans("DurationWeek"),"m"=>$langs->trans("DurationMonth"),"y"=>$langs->trans("DurationYear"));
466 482
 			}
@@ -475,14 +491,15 @@  discard block
 block discarded – undo
475 491
 	// Amount
476 492
 
477 493
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Amount");
478
-	if (empty($amount)) print ' ('.$langs->trans("ToComplete").')';
494
+	if (empty($amount)) {
495
+		print ' ('.$langs->trans("ToComplete").')';
496
+	}
479 497
 	print '</td><td class="CTableRow'.($var?'1':'2').'">';
480 498
 	if (empty($amount) || ! is_numeric($amount))
481 499
 	{
482 500
         print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
483 501
 	    print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">';
484
-	}
485
-	else {
502
+	} else {
486 503
 		print '<b>'.price($amount).'</b>';
487 504
         print '<input type="hidden" name="amount" value="'.$amount.'">';
488 505
 		print '<input type="hidden" name="newamount" value="'.$amount.'">';
@@ -509,16 +526,19 @@  discard block
 block discarded – undo
509 526
 	{
510 527
 		$mesg=$member->error;
511 528
 		$error++;
512
-	}
513
-	else
529
+	} else
514 530
 	{
515 531
 		$subscription=new Subscription($db);
516 532
 	}
517 533
 
518
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
534
+    if ($action != 'dosign') {
535
+    	// Do not change amount if we just click on first dosign
519 536
     {
520 537
     	$amount=$subscription->total_ttc;
521
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
538
+    }
539
+        if (GETPOST("amount",'int')) {
540
+        	$amount=GETPOST("amount",'int');
541
+        }
522 542
         $amount=price2num($amount);
523 543
     }
524 544
 
@@ -537,8 +557,11 @@  discard block
 block discarded – undo
537 557
 
538 558
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Member");
539 559
 	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>';
540
-	if ($member->morphy == 'mor' && ! empty($member->societe)) print $member->societe;
541
-	else print $member->getFullName($langs);
560
+	if ($member->morphy == 'mor' && ! empty($member->societe)) {
561
+		print $member->societe;
562
+	} else {
563
+		print $member->getFullName($langs);
564
+	}
542 565
 	print '</b>';
543 566
 
544 567
 	// Object
@@ -564,7 +587,9 @@  discard block
 block discarded – undo
564 587
 		print '</td><td class="CTableRow'.($var?'1':'2').'">'.price($member->last_subscription_amount);
565 588
 		print '</td></tr>'."\n";
566 589
 
567
-		if (empty($amount) && ! GETPOST('newamount')) $_GET['newamount']=$member->last_subscription_amount;
590
+		if (empty($amount) && ! GETPOST('newamount')) {
591
+			$_GET['newamount']=$member->last_subscription_amount;
592
+		}
568 593
 	}
569 594
 
570 595
 	// Amount
@@ -573,20 +598,25 @@  discard block
 block discarded – undo
573 598
 	if (empty($amount))
574 599
 	{
575 600
 		print ' ('.$langs->trans("ToComplete");
576
-		if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>';
601
+		if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) {
602
+			print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>';
603
+		}
577 604
 		print ')';
578 605
 	}
579 606
 	print '</td><td class="CTableRow'.($var?'1':'2').'">';
580 607
 	if (empty($amount) || ! is_numeric($amount))
581 608
 	{
582 609
 	    $valtoshow=GETPOST("newamount",'int');
583
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
610
+	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) {
611
+	    	$valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
612
+	    }
584 613
         print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
585 614
 	    print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">';
586
-	}
587
-	else {
615
+	} else {
588 616
 	    $valtoshow=$amount;
589
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
617
+	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) {
618
+	    	$valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
619
+	    }
590 620
 	    print '<b>'.price($valtoshow).'</b>';
591 621
         print '<input type="hidden" name="amount" value="'.$valtoshow.'">';
592 622
 		print '<input type="hidden" name="newamount" value="'.$valtoshow.'">';
@@ -601,16 +631,21 @@  discard block
 block discarded – undo
601 631
 
602 632
 
603 633
 
604
-if (! $found && ! $mesg) $mesg=$langs->trans("ErrorBadParameters");
634
+if (! $found && ! $mesg) {
635
+	$mesg=$langs->trans("ErrorBadParameters");
636
+}
605 637
 
606
-if ($mesg) print '<tr><td align="center" colspan="2"><br><div class="warning">'.$mesg.'</div></td></tr>'."\n";
638
+if ($mesg) {
639
+	print '<tr><td align="center" colspan="2"><br><div class="warning">'.$mesg.'</div></td></tr>'."\n";
640
+}
607 641
 
608 642
 print '</table>'."\n";
609 643
 print "\n";
610 644
 
611 645
 if ($action != 'dosign')
612 646
 {
613
-    if ($found && ! $error)	// We are in a management option and no error
647
+    if ($found && ! $error) {
648
+    	// We are in a management option and no error
614 649
     {
615 650
 
616 651
 
@@ -619,8 +654,8 @@  discard block
 block discarded – undo
619 654
     {
620 655
     	dol_print_error_email('ERRORNEWONLINESIGNPAYPAL');
621 656
     }
622
-}
623
-else
657
+    }
658
+} else
624 659
 {
625 660
     // Print
626 661
 }
Please login to merge, or discard this patch.
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -67,11 +67,11 @@  discard block
 block discarded – undo
67 67
 
68 68
 if (! $action)
69 69
 {
70
-    if ($source && ! $ref)
71
-    {
72
-    	dol_print_error('',$langs->trans('ErrorBadParameters')." - ref");
73
-    	exit;
74
-    }
70
+	if ($source && ! $ref)
71
+	{
72
+		dol_print_error('',$langs->trans('ErrorBadParameters')." - ref");
73
+		exit;
74
+	}
75 75
 }
76 76
 
77 77
 
@@ -92,18 +92,18 @@  discard block
 block discarded – undo
92 92
 
93 93
 if (! empty($SOURCE))
94 94
 {
95
-    $urlok.='source='.urlencode($SOURCE).'&';
96
-    $urlko.='source='.urlencode($SOURCE).'&';
95
+	$urlok.='source='.urlencode($SOURCE).'&';
96
+	$urlko.='source='.urlencode($SOURCE).'&';
97 97
 }
98 98
 if (! empty($REF))
99 99
 {
100
-    $urlok.='ref='.urlencode($REF).'&';
101
-    $urlko.='ref='.urlencode($REF).'&';
100
+	$urlok.='ref='.urlencode($REF).'&';
101
+	$urlko.='ref='.urlencode($REF).'&';
102 102
 }
103 103
 if (! empty($SECUREKEY))
104 104
 {
105
-    $urlok.='securekey='.urlencode($SECUREKEY).'&';
106
-    $urlko.='securekey='.urlencode($SECUREKEY).'&';
105
+	$urlok.='securekey='.urlencode($SECUREKEY).'&';
106
+	$urlko.='securekey='.urlencode($SECUREKEY).'&';
107 107
 }
108 108
 if (! empty($entity))
109 109
 {
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 
124 124
 if ($action == 'dosign')
125 125
 {
126
-    // TODO
126
+	// TODO
127 127
 
128 128
 }
129 129
 
@@ -143,11 +143,11 @@  discard block
 block discarded – undo
143 143
 // Check link validity
144 144
 if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', '')))
145 145
 {
146
-    $langs->load("errors");
147
-    dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $SOURCE, $ref));
148
-    llxFooter();
149
-    $db->close();
150
-    exit;
146
+	$langs->load("errors");
147
+	dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $SOURCE, $ref));
148
+	llxFooter();
149
+	$db->close();
150
+	exit;
151 151
 }
152 152
 
153 153
 print '<span id="dolpaymentspan"></span>'."\n";
@@ -198,15 +198,15 @@  discard block
 block discarded – undo
198 198
 $text='';
199 199
 if (! empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
200 200
 {
201
-    $langs->load("members");
202
-    if (preg_match('/^\((.*)\)$/',$conf->global->ONLINE_SIGN_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n";
203
-    else $text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
204
-    $text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
201
+	$langs->load("members");
202
+	if (preg_match('/^\((.*)\)$/',$conf->global->ONLINE_SIGN_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n";
203
+	else $text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
204
+	$text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
205 205
 }
206 206
 if (empty($text))
207 207
 {
208
-    $text.='<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage").'</strong></td></tr>'."\n";
209
-    $text.='<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom",$creditor).'<br><br></td></tr>'."\n";
208
+	$text.='<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage").'</strong></td></tr>'."\n";
209
+	$text.='<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom",$creditor).'<br><br></td></tr>'."\n";
210 210
 }
211 211
 print $text;
212 212
 
@@ -229,14 +229,14 @@  discard block
 block discarded – undo
229 229
 	// Creditor
230 230
 
231 231
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
232
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
233
-    print '<input type="hidden" name="creditor" value="'.$creditor.'">';
234
-    print '</td></tr>'."\n";
232
+	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
233
+	print '<input type="hidden" name="creditor" value="'.$creditor.'">';
234
+	print '</td></tr>'."\n";
235 235
 
236 236
 
237 237
 
238
-    // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum
239
-    // as they don't exists (buyer is unknown, tag is free).
238
+	// We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum
239
+	// as they don't exists (buyer is unknown, tag is free).
240 240
 }
241 241
 
242 242
 
@@ -263,9 +263,9 @@  discard block
 block discarded – undo
263 263
 	// Creditor
264 264
 
265 265
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
266
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
267
-    print '<input type="hidden" name="creditor" value="'.$creditor.'">';
268
-    print '</td></tr>'."\n";
266
+	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
267
+	print '<input type="hidden" name="creditor" value="'.$creditor.'">';
268
+	print '</td></tr>'."\n";
269 269
 
270 270
 	// Debitor
271 271
 
@@ -305,19 +305,19 @@  discard block
 block discarded – undo
305 305
 		$result=$invoice->fetch_thirdparty($invoice->socid);
306 306
 	}
307 307
 
308
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
309
-    {
310
-    	$amount=price2num($invoice->total_ttc - $invoice->getSommePaiement());
311
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
312
-        $amount=price2num($amount);
313
-    }
308
+	if ($action != 'dosign') // Do not change amount if we just click on first dosign
309
+	{
310
+		$amount=price2num($invoice->total_ttc - $invoice->getSommePaiement());
311
+		if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
312
+		$amount=price2num($amount);
313
+	}
314 314
 
315 315
 	// Creditor
316 316
 
317 317
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
318
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
319
-    print '<input type="hidden" name="creditor" value="'.$creditor.'">';
320
-    print '</td></tr>'."\n";
318
+	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
319
+	print '<input type="hidden" name="creditor" value="'.$creditor.'">';
320
+	print '</td></tr>'."\n";
321 321
 
322 322
 	// Debitor
323 323
 
@@ -373,38 +373,38 @@  discard block
 block discarded – undo
373 373
 		}
374 374
 	}
375 375
 
376
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
377
-    {
378
-    	$amount=$contractline->total_ttc;
379
-    	if ($contractline->fk_product)
380
-    	{
381
-    		$product=new Product($db);
382
-    		$result=$product->fetch($contractline->fk_product);
383
-
384
-    		// We define price for product (TODO Put this in a method in product class)
385
-    		if (! empty($conf->global->PRODUIT_MULTIPRICES))
386
-    		{
387
-    			$pu_ht = $product->multiprices[$contract->thirdparty->price_level];
388
-    			$pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level];
389
-    			$price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level];
390
-    		}
391
-    		else
392
-    		{
393
-    			$pu_ht = $product->price;
394
-    			$pu_ttc = $product->price_ttc;
395
-    			$price_base_type = $product->price_base_type;
396
-    		}
397
-
398
-    		$amount=$pu_ttc;
399
-    		if (empty($amount))
400
-    		{
401
-    			dol_print_error('','ErrorNoPriceDefinedForThisProduct');
402
-    			exit;
403
-    		}
404
-    	}
405
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
406
-        $amount=price2num($amount);
407
-    }
376
+	if ($action != 'dosign') // Do not change amount if we just click on first dosign
377
+	{
378
+		$amount=$contractline->total_ttc;
379
+		if ($contractline->fk_product)
380
+		{
381
+			$product=new Product($db);
382
+			$result=$product->fetch($contractline->fk_product);
383
+
384
+			// We define price for product (TODO Put this in a method in product class)
385
+			if (! empty($conf->global->PRODUIT_MULTIPRICES))
386
+			{
387
+				$pu_ht = $product->multiprices[$contract->thirdparty->price_level];
388
+				$pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level];
389
+				$price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level];
390
+			}
391
+			else
392
+			{
393
+				$pu_ht = $product->price;
394
+				$pu_ttc = $product->price_ttc;
395
+				$price_base_type = $product->price_base_type;
396
+			}
397
+
398
+			$amount=$pu_ttc;
399
+			if (empty($amount))
400
+			{
401
+				dol_print_error('','ErrorNoPriceDefinedForThisProduct');
402
+				exit;
403
+			}
404
+		}
405
+		if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
406
+		$amount=price2num($amount);
407
+	}
408 408
 
409 409
 	$qty=1;
410 410
 	if (GETPOST('qty')) $qty=GETPOST('qty');
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 
414 414
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
415 415
 	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
416
-    print '<input type="hidden" name="creditor" value="'.$creditor.'">';
416
+	print '<input type="hidden" name="creditor" value="'.$creditor.'">';
417 417
 	print '</td></tr>'."\n";
418 418
 
419 419
 	// Debitor
@@ -479,12 +479,12 @@  discard block
 block discarded – undo
479 479
 	print '</td><td class="CTableRow'.($var?'1':'2').'">';
480 480
 	if (empty($amount) || ! is_numeric($amount))
481 481
 	{
482
-        print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
483
-	    print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">';
482
+		print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
483
+		print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">';
484 484
 	}
485 485
 	else {
486 486
 		print '<b>'.price($amount).'</b>';
487
-        print '<input type="hidden" name="amount" value="'.$amount.'">';
487
+		print '<input type="hidden" name="amount" value="'.$amount.'">';
488 488
 		print '<input type="hidden" name="newamount" value="'.$amount.'">';
489 489
 	}
490 490
 	// Currency
@@ -515,12 +515,12 @@  discard block
 block discarded – undo
515 515
 		$subscription=new Subscription($db);
516 516
 	}
517 517
 
518
-    if ($action != 'dosign') // Do not change amount if we just click on first dosign
519
-    {
520
-    	$amount=$subscription->total_ttc;
521
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
522
-        $amount=price2num($amount);
523
-    }
518
+	if ($action != 'dosign') // Do not change amount if we just click on first dosign
519
+	{
520
+		$amount=$subscription->total_ttc;
521
+		if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
522
+		$amount=price2num($amount);
523
+	}
524 524
 
525 525
 	$fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M');
526 526
 	if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; }
@@ -529,9 +529,9 @@  discard block
 block discarded – undo
529 529
 	// Creditor
530 530
 
531 531
 	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
532
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
533
-    print '<input type="hidden" name="creditor" value="'.$creditor.'">';
534
-    print '</td></tr>'."\n";
532
+	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
533
+	print '<input type="hidden" name="creditor" value="'.$creditor.'">';
534
+	print '</td></tr>'."\n";
535 535
 
536 536
 	// Debitor
537 537
 
@@ -579,16 +579,16 @@  discard block
 block discarded – undo
579 579
 	print '</td><td class="CTableRow'.($var?'1':'2').'">';
580 580
 	if (empty($amount) || ! is_numeric($amount))
581 581
 	{
582
-	    $valtoshow=GETPOST("newamount",'int');
583
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
584
-        print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
585
-	    print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">';
582
+		$valtoshow=GETPOST("newamount",'int');
583
+		if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
584
+		print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
585
+		print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">';
586 586
 	}
587 587
 	else {
588
-	    $valtoshow=$amount;
589
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
590
-	    print '<b>'.price($valtoshow).'</b>';
591
-        print '<input type="hidden" name="amount" value="'.$valtoshow.'">';
588
+		$valtoshow=$amount;
589
+		if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
590
+		print '<b>'.price($valtoshow).'</b>';
591
+		print '<input type="hidden" name="amount" value="'.$valtoshow.'">';
592 592
 		print '<input type="hidden" name="newamount" value="'.$valtoshow.'">';
593 593
 	}
594 594
 	// Currency
@@ -610,19 +610,19 @@  discard block
 block discarded – undo
610 610
 
611 611
 if ($action != 'dosign')
612 612
 {
613
-    if ($found && ! $error)	// We are in a management option and no error
614
-    {
613
+	if ($found && ! $error)	// We are in a management option and no error
614
+	{
615 615
 
616 616
 
617
-    }
618
-    else
619
-    {
620
-    	dol_print_error_email('ERRORNEWONLINESIGNPAYPAL');
621
-    }
617
+	}
618
+	else
619
+	{
620
+		dol_print_error_email('ERRORNEWONLINESIGNPAYPAL');
621
+	}
622 622
 }
623 623
 else
624 624
 {
625
-    // Print
625
+	// Print
626 626
 }
627 627
 
628 628
 print '</td></tr>'."\n";
Please login to merge, or discard this patch.
Spacing   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -26,13 +26,13 @@  discard block
 block discarded – undo
26 26
  *		\brief      File to offer a way to make an online signature for a particular Dolibarr entity
27 27
  */
28 28
 
29
-define("NOLOGIN",1);		// This means this output page does not require to be logged.
30
-define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
29
+define("NOLOGIN", 1); // This means this output page does not require to be logged.
30
+define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
31 31
 
32 32
 // For MultiCompany module.
33 33
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
34 34
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
35
-$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
35
+$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
36 36
 if (is_numeric($entity)) define("DOLENTITY", $entity);
37 37
 
38 38
 require '../../main.inc.php';
@@ -50,9 +50,9 @@  discard block
 block discarded – undo
50 50
 $langs->load("bills");
51 51
 $langs->load("companies");
52 52
 $langs->load("errors");
53
-$langs->load("paybox");     // File with generic data
53
+$langs->load("paybox"); // File with generic data
54 54
 
55
-$action=GETPOST('action','alpha');
55
+$action = GETPOST('action', 'alpha');
56 56
 
57 57
 // Input are:
58 58
 // type ('invoice','order','contractline'),
@@ -61,22 +61,22 @@  discard block
 block discarded – undo
61 61
 // tag (a free text, required if type is empty)
62 62
 // currency (iso code)
63 63
 
64
-$suffix=GETPOST("suffix",'alpha');
65
-$SOURCE=GETPOST("source",'alpha');
66
-$ref=$REF=GETPOST("ref",'alpha');
64
+$suffix = GETPOST("suffix", 'alpha');
65
+$SOURCE = GETPOST("source", 'alpha');
66
+$ref = $REF = GETPOST("ref", 'alpha');
67 67
 
68
-if (! $action)
68
+if (!$action)
69 69
 {
70
-    if ($source && ! $ref)
70
+    if ($source && !$ref)
71 71
     {
72
-    	dol_print_error('',$langs->trans('ErrorBadParameters')." - ref");
72
+    	dol_print_error('', $langs->trans('ErrorBadParameters')." - ref");
73 73
     	exit;
74 74
     }
75 75
 }
76 76
 
77 77
 
78
-$paymentmethod='';
79
-$validpaymentmethod=array();
78
+$paymentmethod = '';
79
+$validpaymentmethod = array();
80 80
 
81 81
 
82 82
 
@@ -84,34 +84,34 @@  discard block
 block discarded – undo
84 84
 // Define $urlwithroot
85 85
 //$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
86 86
 //$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
87
-$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current. For Paypal payment, we can use internal URL like localhost.
87
+$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current. For Paypal payment, we can use internal URL like localhost.
88 88
 
89 89
 
90 90
 // Complete urls for post treatment
91
-$SECUREKEY=GETPOST("securekey");	        // Secure key
91
+$SECUREKEY = GETPOST("securekey"); // Secure key
92 92
 
93
-if (! empty($SOURCE))
93
+if (!empty($SOURCE))
94 94
 {
95
-    $urlok.='source='.urlencode($SOURCE).'&';
96
-    $urlko.='source='.urlencode($SOURCE).'&';
95
+    $urlok .= 'source='.urlencode($SOURCE).'&';
96
+    $urlko .= 'source='.urlencode($SOURCE).'&';
97 97
 }
98
-if (! empty($REF))
98
+if (!empty($REF))
99 99
 {
100
-    $urlok.='ref='.urlencode($REF).'&';
101
-    $urlko.='ref='.urlencode($REF).'&';
100
+    $urlok .= 'ref='.urlencode($REF).'&';
101
+    $urlko .= 'ref='.urlencode($REF).'&';
102 102
 }
103
-if (! empty($SECUREKEY))
103
+if (!empty($SECUREKEY))
104 104
 {
105
-    $urlok.='securekey='.urlencode($SECUREKEY).'&';
106
-    $urlko.='securekey='.urlencode($SECUREKEY).'&';
105
+    $urlok .= 'securekey='.urlencode($SECUREKEY).'&';
106
+    $urlko .= 'securekey='.urlencode($SECUREKEY).'&';
107 107
 }
108
-if (! empty($entity))
108
+if (!empty($entity))
109 109
 {
110
-	$urlok.='entity='.urlencode($entity).'&';
111
-	$urlko.='entity='.urlencode($entity).'&';
110
+	$urlok .= 'entity='.urlencode($entity).'&';
111
+	$urlko .= 'entity='.urlencode($entity).'&';
112 112
 }
113
-$urlok=preg_replace('/&$/','',$urlok);  // Remove last &
114
-$urlko=preg_replace('/&$/','',$urlko);  // Remove last &
113
+$urlok = preg_replace('/&$/', '', $urlok); // Remove last &
114
+$urlko = preg_replace('/&$/', '', $urlko); // Remove last &
115 115
 
116 116
 
117 117
 
@@ -132,16 +132,16 @@  discard block
 block discarded – undo
132 132
  * View
133 133
  */
134 134
 
135
-$head='';
136
-if (! empty($conf->global->MAIN_SIGN_CSS_URL)) $head='<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
135
+$head = '';
136
+if (!empty($conf->global->MAIN_SIGN_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
137 137
 
138
-$conf->dol_hide_topmenu=1;
139
-$conf->dol_hide_leftmenu=1;
138
+$conf->dol_hide_topmenu = 1;
139
+$conf->dol_hide_leftmenu = 1;
140 140
 
141 141
 llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody');
142 142
 
143 143
 // Check link validity
144
-if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', '')))
144
+if (!empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', '')))
145 145
 {
146 146
     $langs->load("errors");
147 147
     dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $SOURCE, $ref));
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
 print '<form id="dolpaymentform" class="center" name="paymentform" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
156 156
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
157 157
 print '<input type="hidden" name="action" value="dosign">'."\n";
158
-print '<input type="hidden" name="tag" value="'.GETPOST("tag",'alpha').'">'."\n";
159
-print '<input type="hidden" name="suffix" value="'.GETPOST("suffix",'alpha').'">'."\n";
158
+print '<input type="hidden" name="tag" value="'.GETPOST("tag", 'alpha').'">'."\n";
159
+print '<input type="hidden" name="suffix" value="'.GETPOST("suffix", 'alpha').'">'."\n";
160 160
 print '<input type="hidden" name="securekey" value="'.$SECUREKEY.'">'."\n";
161 161
 print '<input type="hidden" name="entity" value="'.$entity.'" />';
162 162
 print "\n";
@@ -165,24 +165,24 @@  discard block
 block discarded – undo
165 165
 print '<table id="dolpaymenttable" summary="Payment form" class="center">'."\n";
166 166
 
167 167
 // Show logo (search order: logo defined by ONLINE_SIGN_LOGO_suffix, then ONLINE_SIGN_LOGO_, then small company logo, large company logo, theme logo, common logo)
168
-$width=0;
168
+$width = 0;
169 169
 // Define logo and logosmall
170
-$logosmall=$mysoc->logo_small;
171
-$logo=$mysoc->logo;
172
-$paramlogo='ONLINE_SIGN_LOGO_'.$suffix;
173
-if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo;
174
-else if (! empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall=$conf->global->ONLINE_SIGN_LOGO;
170
+$logosmall = $mysoc->logo_small;
171
+$logo = $mysoc->logo;
172
+$paramlogo = 'ONLINE_SIGN_LOGO_'.$suffix;
173
+if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo;
174
+else if (!empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall = $conf->global->ONLINE_SIGN_LOGO;
175 175
 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
176 176
 // Define urllogo
177
-$urllogo='';
178
-if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall))
177
+$urllogo = '';
178
+if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall))
179 179
 {
180
-	$urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('thumbs/'.$logosmall);
180
+	$urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('thumbs/'.$logosmall);
181 181
 }
182
-elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo))
182
+elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo))
183 183
 {
184
-	$urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode($logo);
185
-	$width=96;
184
+	$urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode($logo);
185
+	$width = 96;
186 186
 }
187 187
 // Output html code for logo
188 188
 if ($urllogo)
@@ -195,18 +195,18 @@  discard block
 block discarded – undo
195 195
 }
196 196
 
197 197
 // Output introduction text
198
-$text='';
199
-if (! empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
198
+$text = '';
199
+if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT))
200 200
 {
201 201
     $langs->load("members");
202
-    if (preg_match('/^\((.*)\)$/',$conf->global->ONLINE_SIGN_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n";
203
-    else $text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
204
-    $text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
202
+    if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n";
203
+    else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n";
204
+    $text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n";
205 205
 }
206 206
 if (empty($text))
207 207
 {
208
-    $text.='<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage").'</strong></td></tr>'."\n";
209
-    $text.='<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom",$creditor).'<br><br></td></tr>'."\n";
208
+    $text .= '<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage").'</strong></td></tr>'."\n";
209
+    $text .= '<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'<br><br></td></tr>'."\n";
210 210
 }
211 211
 print $text;
212 212
 
@@ -215,21 +215,21 @@  discard block
 block discarded – undo
215 215
 print '<table with="100%" id="tablepublicpayment">';
216 216
 print '<tr class="liste_total"><td align="left" colspan="2">'.$langs->trans("ThisIsInformationOnDocumentToSign").' :</td></tr>'."\n";
217 217
 
218
-$found=false;
219
-$error=0;
220
-$var=false;
218
+$found = false;
219
+$error = 0;
220
+$var = false;
221 221
 
222 222
 // Free payment
223
-if (! GETPOST("source"))
223
+if (!GETPOST("source"))
224 224
 {
225
-	$found=true;
226
-	$tag=GETPOST("tag");
227
-	$fulltag=$tag;
225
+	$found = true;
226
+	$tag = GETPOST("tag");
227
+	$fulltag = $tag;
228 228
 
229 229
 	// Creditor
230 230
 
231
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
232
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
231
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
232
+    print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
233 233
     print '<input type="hidden" name="creditor" value="'.$creditor.'">';
234 234
     print '</td></tr>'."\n";
235 235
 
@@ -243,41 +243,41 @@  discard block
 block discarded – undo
243 243
 // Payment on customer order
244 244
 if (GETPOST("source") == 'order')
245 245
 {
246
-	$found=true;
246
+	$found = true;
247 247
 	$langs->load("orders");
248 248
 
249 249
 	require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
250 250
 
251
-	$order=new Commande($db);
252
-	$result=$order->fetch('',$ref);
251
+	$order = new Commande($db);
252
+	$result = $order->fetch('', $ref);
253 253
 	if ($result < 0)
254 254
 	{
255
-		$mesg=$order->error;
255
+		$mesg = $order->error;
256 256
 		$error++;
257 257
 	}
258 258
 	else
259 259
 	{
260
-		$result=$order->fetch_thirdparty($order->socid);
260
+		$result = $order->fetch_thirdparty($order->socid);
261 261
 	}
262 262
 
263 263
 	// Creditor
264 264
 
265
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
266
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
265
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
266
+    print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
267 267
     print '<input type="hidden" name="creditor" value="'.$creditor.'">';
268 268
     print '</td></tr>'."\n";
269 269
 
270 270
 	// Debitor
271 271
 
272
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("ThirdParty");
273
-	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$order->thirdparty->name.'</b>';
272
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("ThirdParty");
273
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$order->thirdparty->name.'</b>';
274 274
 
275 275
 	// Object
276 276
 
277
-	$text='<b>'.$langs->trans("PaymentOrderRef",$order->ref).'</b>';
278
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Designation");
279
-	print '</td><td class="CTableRow'.($var?'1':'2').'">'.$text;
280
-	print '<input type="hidden" name="source" value="'.GETPOST("source",'alpha').'">';
277
+	$text = '<b>'.$langs->trans("PaymentOrderRef", $order->ref).'</b>';
278
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation");
279
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text;
280
+	print '<input type="hidden" name="source" value="'.GETPOST("source", 'alpha').'">';
281 281
 	print '<input type="hidden" name="ref" value="'.$order->ref.'">';
282 282
 	print '</td></tr>'."\n";
283 283
 
@@ -288,48 +288,48 @@  discard block
 block discarded – undo
288 288
 // Payment on customer invoice
289 289
 if (GETPOST("source") == 'invoice')
290 290
 {
291
-	$found=true;
291
+	$found = true;
292 292
 	$langs->load("bills");
293 293
 
294 294
 	require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
295 295
 
296
-	$invoice=new Facture($db);
297
-	$result=$invoice->fetch('',$ref);
296
+	$invoice = new Facture($db);
297
+	$result = $invoice->fetch('', $ref);
298 298
 	if ($result < 0)
299 299
 	{
300
-		$mesg=$invoice->error;
300
+		$mesg = $invoice->error;
301 301
 		$error++;
302 302
 	}
303 303
 	else
304 304
 	{
305
-		$result=$invoice->fetch_thirdparty($invoice->socid);
305
+		$result = $invoice->fetch_thirdparty($invoice->socid);
306 306
 	}
307 307
 
308 308
     if ($action != 'dosign') // Do not change amount if we just click on first dosign
309 309
     {
310
-    	$amount=price2num($invoice->total_ttc - $invoice->getSommePaiement());
311
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
312
-        $amount=price2num($amount);
310
+    	$amount = price2num($invoice->total_ttc - $invoice->getSommePaiement());
311
+        if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int');
312
+        $amount = price2num($amount);
313 313
     }
314 314
 
315 315
 	// Creditor
316 316
 
317
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
318
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
317
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
318
+    print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
319 319
     print '<input type="hidden" name="creditor" value="'.$creditor.'">';
320 320
     print '</td></tr>'."\n";
321 321
 
322 322
 	// Debitor
323 323
 
324
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("ThirdParty");
325
-	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$invoice->thirdparty->name.'</b>';
324
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("ThirdParty");
325
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$invoice->thirdparty->name.'</b>';
326 326
 
327 327
 	// Object
328 328
 
329
-	$text='<b>'.$langs->trans("PaymentInvoiceRef",$invoice->ref).'</b>';
330
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Designation");
331
-	print '</td><td class="CTableRow'.($var?'1':'2').'">'.$text;
332
-	print '<input type="hidden" name="source" value="'.GETPOST("source",'alpha').'">';
329
+	$text = '<b>'.$langs->trans("PaymentInvoiceRef", $invoice->ref).'</b>';
330
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation");
331
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text;
332
+	print '<input type="hidden" name="source" value="'.GETPOST("source", 'alpha').'">';
333 333
 	print '<input type="hidden" name="ref" value="'.$invoice->ref.'">';
334 334
 	print '</td></tr>'."\n";
335 335
 
@@ -338,51 +338,51 @@  discard block
 block discarded – undo
338 338
 // Payment on contract line
339 339
 if (GETPOST("source") == 'contractline')
340 340
 {
341
-	$found=true;
341
+	$found = true;
342 342
 	$langs->load("contracts");
343 343
 
344 344
 	require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
345 345
 
346
-	$contractline=new ContratLigne($db);
347
-	$result=$contractline->fetch('',$ref);
346
+	$contractline = new ContratLigne($db);
347
+	$result = $contractline->fetch('', $ref);
348 348
 	if ($result < 0)
349 349
 	{
350
-		$mesg=$contractline->error;
350
+		$mesg = $contractline->error;
351 351
 		$error++;
352 352
 	}
353 353
 	else
354 354
 	{
355 355
 		if ($contractline->fk_contrat > 0)
356 356
 		{
357
-			$contract=new Contrat($db);
358
-			$result=$contract->fetch($contractline->fk_contrat);
357
+			$contract = new Contrat($db);
358
+			$result = $contract->fetch($contractline->fk_contrat);
359 359
 			if ($result > 0)
360 360
 			{
361
-				$result=$contract->fetch_thirdparty($contract->socid);
361
+				$result = $contract->fetch_thirdparty($contract->socid);
362 362
 			}
363 363
 			else
364 364
 			{
365
-				$mesg=$contract->error;
365
+				$mesg = $contract->error;
366 366
 				$error++;
367 367
 			}
368 368
 		}
369 369
 		else
370 370
 		{
371
-			$mesg='ErrorRecordNotFound';
371
+			$mesg = 'ErrorRecordNotFound';
372 372
 			$error++;
373 373
 		}
374 374
 	}
375 375
 
376 376
     if ($action != 'dosign') // Do not change amount if we just click on first dosign
377 377
     {
378
-    	$amount=$contractline->total_ttc;
378
+    	$amount = $contractline->total_ttc;
379 379
     	if ($contractline->fk_product)
380 380
     	{
381
-    		$product=new Product($db);
382
-    		$result=$product->fetch($contractline->fk_product);
381
+    		$product = new Product($db);
382
+    		$result = $product->fetch($contractline->fk_product);
383 383
 
384 384
     		// We define price for product (TODO Put this in a method in product class)
385
-    		if (! empty($conf->global->PRODUIT_MULTIPRICES))
385
+    		if (!empty($conf->global->PRODUIT_MULTIPRICES))
386 386
     		{
387 387
     			$pu_ht = $product->multiprices[$contract->thirdparty->price_level];
388 388
     			$pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level];
@@ -395,92 +395,92 @@  discard block
 block discarded – undo
395 395
     			$price_base_type = $product->price_base_type;
396 396
     		}
397 397
 
398
-    		$amount=$pu_ttc;
398
+    		$amount = $pu_ttc;
399 399
     		if (empty($amount))
400 400
     		{
401
-    			dol_print_error('','ErrorNoPriceDefinedForThisProduct');
401
+    			dol_print_error('', 'ErrorNoPriceDefinedForThisProduct');
402 402
     			exit;
403 403
     		}
404 404
     	}
405
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
406
-        $amount=price2num($amount);
405
+        if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int');
406
+        $amount = price2num($amount);
407 407
     }
408 408
 
409
-	$qty=1;
410
-	if (GETPOST('qty')) $qty=GETPOST('qty');
409
+	$qty = 1;
410
+	if (GETPOST('qty')) $qty = GETPOST('qty');
411 411
 
412 412
 	// Creditor
413 413
 
414
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
415
-	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
414
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
415
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
416 416
     print '<input type="hidden" name="creditor" value="'.$creditor.'">';
417 417
 	print '</td></tr>'."\n";
418 418
 
419 419
 	// Debitor
420 420
 
421
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("ThirdParty");
422
-	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$contract->thirdparty->name.'</b>';
421
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("ThirdParty");
422
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$contract->thirdparty->name.'</b>';
423 423
 
424 424
 	// Object
425 425
 
426
-	$text='<b>'.$langs->trans("PaymentRenewContractId",$contract->ref,$contractline->ref).'</b>';
426
+	$text = '<b>'.$langs->trans("PaymentRenewContractId", $contract->ref, $contractline->ref).'</b>';
427 427
 	if ($contractline->fk_product)
428 428
 	{
429
-		$text.='<br>'.$product->ref.($product->label?' - '.$product->label:'');
429
+		$text .= '<br>'.$product->ref.($product->label ? ' - '.$product->label : '');
430 430
 	}
431
-	if ($contractline->description) $text.='<br>'.dol_htmlentitiesbr($contractline->description);
431
+	if ($contractline->description) $text .= '<br>'.dol_htmlentitiesbr($contractline->description);
432 432
 	//if ($contractline->date_fin_validite) {
433 433
 	//	$text.='<br>'.$langs->trans("DateEndPlanned").': ';
434 434
 	//	$text.=dol_print_date($contractline->date_fin_validite);
435 435
 	//}
436 436
 	if ($contractline->date_fin_validite)
437 437
 	{
438
-		$text.='<br>'.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite);
438
+		$text .= '<br>'.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite);
439 439
 	}
440 440
 
441
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Designation");
442
-	print '</td><td class="CTableRow'.($var?'1':'2').'">'.$text;
443
-	print '<input type="hidden" name="source" value="'.GETPOST("source",'alpha').'">';
441
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation");
442
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text;
443
+	print '<input type="hidden" name="source" value="'.GETPOST("source", 'alpha').'">';
444 444
 	print '<input type="hidden" name="ref" value="'.$contractline->ref.'">';
445 445
 	print '</td></tr>'."\n";
446 446
 
447 447
 	// Quantity
448 448
 
449
-	$label=$langs->trans("Quantity");
450
-	$qty=1;
451
-	$duration='';
449
+	$label = $langs->trans("Quantity");
450
+	$qty = 1;
451
+	$duration = '';
452 452
 	if ($contractline->fk_product)
453 453
 	{
454 454
 		if ($product->isService() && $product->duration_value > 0)
455 455
 		{
456
-			$label=$langs->trans("Duration");
456
+			$label = $langs->trans("Duration");
457 457
 
458 458
 			// TODO Put this in a global method
459 459
 			if ($product->duration_value > 1)
460 460
 			{
461
-				$dur=array("h"=>$langs->trans("Hours"),"d"=>$langs->trans("DurationDays"),"w"=>$langs->trans("DurationWeeks"),"m"=>$langs->trans("DurationMonths"),"y"=>$langs->trans("DurationYears"));
461
+				$dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("DurationDays"), "w"=>$langs->trans("DurationWeeks"), "m"=>$langs->trans("DurationMonths"), "y"=>$langs->trans("DurationYears"));
462 462
 			}
463 463
 			else
464 464
 			{
465
-				$dur=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("DurationDay"),"w"=>$langs->trans("DurationWeek"),"m"=>$langs->trans("DurationMonth"),"y"=>$langs->trans("DurationYear"));
465
+				$dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("DurationDay"), "w"=>$langs->trans("DurationWeek"), "m"=>$langs->trans("DurationMonth"), "y"=>$langs->trans("DurationYear"));
466 466
 			}
467
-			$duration=$product->duration_value.' '.$dur[$product->duration_unit];
467
+			$duration = $product->duration_value.' '.$dur[$product->duration_unit];
468 468
 		}
469 469
 	}
470
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$label.'</td>';
471
-	print '<td class="CTableRow'.($var?'1':'2').'"><b>'.($duration?$duration:$qty).'</b>';
470
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$label.'</td>';
471
+	print '<td class="CTableRow'.($var ? '1' : '2').'"><b>'.($duration ? $duration : $qty).'</b>';
472 472
 	print '<input type="hidden" name="newqty" value="'.dol_escape_htmltag($qty).'">';
473 473
 	print '</b></td></tr>'."\n";
474 474
 
475 475
 	// Amount
476 476
 
477
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Amount");
477
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount");
478 478
 	if (empty($amount)) print ' ('.$langs->trans("ToComplete").')';
479
-	print '</td><td class="CTableRow'.($var?'1':'2').'">';
480
-	if (empty($amount) || ! is_numeric($amount))
479
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">';
480
+	if (empty($amount) || !is_numeric($amount))
481 481
 	{
482
-        print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
483
-	    print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">';
482
+        print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">';
483
+	    print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount", "int").'">';
484 484
 	}
485 485
 	else {
486 486
 		print '<b>'.price($amount).'</b>';
@@ -497,56 +497,56 @@  discard block
 block discarded – undo
497 497
 // Payment on member subscription
498 498
 if (GETPOST("source") == 'membersubscription')
499 499
 {
500
-	$found=true;
500
+	$found = true;
501 501
 	$langs->load("members");
502 502
 
503 503
 	require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
504 504
 	require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
505 505
 
506
-	$member=new Adherent($db);
507
-	$result=$member->fetch('',$ref);
506
+	$member = new Adherent($db);
507
+	$result = $member->fetch('', $ref);
508 508
 	if ($result < 0)
509 509
 	{
510
-		$mesg=$member->error;
510
+		$mesg = $member->error;
511 511
 		$error++;
512 512
 	}
513 513
 	else
514 514
 	{
515
-		$subscription=new Subscription($db);
515
+		$subscription = new Subscription($db);
516 516
 	}
517 517
 
518 518
     if ($action != 'dosign') // Do not change amount if we just click on first dosign
519 519
     {
520
-    	$amount=$subscription->total_ttc;
521
-        if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int');
522
-        $amount=price2num($amount);
520
+    	$amount = $subscription->total_ttc;
521
+        if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int');
522
+        $amount = price2num($amount);
523 523
     }
524 524
 
525
-	$fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M');
526
-	if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; }
527
-	$fulltag=dol_string_unaccent($fulltag);
525
+	$fulltag = 'MEM='.$member->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M');
526
+	if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; }
527
+	$fulltag = dol_string_unaccent($fulltag);
528 528
 
529 529
 	// Creditor
530 530
 
531
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor");
532
-    print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>';
531
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor");
532
+    print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'.$creditor.'</b>';
533 533
     print '<input type="hidden" name="creditor" value="'.$creditor.'">';
534 534
     print '</td></tr>'."\n";
535 535
 
536 536
 	// Debitor
537 537
 
538
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Member");
539
-	print '</td><td class="CTableRow'.($var?'1':'2').'"><b>';
540
-	if ($member->morphy == 'mor' && ! empty($member->societe)) print $member->societe;
538
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Member");
539
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>';
540
+	if ($member->morphy == 'mor' && !empty($member->societe)) print $member->societe;
541 541
 	else print $member->getFullName($langs);
542 542
 	print '</b>';
543 543
 
544 544
 	// Object
545 545
 
546
-	$text='<b>'.$langs->trans("PaymentSubscription").'</b>';
547
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Designation");
548
-	print '</td><td class="CTableRow'.($var?'1':'2').'">'.$text;
549
-	print '<input type="hidden" name="source" value="'.GETPOST("source",'alpha').'">';
546
+	$text = '<b>'.$langs->trans("PaymentSubscription").'</b>';
547
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation");
548
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text;
549
+	print '<input type="hidden" name="source" value="'.GETPOST("source", 'alpha').'">';
550 550
 	print '<input type="hidden" name="ref" value="'.$member->ref.'">';
551 551
 	print '</td></tr>'."\n";
552 552
 
@@ -554,39 +554,39 @@  discard block
 block discarded – undo
554 554
 	{
555 555
 		// Last subscription date
556 556
 
557
-		print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("LastSubscriptionDate");
558
-		print '</td><td class="CTableRow'.($var?'1':'2').'">'.dol_print_date($member->last_subscription_date,'day');
557
+		print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("LastSubscriptionDate");
558
+		print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.dol_print_date($member->last_subscription_date, 'day');
559 559
 		print '</td></tr>'."\n";
560 560
 
561 561
 		// Last subscription amount
562 562
 
563
-		print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("LastSubscriptionAmount");
564
-		print '</td><td class="CTableRow'.($var?'1':'2').'">'.price($member->last_subscription_amount);
563
+		print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("LastSubscriptionAmount");
564
+		print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.price($member->last_subscription_amount);
565 565
 		print '</td></tr>'."\n";
566 566
 
567
-		if (empty($amount) && ! GETPOST('newamount')) $_GET['newamount']=$member->last_subscription_amount;
567
+		if (empty($amount) && !GETPOST('newamount')) $_GET['newamount'] = $member->last_subscription_amount;
568 568
 	}
569 569
 
570 570
 	// Amount
571 571
 
572
-	print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Amount");
572
+	print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount");
573 573
 	if (empty($amount))
574 574
 	{
575 575
 		print ' ('.$langs->trans("ToComplete");
576
-		if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>';
576
+		if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>';
577 577
 		print ')';
578 578
 	}
579
-	print '</td><td class="CTableRow'.($var?'1':'2').'">';
580
-	if (empty($amount) || ! is_numeric($amount))
579
+	print '</td><td class="CTableRow'.($var ? '1' : '2').'">';
580
+	if (empty($amount) || !is_numeric($amount))
581 581
 	{
582
-	    $valtoshow=GETPOST("newamount",'int');
583
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
584
-        print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">';
582
+	    $valtoshow = GETPOST("newamount", 'int');
583
+	    if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow);
584
+        print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">';
585 585
 	    print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">';
586 586
 	}
587 587
 	else {
588
-	    $valtoshow=$amount;
589
-	    if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow);
588
+	    $valtoshow = $amount;
589
+	    if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow);
590 590
 	    print '<b>'.price($valtoshow).'</b>';
591 591
         print '<input type="hidden" name="amount" value="'.$valtoshow.'">';
592 592
 		print '<input type="hidden" name="newamount" value="'.$valtoshow.'">';
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
 
602 602
 
603 603
 
604
-if (! $found && ! $mesg) $mesg=$langs->trans("ErrorBadParameters");
604
+if (!$found && !$mesg) $mesg = $langs->trans("ErrorBadParameters");
605 605
 
606 606
 if ($mesg) print '<tr><td align="center" colspan="2"><br><div class="warning">'.$mesg.'</div></td></tr>'."\n";
607 607
 
@@ -610,7 +610,7 @@  discard block
 block discarded – undo
610 610
 
611 611
 if ($action != 'dosign')
612 612
 {
613
-    if ($found && ! $error)	// We are in a management option and no error
613
+    if ($found && !$error)	// We are in a management option and no error
614 614
     {
615 615
 
616 616
 
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 print '<br>';
634 634
 
635 635
 
636
-htmlPrintOnlinePaymentFooter($mysoc,$langs);
636
+htmlPrintOnlinePaymentFooter($mysoc, $langs);
637 637
 
638 638
 llxFooter('', 'public');
639 639
 
Please login to merge, or discard this patch.
htdocs/public/members/public_card.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -152,7 +152,7 @@
 block discarded – undo
152 152
 */
153 153
 function llxFooterVierge()
154 154
 {
155
-    printCommonFooter('public');
155
+	printCommonFooter('public');
156 156
 
157 157
 	print "</body>\n";
158 158
 	print "</html>\n";
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -24,13 +24,13 @@  discard block
 block discarded – undo
24 24
  * 	\brief      File to show a public card of a member
25 25
  */
26 26
 
27
-define("NOLOGIN",1);		// This means this output page does not require to be logged.
28
-define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
27
+define("NOLOGIN", 1); // This means this output page does not require to be logged.
28
+define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
29 29
 
30 30
 // For MultiCompany module.
31 31
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
32 32
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
33
-$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
33
+$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
34 34
 if (is_numeric($entity)) define("DOLENTITY", $entity);
35 35
 
36 36
 require '../../main.inc.php';
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
40 40
 
41 41
 // Security check
42
-if (empty($conf->adherent->enabled)) accessforbidden('',0,0,1);
42
+if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1);
43 43
 
44 44
 
45 45
 $langs->load("main");
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 $langs->load("companies");
48 48
 $langs->load("other");
49 49
 
50
-$id=GETPOST('id','int');
50
+$id = GETPOST('id', 'int');
51 51
 $object = new Adherent($db);
52 52
 $extrafields = new ExtraFields($db);
53 53
 
@@ -65,19 +65,19 @@  discard block
 block discarded – undo
65 65
  * View
66 66
  */
67 67
 
68
-$morehead='';
69
-if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
70
-else $morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
68
+$morehead = '';
69
+if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
70
+else $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
71 71
 
72 72
 llxHeaderVierge($langs->trans("MemberCard"), $morehead);
73 73
 
74 74
 // fetch optionals attributes and labels
75
-$extralabels=$extrafields->fetch_name_optionals_label('adherent');
75
+$extralabels = $extrafields->fetch_name_optionals_label('adherent');
76 76
 if ($id > 0)
77 77
 {
78
-	$res=$object->fetch($id);
79
-	if ($res < 0) { dol_print_error($db,$object->error); exit; }
80
-	$res=$object->fetch_optionals($object->id,$extralabels);
78
+	$res = $object->fetch($id);
79
+	if ($res < 0) { dol_print_error($db, $object->error); exit; }
80
+	$res = $object->fetch_optionals($object->id, $extralabels);
81 81
 
82 82
 	print load_fiche_titre($langs->trans("MemberCard"), '', '');
83 83
 
@@ -98,9 +98,9 @@  discard block
 block discarded – undo
98 98
 		print '<tr><td>'.$langs->trans("Zip").' / '.$langs->trans("Town").'</td><td class="valeur">'.$object->zip.' '.$object->town.'&nbsp;</td></tr>';
99 99
 		print '<tr><td>'.$langs->trans("Country").'</td><td class="valeur">'.$object->country.'&nbsp;</td></tr>';
100 100
 		print '<tr><td>'.$langs->trans("EMail").'</td><td class="valeur">'.$object->email.'&nbsp;</td></tr>';
101
-		print '<tr><td>'.$langs->trans("Birthday").'</td><td class="valeur">'.dol_print_date($object->birth,'day').'</td></tr>';
101
+		print '<tr><td>'.$langs->trans("Birthday").'</td><td class="valeur">'.dol_print_date($object->birth, 'day').'</td></tr>';
102 102
 
103
-		if (isset($object->photo) && $object->photo !='')
103
+		if (isset($object->photo) && $object->photo != '')
104 104
 		{
105 105
 			$form = new Form($db);
106 106
 			print '<tr><td>URL Photo</td><td class="valeur">';
Please login to merge, or discard this patch.
Braces   +15 added lines, -7 removed lines patch added patch discarded remove patch
@@ -31,7 +31,9 @@  discard block
 block discarded – undo
31 31
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
32 32
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
33 33
 $entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
34
-if (is_numeric($entity)) define("DOLENTITY", $entity);
34
+if (is_numeric($entity)) {
35
+	define("DOLENTITY", $entity);
36
+}
35 37
 
36 38
 require '../../main.inc.php';
37 39
 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
@@ -39,7 +41,9 @@  discard block
 block discarded – undo
39 41
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
40 42
 
41 43
 // Security check
42
-if (empty($conf->adherent->enabled)) accessforbidden('',0,0,1);
44
+if (empty($conf->adherent->enabled)) {
45
+	accessforbidden('',0,0,1);
46
+}
43 47
 
44 48
 
45 49
 $langs->load("main");
@@ -66,8 +70,11 @@  discard block
 block discarded – undo
66 70
  */
67 71
 
68 72
 $morehead='';
69
-if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
70
-else $morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
73
+if (! empty($conf->global->MEMBER_PUBLIC_CSS)) {
74
+	$morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
75
+} else {
76
+	$morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
77
+}
71 78
 
72 79
 llxHeaderVierge($langs->trans("MemberCard"), $morehead);
73 80
 
@@ -84,8 +91,7 @@  discard block
 block discarded – undo
84 91
 	if (empty($object->public))
85 92
 	{
86 93
 		 print $langs->trans("ErrorThisMemberIsNotPublic");
87
-	}
88
-	else
94
+	} else
89 95
 	{
90 96
 		print '<table class="public_border" cellspacing="0" width="100%" cellpadding="3">';
91 97
 
@@ -140,7 +146,9 @@  discard block
 block discarded – undo
140 146
 	print "<html>\n";
141 147
 	print "<head>\n";
142 148
 	print "<title>".$title."</title>\n";
143
-	if ($head) print $head."\n";
149
+	if ($head) {
150
+		print $head."\n";
151
+	}
144 152
 	print "</head>\n";
145 153
 	print '<body class="public_body">'."\n";
146 154
 }
Please login to merge, or discard this patch.
htdocs/public/members/public_list.php 3 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -58,10 +58,10 @@  discard block
 block discarded – undo
58 58
 
59 59
 	header("Content-type: text/html; charset=".$conf->file->character_set_client);
60 60
 	print "<html>\n";
61
-    print "<head>\n";
62
-    print "<title>".$title."</title>\n";
63
-    if ($head) print $head."\n";
64
-    print "</head>\n";
61
+	print "<head>\n";
62
+	print "<title>".$title."</title>\n";
63
+	if ($head) print $head."\n";
64
+	print "</head>\n";
65 65
 	print '<body class="public_body">'."\n";
66 66
 }
67 67
 
@@ -72,9 +72,9 @@  discard block
 block discarded – undo
72 72
  */
73 73
 function llxFooterVierge()
74 74
 {
75
-    printCommonFooter('public');
75
+	printCommonFooter('public');
76 76
 
77
-    print "</body>\n";
77
+	print "</body>\n";
78 78
 	print "</html>\n";
79 79
 }
80 80
 
Please login to merge, or discard this patch.
Braces   +16 added lines, -9 removed lines patch added patch discarded remove patch
@@ -31,12 +31,16 @@  discard block
 block discarded – undo
31 31
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
32 32
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
33 33
 $entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
34
-if (is_numeric($entity)) define("DOLENTITY", $entity);
34
+if (is_numeric($entity)) {
35
+	define("DOLENTITY", $entity);
36
+}
35 37
 
36 38
 require '../../main.inc.php';
37 39
 
38 40
 // Security check
39
-if (empty($conf->adherent->enabled)) accessforbidden('',0,0,1);
41
+if (empty($conf->adherent->enabled)) {
42
+	accessforbidden('',0,0,1);
43
+}
40 44
 
41 45
 
42 46
 $langs->load("main");
@@ -60,7 +64,9 @@  discard block
 block discarded – undo
60 64
 	print "<html>\n";
61 65
     print "<head>\n";
62 66
     print "<title>".$title."</title>\n";
63
-    if ($head) print $head."\n";
67
+    if ($head) {
68
+    	print $head."\n";
69
+    }
64 70
     print "</head>\n";
65 71
 	print '<body class="public_body">'."\n";
66 72
 }
@@ -102,8 +108,11 @@  discard block
 block discarded – undo
102 108
 $form = new Form($db);
103 109
 
104 110
 $morehead='';
105
-if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
106
-else $morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
111
+if (! empty($conf->global->MEMBER_PUBLIC_CSS)) {
112
+	$morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
113
+} else {
114
+	$morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
115
+}
107 116
 
108 117
 llxHeaderVierge($langs->trans("ListOfValidatedPublicMembers"), $morehead);
109 118
 
@@ -155,8 +164,7 @@  discard block
 block discarded – undo
155 164
 			print '<td>';
156 165
 			print $form->showphoto('memberphoto', $objp, 64);
157 166
 			print '</td>'."\n";
158
-		}
159
-		else
167
+		} else
160 168
 		{
161 169
 			print "<td>&nbsp;</td>\n";
162 170
 		}
@@ -164,8 +172,7 @@  discard block
 block discarded – undo
164 172
 		$i++;
165 173
 	}
166 174
 	print "</table>";
167
-}
168
-else
175
+} else
169 176
 {
170 177
 	dol_print_error($db);
171 178
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -24,19 +24,19 @@  discard block
 block discarded – undo
24 24
  *  \brief      File sample to list members
25 25
  */
26 26
 
27
-define("NOLOGIN",1);		// This means this output page does not require to be logged.
28
-define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
27
+define("NOLOGIN", 1); // This means this output page does not require to be logged.
28
+define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
29 29
 
30 30
 // For MultiCompany module.
31 31
 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
32 32
 // TODO This should be useless. Because entity must be retreive from object ref and not from url.
33
-$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
33
+$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
34 34
 if (is_numeric($entity)) define("DOLENTITY", $entity);
35 35
 
36 36
 require '../../main.inc.php';
37 37
 
38 38
 // Security check
39
-if (empty($conf->adherent->enabled)) accessforbidden('',0,0,1);
39
+if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1);
40 40
 
41 41
 
42 42
 $langs->load("main");
@@ -79,20 +79,20 @@  discard block
 block discarded – undo
79 79
 }
80 80
 
81 81
 
82
-$sortfield = GETPOST("sortfield",'alpha');
83
-$sortorder = GETPOST("sortorder",'alpha');
84
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
85
-$page = GETPOST("page",'int');
82
+$sortfield = GETPOST("sortfield", 'alpha');
83
+$sortorder = GETPOST("sortorder", 'alpha');
84
+$limit = GETPOST('limit') ?GETPOST('limit', 'int') : $conf->liste_limit;
85
+$page = GETPOST("page", 'int');
86 86
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
87 87
 $offset = $limit * $page;
88 88
 $pageprev = $page - 1;
89 89
 $pagenext = $page + 1;
90 90
 
91
-$filter=GETPOST('filter');
92
-$statut=GETPOST('statut');
91
+$filter = GETPOST('filter');
92
+$statut = GETPOST('statut');
93 93
 
94
-if (! $sortorder) {  $sortorder="ASC"; }
95
-if (! $sortfield) {  $sortfield="lastname"; }
94
+if (!$sortorder) {  $sortorder = "ASC"; }
95
+if (!$sortfield) {  $sortfield = "lastname"; }
96 96
 
97 97
 
98 98
 /*
@@ -101,19 +101,19 @@  discard block
 block discarded – undo
101 101
 
102 102
 $form = new Form($db);
103 103
 
104
-$morehead='';
105
-if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead='<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
106
-else $morehead='<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
104
+$morehead = '';
105
+if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">';
106
+else $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php'.'">';
107 107
 
108 108
 llxHeaderVierge($langs->trans("ListOfValidatedPublicMembers"), $morehead);
109 109
 
110 110
 $sql = "SELECT rowid, firstname, lastname, societe, zip, town, email, birth, photo";
111
-$sql.= " FROM ".MAIN_DB_PREFIX."adherent";
112
-$sql.= " WHERE entity = ".$entity;
113
-$sql.= " AND statut = 1";
114
-$sql.= " AND public = 1";
115
-$sql.= $db->order($sortfield,$sortorder);
116
-$sql.= $db->plimit($conf->liste_limit+1, $offset);
111
+$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
112
+$sql .= " WHERE entity = ".$entity;
113
+$sql .= " AND statut = 1";
114
+$sql .= " AND public = 1";
115
+$sql .= $db->order($sortfield, $sortorder);
116
+$sql .= $db->plimit($conf->liste_limit + 1, $offset);
117 117
 //$sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, zip, town, d.email, t.libelle as type, d.morphy, d.statut, t.subscription";
118 118
 //$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t";
119 119
 //$sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = $statut";
@@ -125,21 +125,21 @@  discard block
 block discarded – undo
125 125
 	$num = $db->num_rows($result);
126 126
 	$i = 0;
127 127
 
128
-	$param="&statut=$statut&sortorder=$sortorder&sortfield=$sortfield";
128
+	$param = "&statut=$statut&sortorder=$sortorder&sortfield=$sortfield";
129 129
 	print_barre_liste($langs->trans("ListOfValidatedPublicMembers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, 0, '');
130 130
 	print '<table class="public_border" width="100%">';
131 131
 
132 132
 	print '<tr class="public_liste_titre">';
133
-	print '<td><a href="'.$_SERVER["PHP_SELF"].'?page='.$page.'&sortorder=ASC&sortfield=firstname">'.dolGetFirstLastname($langs->trans("Firstname"),$langs->trans("Lastname")).'</a></td>';
133
+	print '<td><a href="'.$_SERVER["PHP_SELF"].'?page='.$page.'&sortorder=ASC&sortfield=firstname">'.dolGetFirstLastname($langs->trans("Firstname"), $langs->trans("Lastname")).'</a></td>';
134 134
 	print '<td><a href="'.$_SERVER["PHP_SELF"].'?page='.$page.'&sortorder=ASC&sortfield=societe">'.$langs->trans("Company").'</a></td>'."\n";
135 135
 	//print_liste_field_titre("DateToBirth", $_SERVER["PHP_SELF"],"birth",'',$param,$sortfield,$sortorder); // est-ce nécessaire ??
136
-	print_liste_field_titre("EMail", $_SERVER["PHP_SELF"],"email",'',$param,'',$sortfield,$sortorder,'public_');
137
-	print_liste_field_titre("Zip", $_SERVER["PHP_SELF"],"zip","",$param,'',$sortfield,$sortorder,'public_');
138
-	print_liste_field_titre("Town", $_SERVER["PHP_SELF"],"town","",$param,'',$sortfield,$sortorder,'public_');
139
-	print_liste_field_titre("Photo", $_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder,'public_');
136
+	print_liste_field_titre("EMail", $_SERVER["PHP_SELF"], "email", '', $param, '', $sortfield, $sortorder, 'public_');
137
+	print_liste_field_titre("Zip", $_SERVER["PHP_SELF"], "zip", "", $param, '', $sortfield, $sortorder, 'public_');
138
+	print_liste_field_titre("Town", $_SERVER["PHP_SELF"], "town", "", $param, '', $sortfield, $sortorder, 'public_');
139
+	print_liste_field_titre("Photo", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'public_');
140 140
 	print "</tr>\n";
141 141
 
142
-	$var=True;
142
+	$var = True;
143 143
 	while ($i < $num && $i < $conf->liste_limit)
144 144
 	{
145 145
 		$objp = $db->fetch_object($result);
Please login to merge, or discard this patch.
htdocs/public/emailing/mailing-read.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@
 block discarded – undo
77 77
 
78 78
 	$resql=$db->query($sql);
79 79
 
80
-    //Update status communication of contact prospect
80
+	//Update status communication of contact prospect
81 81
 	$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=3 WHERE fk_stcomm != -1 AND rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.tag = '".$db->escape($tag)."' AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)";
82 82
 	dol_syslog("public/emailing/mailing-read.php : Mail read contact : ".$sql, LOG_DEBUG);
83 83
 
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -25,11 +25,11 @@  discard block
 block discarded – undo
25 25
  *      \brief      Script use to update mail status if destinaries read it (if images during mail read are display)
26 26
  */
27 27
 
28
-if (! defined('NOLOGIN'))        define("NOLOGIN",1);			// This means this output page does not require to be logged.
29
-if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
30
-if (! defined('NOCSRFCHECK'))    define('NOCSRFCHECK','1');		// Do not check anti CSRF attack test
31
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');	// Do not check anti POST attack test
32
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');	// If there is no need to load and show top and left menu
28
+if (!defined('NOLOGIN'))        define("NOLOGIN", 1); // This means this output page does not require to be logged.
29
+if (!defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN', '1');
30
+if (!defined('NOCSRFCHECK'))    define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
31
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
32
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
33 33
 
34 34
 /**
35 35
  * Header empty
@@ -47,8 +47,8 @@  discard block
 block discarded – undo
47 47
 
48 48
 require '../../main.inc.php';
49 49
 
50
-$tag=GETPOST('tag');
51
-$securitykey=GETPOST('securitykey');
50
+$tag = GETPOST('tag');
51
+$securitykey = GETPOST('securitykey');
52 52
 
53 53
 
54 54
 /*
@@ -63,25 +63,25 @@  discard block
 block discarded – undo
63 63
 	exit;
64 64
 }
65 65
 
66
-if (! empty($tag))
66
+if (!empty($tag))
67 67
 {
68
-	$statut='2';
68
+	$statut = '2';
69 69
 	$sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE tag='".$db->escape($tag)."'";
70 70
 	dol_syslog("public/emailing/mailing-read.php : Mail read : ".$sql, LOG_DEBUG);
71 71
 
72
-	$resql=$db->query($sql);
72
+	$resql = $db->query($sql);
73 73
 
74 74
 	//Update status communication of thirdparty prospect
75 75
 	$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=3 WHERE fk_stcomm != -1 AND rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE tag='".$db->escape($tag)."' AND source_type='thirdparty' AND source_id is not null)";
76 76
 	dol_syslog("public/emailing/mailing-read.php : Mail read thirdparty : ".$sql, LOG_DEBUG);
77 77
 
78
-	$resql=$db->query($sql);
78
+	$resql = $db->query($sql);
79 79
 
80 80
     //Update status communication of contact prospect
81 81
 	$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=3 WHERE fk_stcomm != -1 AND rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.tag = '".$db->escape($tag)."' AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)";
82 82
 	dol_syslog("public/emailing/mailing-read.php : Mail read contact : ".$sql, LOG_DEBUG);
83 83
 
84
-	$resql=$db->query($sql);
84
+	$resql = $db->query($sql);
85 85
 
86 86
 }
87 87
 
Please login to merge, or discard this patch.
Braces   +19 added lines, -5 removed lines patch added patch discarded remove patch
@@ -25,11 +25,25 @@
 block discarded – undo
25 25
  *      \brief      Script use to update mail status if destinaries read it (if images during mail read are display)
26 26
  */
27 27
 
28
-if (! defined('NOLOGIN'))        define("NOLOGIN",1);			// This means this output page does not require to be logged.
29
-if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
30
-if (! defined('NOCSRFCHECK'))    define('NOCSRFCHECK','1');		// Do not check anti CSRF attack test
31
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');	// Do not check anti POST attack test
32
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');	// If there is no need to load and show top and left menu
28
+if (! defined('NOLOGIN')) {
29
+	define("NOLOGIN",1);
30
+}
31
+// This means this output page does not require to be logged.
32
+if (! defined('NOREQUIRETRAN')) {
33
+	define('NOREQUIRETRAN','1');
34
+}
35
+if (! defined('NOCSRFCHECK')) {
36
+	define('NOCSRFCHECK','1');
37
+}
38
+// Do not check anti CSRF attack test
39
+if (! defined('NOTOKENRENEWAL')) {
40
+	define('NOTOKENRENEWAL','1');
41
+}
42
+// Do not check anti POST attack test
43
+if (! defined('NOREQUIREMENU')) {
44
+	define('NOREQUIREMENU','1');
45
+}
46
+// If there is no need to load and show top and left menu
33 47
 
34 48
 /**
35 49
  * Header empty
Please login to merge, or discard this patch.